From e0df2b2e84455c3f5a7aa7ee1c798b1dd1dc9d60 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 00:20:03 +0800 Subject: [PATCH 01/23] docs: design and OpenSpec change for the WhatsApp inbox Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../specs/2026-12-02-whatsapp-inbox-design.md | 200 ++++++++++++++++++ .../changes/add-whatsapp-inbox/.openspec.yaml | 2 + openspec/changes/add-whatsapp-inbox/design.md | 111 ++++++++++ .../changes/add-whatsapp-inbox/proposal.md | 40 ++++ .../specs/admin-visual-design/spec.md | 31 +++ .../specs/whatsapp-inbox/spec.md | 198 +++++++++++++++++ openspec/changes/add-whatsapp-inbox/tasks.md | 94 ++++++++ 7 files changed, 676 insertions(+) create mode 100644 docs/superpowers/specs/2026-12-02-whatsapp-inbox-design.md create mode 100644 openspec/changes/add-whatsapp-inbox/.openspec.yaml create mode 100644 openspec/changes/add-whatsapp-inbox/design.md create mode 100644 openspec/changes/add-whatsapp-inbox/proposal.md create mode 100644 openspec/changes/add-whatsapp-inbox/specs/admin-visual-design/spec.md create mode 100644 openspec/changes/add-whatsapp-inbox/specs/whatsapp-inbox/spec.md create mode 100644 openspec/changes/add-whatsapp-inbox/tasks.md diff --git a/docs/superpowers/specs/2026-12-02-whatsapp-inbox-design.md b/docs/superpowers/specs/2026-12-02-whatsapp-inbox-design.md new file mode 100644 index 0000000..d71f079 --- /dev/null +++ b/docs/superpowers/specs/2026-12-02-whatsapp-inbox-design.md @@ -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 `` being the company code: + - `WHATSAPP__PHONE_NUMBER_ID`; + - `WHATSAPP__WABA_ID`, the business account id used for templates; + - `WHATSAPP__ACCESS_TOKEN`, the system-user token; + - `WHATSAPP__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%. diff --git a/openspec/changes/add-whatsapp-inbox/.openspec.yaml b/openspec/changes/add-whatsapp-inbox/.openspec.yaml new file mode 100644 index 0000000..eb2b21e --- /dev/null +++ b/openspec/changes/add-whatsapp-inbox/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-12-02 diff --git a/openspec/changes/add-whatsapp-inbox/design.md b/openspec/changes/add-whatsapp-inbox/design.md new file mode 100644 index 0000000..32603b4 --- /dev/null +++ b/openspec/changes/add-whatsapp-inbox/design.md @@ -0,0 +1,111 @@ +## 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=//**` (`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__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 200 even if the service errors, logging only counts, because Meta retries and the service is idempotent. + 2. The service accepts each `entry.changes[].value` only when its `metadata.phone_number_id` belongs to one of the matched companies. + 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:///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. diff --git a/openspec/changes/add-whatsapp-inbox/proposal.md b/openspec/changes/add-whatsapp-inbox/proposal.md new file mode 100644 index 0000000..75b1eb1 --- /dev/null +++ b/openspec/changes/add-whatsapp-inbox/proposal.md @@ -0,0 +1,40 @@ +## Why + +Sales staff follow up event leads on WhatsApp from their own phones. Nothing is recorded, and nobody else can pick up a chat. The owner wants a two-way WhatsApp inbox inside Co-Lite on each company's business number. Meta business verification is done and the accounts are ready. The secrets are deployed to Kubernetes after the repository moves to solvway. + +## What Changes + +- A new service, `solvway-services-whatsapp`, with its own schema `service-whatsapp`. It owns conversations, messages, read markers, templates and the Meta Cloud API client. +- The Meta webhook comes in through mobile-api at `/api/public/whatsapp/webhook`. mobile-api answers the handshake, checks the signature, and passes events to the service. The service routes each event to its company by number. +- Automatic chat ownership from the lead's latest salesperson who has WhatsApp access. A WhatsApp Admin can reassign a chat, and that assignment sticks. Chats go back to the unassigned queue when the owner is disabled or loses access. +- Sending text inside the 24-hour window, and Meta-approved templates at any time. Templates are synced per company account. Staff can start a chat from a lead or event lead. +- Incoming images, documents, audio, video, stickers and locations can be viewed through an on-demand media proxy. Delivery ticks and failures are shown. +- New modules `BO_WHATSAPP` (own chats) and `BO_WHATSAPP_ADMIN` (all of the company's chats, routing, template sync). +- A portal Inbox page in the sidebar's Leads section, with an unread badge, and WhatsApp buttons on leads and event leads. +- A local `whatsapp-mock` container stands in for Meta's API, so the whole flow can be developed and tested without a Meta account. + +## Capabilities + +### New Capabilities + +- `whatsapp-inbox`: receiving and sending WhatsApp messages per company, ownership and routing, templates, media, and access. + +### Modified Capabilities + +- `admin-visual-design`: the Leads section of the sidebar lists the WhatsApp inbox. + +## Impact + +- **New:** + - the service module and its pom (no new third-party dependency); + - a `local/docker-compose.yml` entry for the service and the mock; + - a gateway route `Path=/whatsapp/**`; + - schema DDL and module seeds (SQL in this change folder; the local seed gets the same); + - environment settings per company, listed in `docs/deployment.md`. +- **Changed:** + - mobile-api: webhook, admin API, and a call from the user save path; + - counter: a lead lookup by mobile with its latest salesperson, and a notify call when an event lead's salesperson changes; + - gateway log redactor: masks the webhook's query and body; + - portal: inbox, sidebar, buttons, route modules. +- **Security:** a public webhook protected by Meta's HMAC signature, per-company secrets from the environment only, and no message content, phone numbers or tokens in logs. +- **Design:** `docs/superpowers/specs/2026-12-02-whatsapp-inbox-design.md`. diff --git a/openspec/changes/add-whatsapp-inbox/specs/admin-visual-design/spec.md b/openspec/changes/add-whatsapp-inbox/specs/admin-visual-design/spec.md new file mode 100644 index 0000000..7505862 --- /dev/null +++ b/openspec/changes/add-whatsapp-inbox/specs/admin-visual-design/spec.md @@ -0,0 +1,31 @@ +## MODIFIED Requirements + +### Requirement: Sidebar Sections + +The sidebar SHALL show Dashboard first, then the labelled sections Events, Leads, Access and System, each with a fixed set and order of pages. A page not in any section SHALL appear in a final section without a label. A section SHALL be marked by a divider and a small muted label, with only the divider in the collapsed rail, and SHALL NOT show when it has no page the user may open. Every page SHALL have a distinct icon. + +#### Scenario: WhatsApp inbox in the Leads section + +- **WHEN** a user with `BO_WHATSAPP` and two unread conversations opens the portal +- **THEN** the Leads section lists Leads, Interests and WhatsApp, with a badge showing 2 + +#### Scenario: Super admin sidebar + +- **WHEN** a super admin opens the portal +- **THEN** the sidebar shows Dashboard, then "Events" with Events and Event leads, "Leads" with Leads, Interests and WhatsApp, "Access" with Users, Roles and Login security, and "System" with Companies, Emails and Audit log + +#### Scenario: Staff without admin pages + +- **WHEN** a staff user who can open only Events and Event leads opens the portal +- **THEN** the sidebar shows only the "Events" section +- **AND** no "Leads", "Access" or "System" label + +#### Scenario: Unknown page + +- **WHEN** the server menu has a page that is not in the category map +- **THEN** it is listed after the System section, without a label + +#### Scenario: Collapsed rail + +- **WHEN** an admin collapses the sidebar to the icon rail +- **THEN** the sections are separated by dividers and no section label shows diff --git a/openspec/changes/add-whatsapp-inbox/specs/whatsapp-inbox/spec.md b/openspec/changes/add-whatsapp-inbox/specs/whatsapp-inbox/spec.md new file mode 100644 index 0000000..4e02500 --- /dev/null +++ b/openspec/changes/add-whatsapp-inbox/specs/whatsapp-inbox/spec.md @@ -0,0 +1,198 @@ +## ADDED Requirements + +### Requirement: Company WhatsApp settings + +The system SHALL read each company's WhatsApp number id, business account id, access token and app secret from the environment, and SHALL never store or log them. A company without complete settings SHALL have WhatsApp switched off. Its inbox SHALL say "WhatsApp is not configured", and the rest of the system SHALL keep working. + +#### Scenario: Company not configured + +- **GIVEN** CV has no WhatsApp settings +- **WHEN** a CV admin with `BO_WHATSAPP` opens the inbox +- **THEN** the page says "WhatsApp is not configured" and offers no composer + +### Requirement: Webhook handshake + +The public webhook SHALL answer Meta's subscription check with the given challenge only when the verify token matches the configured one. Otherwise it SHALL answer 403. + +#### Scenario: Wrong verify token + +- **WHEN** a subscription check arrives with a verify token that does not match +- **THEN** the webhook answers 403 and does not echo the challenge + +### Requirement: Webhook signature + +The webhook SHALL accept an event only when its `X-Hub-Signature-256` header is a valid HMAC-SHA256 of the raw body under the app secret of the company the event's number belongs to. A missing or invalid signature SHALL get 401, and nothing SHALL be stored. + +#### Scenario: Forged event + +- **WHEN** an event for INS's number arrives without a valid signature +- **THEN** the webhook answers 401 and no message is stored + +#### Scenario: Signed with the other company's secret + +- **GIVEN** INS and CV have different app secrets +- **WHEN** an event for INS's number is signed with CV's app secret +- **THEN** the event is rejected and no message is stored + +### Requirement: Inbound messages + +An accepted inbound message SHALL be stored once, in the conversation of the company that owns the receiving number, for the sender's WhatsApp number. Meta redelivering the same message id SHALL NOT create a second message. An event for a number no company owns SHALL be dropped. Receiving a message SHALL open the 24-hour reply window. + +#### Scenario: Lead writes to INS + +- **GIVEN** INS lead Aisyah has mobile `+60123456701` +- **WHEN** she sends "Hi, about the expo" to INS's number +- **THEN** an INS conversation for `60123456701` holds the message, linked to Aisyah's lead +- **AND** no CV user can see it + +#### Scenario: Redelivery + +- **WHEN** Meta delivers the same message id twice +- **THEN** the conversation holds the message once + +### Requirement: Delivery status + +The status of a sent message SHALL move only forward, from pending to sent to delivered to read, except that failed SHALL be recorded at any point, together with Meta's error code and title. The thread SHALL show the status as ticks, or as a failure with its reason. + +#### Scenario: Late delivered after read + +- **WHEN** a "read" status arrives and then a "delivered" status arrives for the same message +- **THEN** the message stays "read" + +#### Scenario: Send failed + +- **WHEN** Meta rejects a sent message +- **THEN** the thread shows the message as failed with Meta's error title + +### Requirement: Automatic ownership + +A conversation without a manual owner SHALL be owned by the lead's latest salesperson (the salesperson of its most recently captured event lead that has one) when that user is active and holds `BO_WHATSAPP`. Otherwise the current owner SHALL be kept while still active with `BO_WHATSAPP`, and the conversation SHALL be unassigned when not. Ownership SHALL be recomputed when the conversation is created and when an event lead of that lead is captured or changes salesperson. + +#### Scenario: Chat follows the latest salesperson + +- **GIVEN** Aisyah's latest event lead has salesperson `sales1`, who holds `BO_WHATSAPP` +- **WHEN** Aisyah writes for the first time +- **THEN** the conversation is owned by `sales1` + +#### Scenario: Latest event has no salesperson + +- **GIVEN** a conversation owned by `sales1` +- **WHEN** Aisyah is captured at a new event without a salesperson +- **THEN** the conversation stays with `sales1` + +#### Scenario: Salesperson without WhatsApp access + +- **GIVEN** Aisyah's latest salesperson `sales2` does not hold `BO_WHATSAPP` and the conversation has no owner +- **WHEN** ownership is recomputed +- **THEN** the conversation is unassigned + +#### Scenario: Unknown sender + +- **WHEN** a number with no lead in INS writes to INS +- **THEN** an unassigned conversation without a lead link is created + +### Requirement: Manual assignment + +A WhatsApp Admin SHALL be able to assign a conversation of their company to any active user of that company who holds `BO_WHATSAPP`, including themselves. A manual owner SHALL NOT change when event leads change. "Return to automatic" SHALL clear the manual owner and recompute it. + +#### Scenario: Manual owner sticks + +- **GIVEN** a WhatsApp Admin assigned Aisyah's conversation to `sales3` +- **WHEN** Aisyah is captured at a new event with salesperson `sales1` +- **THEN** the conversation stays with `sales3` + +#### Scenario: Owner outside WhatsApp + +- **WHEN** a WhatsApp Admin tries to assign a conversation to a user without `BO_WHATSAPP` +- **THEN** the request is refused and the owner does not change + +### Requirement: Owner loses access + +When a user is disabled, or their roles no longer grant `BO_WHATSAPP`, the system SHALL make their conversations unassigned and clear any manual assignment. A user locked out by failed logins SHALL keep their conversations. + +#### Scenario: Owner disabled + +- **GIVEN** `sales1` owns three conversations +- **WHEN** an admin disables `sales1` +- **THEN** the three conversations are unassigned + +### Requirement: Inbox access + +A user with `BO_WHATSAPP` SHALL see, read and reply only in conversations they own. A user with `BO_WHATSAPP_ADMIN` SHALL see every conversation of their company, including unassigned ones, and SHALL be able to read and reply in any of them. A super admin SHALL see the conversations of every company. Every request SHALL be limited to the caller's company, and SHALL fail closed when the caller's company cannot be determined. + +#### Scenario: Staff opens someone else's chat + +- **WHEN** `sales1` requests a conversation owned by `sales3` +- **THEN** the request answers 404 + +#### Scenario: WhatsApp Admin sees the queue + +- **WHEN** an INS WhatsApp Admin opens the Unassigned tab +- **THEN** it lists INS's unassigned conversations and none of CV's + +### Requirement: Replies inside the 24-hour window + +A user SHALL be able to send a text message only while less than 24 hours have passed since the contact's last inbound message. Outside the window a text send SHALL be refused with "The 24-hour window has closed. Send a template." The composer SHALL show the window's state and offer only templates when the window is closed. + +#### Scenario: Window closed + +- **GIVEN** Aisyah last wrote 25 hours ago +- **WHEN** `sales1` sends a text reply +- **THEN** it is refused and nothing is sent to Meta + +### Requirement: Templates + +A WhatsApp Admin SHALL be able to sync a company's approved templates from that company's business account, and the system SHALL also sync them nightly. Staff SHALL be able to send a synced template with every body parameter filled, inside or outside the window. Templates whose header or buttons need parameters SHALL be listed as not supported and SHALL NOT be sendable. + +#### Scenario: Missing parameter + +- **WHEN** a user sends template `expo_followup` with one of its two parameters empty +- **THEN** it is refused and nothing is sent to Meta + +### Requirement: Starting a chat from a lead + +A user with `BO_WHATSAPP` SHALL be able to start a chat from a lead or event lead that has a mobile number, in that lead's company. If the conversation has no owner it SHALL become the starter's as a manual assignment. If another user owns it, the starter SHALL be told who owns it. Until the contact replies, only templates SHALL be offered. + +#### Scenario: Start an unowned chat + +- **GIVEN** Aisyah has no conversation yet and no salesperson with WhatsApp +- **WHEN** `sales1` presses WhatsApp on her event lead +- **THEN** a conversation owned by `sales1` opens with the template composer + +### Requirement: Incoming media + +Incoming images, documents, audio, video, stickers and locations SHALL be shown in the thread. Media SHALL be fetched from Meta only when a user with access opens it. Media that Meta no longer holds SHALL show "Media expired". + +#### Scenario: Image opened by someone without access + +- **WHEN** a user who cannot see the conversation requests one of its images +- **THEN** the request answers 404 + +### Requirement: Unread counts + +The system SHALL track, per user, the last message they read in each conversation they can see. It SHALL show unread conversations in the list and the number of unread conversations as a badge on the sidebar's inbox item. + +#### Scenario: Reading clears the badge + +- **GIVEN** `sales1` has one unread conversation +- **WHEN** `sales1` opens it +- **THEN** the sidebar badge clears + +### Requirement: WhatsApp audit and privacy + +Sending a message, reassigning a conversation and syncing templates SHALL be recorded in the audit log with the conversation and template names but not the message text. Message text, phone numbers, media, tokens and signatures SHALL NOT be written to application logs. + +#### Scenario: Template send audited + +- **WHEN** `sales1` sends template `expo_followup` +- **THEN** the audit log records the send by `sales1` with the conversation and template name +- **AND** not the filled-in text + +### Requirement: Local Meta stand-in + +The local stack SHALL include a test-only stand-in for Meta's API. It SHALL accept sends, serve templates and media, and post signed inbound events to the webhook on request, so the inbox can be developed and tested without a Meta account. The stand-in SHALL NOT be part of any release. + +#### Scenario: Simulated inbound message + +- **WHEN** a developer asks the stand-in to deliver "Hello" from `+60123456701` to INS's number +- **THEN** the INS inbox shows the message within one polling interval diff --git a/openspec/changes/add-whatsapp-inbox/tasks.md b/openspec/changes/add-whatsapp-inbox/tasks.md new file mode 100644 index 0000000..d588344 --- /dev/null +++ b/openspec/changes/add-whatsapp-inbox/tasks.md @@ -0,0 +1,94 @@ +# Tasks: add-whatsapp-inbox + +Design: `design.md` and `docs/superpowers/specs/2026-12-02-whatsapp-inbox-design.md`. Every task is TDD, followed by the review gate (an Opus reviewer). At most 2 workers run at once (owner, 2026-12-01). Waves list tasks that may run in parallel in separate worktrees. Everything else runs serially in order. + +Verify commands: +- **Backend:** `mvn -T 1C -q -pl verify` (`-T 0.5C` while a wave builds at the same time). +- **Portal:** `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint` (check the vitest exit code). + +## Wave 1 (serial: contracts and hotspots) + +- [ ] 1.1 Schema and modules: `sql/01-whatsapp-schema.sql`, `sql/02-whatsapp-modules.sql` and `sql/99-rollback.sql` in this change folder, mirrored into `local/seed/`. + - Depends on: none + - Scope: `openspec/changes/add-whatsapp-inbox/sql/**`, `local/seed/**` + - Verify: load the seed into a fresh local MySQL volume (compose `down -v` on a throwaway project name, then `up mysql`) and list the tables. +- [ ] 1.2 Service skeleton: `solvway-services-whatsapp` module (pom, Dockerfile, `application.yml`, settings binding, health), root pom module entry, the gateway route `Path=/whatsapp/**`, and compose entries for the service and `whatsapp-mock`. The mock is a skeleton that answers health. + - Depends on: 1.1 + - Scope: `solvway-services-whatsapp/**`, `pom.xml`, `solvway-api-gateway/src/main/resources/application.yml`, `local/docker-compose.yml`, `local/whatsapp-mock/**`, `local/.env.example` + - Verify: `mvn -T 1C -q -pl solvway-services-whatsapp,solvway-api-gateway verify` +- [ ] 1.3 Shared DTOs and API constants: the webhook ingest body, conversation and message views, and `RestApiWhatsappServiceConstants` in mobile-api. + - Depends on: 1.2 + - Scope: `solvway-services-whatsapp/src/main/java/**/dto/**`, `solvway-mobile-api/src/main/java/**/constant/api/RestApiWhatsappServiceConstants.java`, `solvway-mobile-api/src/main/java/**/dto/whatsapp/**` + - Verify: `mvn -T 1C -q -pl solvway-services-whatsapp,solvway-mobile-api verify` + +## Wave 2 (parallel: 2.1 and 2.2) + +- [ ] 2.1 Service ingest: + - number-to-company routing restricted to the matched companies; + - conversation upsert and the message insert, idempotent on `wamid`; + - the status ranking; + - `last_inbound_at`. + - Depends on: 1.3 + - Scope: `solvway-services-whatsapp/src/main/java/**` except `meta/**` and `dto/**`, `solvway-services-whatsapp/src/test/**` + - Verify: `mvn -T 0.5C -q -pl solvway-services-whatsapp verify` +- [ ] 2.2 Counter lead lookup: `GET /counter/lead/whatsappContact` (newest lead by mobile, its latest salesperson), and the best-effort `leadChanged` notify on the event lead save paths (capture, salesperson change). + - Depends on: 1.3 + - Scope: `solvway-services-counter/**` + - Verify: `mvn -T 0.5C -q -pl solvway-services-counter verify` + +## Wave 3 (parallel: 3.1 and 3.2) + +- [ ] 3.1 mobile-api webhook: the GET handshake, the POST raw-body HMAC against each company secret, forwarding to ingest, the per-IP limit, the public-route exemptions, and `LogRedactor` masking for the webhook query. + - Depends on: 2.1 + - Scope: `solvway-mobile-api/src/main/java/**/whatsapp/**`, `solvway-mobile-api/src/main/java/**/controller/PublicWhatsApp*`, `solvway-mobile-api/src/test/**/whatsapp/**`, `solvway-api-gateway/src/main/java/**/LogRedactor.java`, `solvway-api-gateway/src/test/**/LogRedactorTest.java`, and the public-path exemption config (security code: also read the whole diff in the controller check) + - Verify: `mvn -T 0.5C -q -pl solvway-mobile-api,solvway-api-gateway verify` +- [ ] 3.2 Service ownership: `OwnershipService.recompute`, the user access check, the `leadChanged` and `userChanged` endpoints, manual assign and automatic return, and the nightly job. + - Depends on: 2.1, 2.2 + - Scope: `solvway-services-whatsapp/src/main/java/**/ownership/**`, `solvway-services-whatsapp/src/main/java/**/job/**`, `solvway-services-whatsapp/src/test/**/ownership/**` + - Verify: `mvn -T 0.5C -q -pl solvway-services-whatsapp verify` + +## Wave 4 (serial) + +- [ ] 4.1 Meta client and sending: text inside the window, templates with parameter validation, template sync per company, the media proxy, error mapping to failed, and "not configured". The mock gains the Graph endpoints and `/simulate/inbound`. + - Depends on: 3.2 + - Scope: `solvway-services-whatsapp/**`, `local/whatsapp-mock/**` + - Verify: `mvn -T 1C -q -pl solvway-services-whatsapp verify` +- [ ] 4.2 mobile-api admin API: every endpoint in design decision 9, module checks, company scoping (fail closed), audit, and the `userChanged` call from the user save path. + - Depends on: 4.1 + - Scope: `solvway-mobile-api/**` (security code: also read the whole diff in the controller check) + - Verify: `mvn -T 1C -q -pl solvway-mobile-api verify` + +## Wave 5 (parallel: 5.1 and 5.2) + +- [ ] 5.1 Portal inbox: + - the `/whatsapp` page, with list tabs, search, thread, bubbles and ticks, the window state, the composer and template picker, media rendering, and assign controls for admins; + - polling; + - proxies under `app/api/admin/whatsapp/**`; + - `routeModules`. + - Depends on: 4.2 + - Scope: `solvway-admin-portal/app/whatsapp/**`, `solvway-admin-portal/app/api/admin/whatsapp/**`, `solvway-admin-portal/app/components/whatsapp/**`, `solvway-admin-portal/app/lib/services/whatsapp*`, `solvway-admin-portal/app/lib/routeModules*` + - Verify: portal verify +- [ ] 5.2 Portal sidebar and buttons: + - `BO_WHATSAPP` in the Leads section with `MessageCircle` and the unread badge; + - WhatsApp buttons on leads and event leads rows and phone cards (start chat; told who owns it when someone else does). + - Depends on: 4.2 + - Scope: `solvway-admin-portal/app/lib/aclSidebar*`, `solvway-admin-portal/app/components/app/**`, `solvway-admin-portal/app/leads/**`, `solvway-admin-portal/app/event-leads/**`, `solvway-admin-portal/app/lib/i18n/defaultMessages.ts` + - Verify: portal verify (5.1 adds its keys to `defaultMessages.ts` after 5.2 is integrated, to avoid a hotspot clash) + +## Wave 6 (serial: release) + +- [ ] 6.1 `docs/deployment.md`: the environment per company, the SQL order, the Meta setup steps (webhook URL, verify token, `messages` subscription, templates), and granting the modules. +- [ ] 6.2 Live check on the local stack with the mock: + - inbound for INS and CV, kept apart; + - an unknown sender; + - automatic owner, and manual reassign that sticks; + - a disabled owner going to unassigned; + - a text reply inside the window and refused outside; + - template send with a missing parameter refused; + - start a chat from an event lead; + - media viewed; + - a failed send shown; + - the unread badge. + + Use Playwright at 1280 and 360 px. +- [ ] 6.3 The owner's manual click-every-button e2e on a production build covers the inbox too (record the result here). -- 2.54.1 From 6e5362fa2c17e803a8e4a3d31c99b5eb53378661 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 00:53:04 +0800 Subject: [PATCH 02/23] feat: WhatsApp inbox schema and modules Adds schema service-whatsapp (wa_conversation, wa_message, wa_read, wa_template), modules BO_WHATSAPP and BO_WHATSAPP_ADMIN, the rollback, and the local seed mirror. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../specs/2026-12-02-whatsapp-inbox-design.md | 2 +- local/seed/00-schemas.sql | 1 + local/seed/03-colite.sql | 81 +++++++++++++++++++ .../sql/01-whatsapp-schema.sql | 78 ++++++++++++++++++ .../sql/02-whatsapp-modules.sql | 9 +++ .../add-whatsapp-inbox/sql/99-rollback.sql | 6 ++ 6 files changed, 176 insertions(+), 1 deletion(-) create mode 100644 openspec/changes/add-whatsapp-inbox/sql/01-whatsapp-schema.sql create mode 100644 openspec/changes/add-whatsapp-inbox/sql/02-whatsapp-modules.sql create mode 100644 openspec/changes/add-whatsapp-inbox/sql/99-rollback.sql diff --git a/docs/superpowers/specs/2026-12-02-whatsapp-inbox-design.md b/docs/superpowers/specs/2026-12-02-whatsapp-inbox-design.md index d71f079..02b77b2 100644 --- a/docs/superpowers/specs/2026-12-02-whatsapp-inbox-design.md +++ b/docs/superpowers/specs/2026-12-02-whatsapp-inbox-design.md @@ -82,7 +82,7 @@ All of these come from the environment, with none committed. Each company has it 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`) +### Data (schema `service-whatsapp`; conversations and templates carry `company_id`, messages and read markers inherit it through `conversation_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`. diff --git a/local/seed/00-schemas.sql b/local/seed/00-schemas.sql index 30d2787..a9920ef 100644 --- a/local/seed/00-schemas.sql +++ b/local/seed/00-schemas.sql @@ -4,3 +4,4 @@ CREATE DATABASE IF NOT EXISTS `service-counter` CHARACTER SET utf8mb4; CREATE DATABASE IF NOT EXISTS `service-member` CHARACTER SET utf8mb4; CREATE DATABASE IF NOT EXISTS `service-log` CHARACTER SET utf8mb4; CREATE DATABASE IF NOT EXISTS `service-email` CHARACTER SET utf8mb4; +CREATE DATABASE IF NOT EXISTS `service-whatsapp` CHARACTER SET utf8mb4; diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index 99553eb..98a43a9 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -347,3 +347,84 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic -- polish-e2e-followups/sql/01-soft-delete.sql ALTER TABLE `service-counter`.`interest` ADD COLUMN `deleted_at` datetime NULL; ALTER TABLE `service-system`.`role` ADD COLUMN `deleted_at` datetime NULL; +-- add-whatsapp-inbox/sql/01-whatsapp-schema.sql +CREATE DATABASE IF NOT EXISTS `service-whatsapp` CHARACTER SET utf8mb4; +USE `service-whatsapp`; + +CREATE TABLE `wa_conversation` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `uuid` varchar(36) NOT NULL, + `company_id` bigint NOT NULL, + `phone_number_id` varchar(32) NOT NULL, + `contact_wa_id` varchar(20) NOT NULL COMMENT 'E.164 digits, no leading +', + `contact_name` varchar(255) NULL, + `lead_uuid` bigint NULL, + `owner_user_id` bigint NULL, + `owner_manual` boolean NOT NULL DEFAULT false, + `last_inbound_at` datetime NULL, + `last_message_at` datetime NULL, + `last_message_preview` varchar(80) NULL, + `created_at` datetime NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_wa_conversation_uuid` (`uuid`), + UNIQUE KEY `uk_wa_conversation_contact` (`company_id`, `contact_wa_id`), + KEY `idx_wa_conversation_owner` (`company_id`, `owner_user_id`, `last_message_at`), + KEY `idx_wa_conversation_last_message` (`company_id`, `last_message_at`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE `wa_message` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `uuid` varchar(36) NOT NULL, + `conversation_id` bigint NOT NULL, + `direction` varchar(3) NOT NULL COMMENT 'IN | OUT', + `wamid` varchar(128) NULL COMMENT 'NULL while an OUT message is pending, before Meta answers', + `type` varchar(16) NOT NULL COMMENT 'text | template | image | document | audio | video | sticker | location | unsupported', + `body` text NULL, + `template_name` varchar(255) NULL, + `media_id` varchar(128) NULL, + `media_mime` varchar(128) NULL, + `media_filename` varchar(255) NULL, + `location_lat` decimal(10,7) NULL, + `location_lng` decimal(10,7) NULL, + `location_name` varchar(255) NULL, + `status` varchar(16) NULL COMMENT 'OUT only: pending | sent | delivered | read | failed', + `error_code` varchar(32) NULL, + `error_title` varchar(255) NULL, + `sent_by_user_id` bigint NULL, + `created_at` datetime NOT NULL, + `status_at` datetime NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_wa_message_uuid` (`uuid`), + UNIQUE KEY `uk_wa_message_wamid` (`wamid`), + KEY `idx_wa_message_conversation` (`conversation_id`, `id`), + CONSTRAINT `fk_wa_message_conversation` FOREIGN KEY (`conversation_id`) REFERENCES `wa_conversation` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE `wa_read` ( + `conversation_id` bigint NOT NULL, + `user_id` bigint NOT NULL, + `last_read_message_id` bigint NOT NULL, + PRIMARY KEY (`conversation_id`, `user_id`), + CONSTRAINT `fk_wa_read_conversation` FOREIGN KEY (`conversation_id`) REFERENCES `wa_conversation` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE `wa_template` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `company_id` bigint NOT NULL, + `name` varchar(255) NOT NULL, + `language` varchar(16) NOT NULL, + `category` varchar(32) NULL, + `status` varchar(32) NOT NULL, + `body_text` text NULL, + `param_count` int NOT NULL DEFAULT 0, + `synced_at` datetime NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_wa_template` (`company_id`, `name`, `language`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- add-whatsapp-inbox/sql/02-whatsapp-modules.sql +USE `service-system`; + +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (41200000, 'BO_WHATSAPP', 'WhatsApp', 'BO', 'M', 40000000, '/whatsapp', 'MessageCircle'), + (41300000, 'BO_WHATSAPP_ADMIN', 'WhatsApp admin', 'BO', 'M', 40000000, NULL, NULL); diff --git a/openspec/changes/add-whatsapp-inbox/sql/01-whatsapp-schema.sql b/openspec/changes/add-whatsapp-inbox/sql/01-whatsapp-schema.sql new file mode 100644 index 0000000..d6a10a1 --- /dev/null +++ b/openspec/changes/add-whatsapp-inbox/sql/01-whatsapp-schema.sql @@ -0,0 +1,78 @@ +-- Co-Lite change add-whatsapp-inbox: the WhatsApp inbox schema. +-- Target: new schema `service-whatsapp`. Additive only. Run once, after the release package. +-- DDL: run with a user that may create databases and tables, not the services' user. +-- company_id, owner_user_id, sent_by_user_id and user_id point at `service-system`; lead_uuid at `service-counter`.`lead`.`uuid`; no foreign keys across schemas. +-- direction (IN | OUT), type and status are varchar, not ENUM, like the rest of the repo. +CREATE DATABASE IF NOT EXISTS `service-whatsapp` CHARACTER SET utf8mb4; +USE `service-whatsapp`; + +CREATE TABLE `wa_conversation` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `uuid` varchar(36) NOT NULL, + `company_id` bigint NOT NULL, + `phone_number_id` varchar(32) NOT NULL, + `contact_wa_id` varchar(20) NOT NULL COMMENT 'E.164 digits, no leading +', + `contact_name` varchar(255) NULL, + `lead_uuid` bigint NULL, + `owner_user_id` bigint NULL, + `owner_manual` boolean NOT NULL DEFAULT false, + `last_inbound_at` datetime NULL, + `last_message_at` datetime NULL, + `last_message_preview` varchar(80) NULL, + `created_at` datetime NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_wa_conversation_uuid` (`uuid`), + UNIQUE KEY `uk_wa_conversation_contact` (`company_id`, `contact_wa_id`), + KEY `idx_wa_conversation_owner` (`company_id`, `owner_user_id`, `last_message_at`), + KEY `idx_wa_conversation_last_message` (`company_id`, `last_message_at`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE `wa_message` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `uuid` varchar(36) NOT NULL, + `conversation_id` bigint NOT NULL, + `direction` varchar(3) NOT NULL COMMENT 'IN | OUT', + `wamid` varchar(128) NULL COMMENT 'NULL while an OUT message is pending, before Meta answers', + `type` varchar(16) NOT NULL COMMENT 'text | template | image | document | audio | video | sticker | location | unsupported', + `body` text NULL, + `template_name` varchar(255) NULL, + `media_id` varchar(128) NULL, + `media_mime` varchar(128) NULL, + `media_filename` varchar(255) NULL, + `location_lat` decimal(10,7) NULL, + `location_lng` decimal(10,7) NULL, + `location_name` varchar(255) NULL, + `status` varchar(16) NULL COMMENT 'OUT only: pending | sent | delivered | read | failed', + `error_code` varchar(32) NULL, + `error_title` varchar(255) NULL, + `sent_by_user_id` bigint NULL, + `created_at` datetime NOT NULL, + `status_at` datetime NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_wa_message_uuid` (`uuid`), + UNIQUE KEY `uk_wa_message_wamid` (`wamid`), + KEY `idx_wa_message_conversation` (`conversation_id`, `id`), + CONSTRAINT `fk_wa_message_conversation` FOREIGN KEY (`conversation_id`) REFERENCES `wa_conversation` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE `wa_read` ( + `conversation_id` bigint NOT NULL, + `user_id` bigint NOT NULL, + `last_read_message_id` bigint NOT NULL, + PRIMARY KEY (`conversation_id`, `user_id`), + CONSTRAINT `fk_wa_read_conversation` FOREIGN KEY (`conversation_id`) REFERENCES `wa_conversation` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE `wa_template` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `company_id` bigint NOT NULL, + `name` varchar(255) NOT NULL, + `language` varchar(16) NOT NULL, + `category` varchar(32) NULL, + `status` varchar(32) NOT NULL, + `body_text` text NULL, + `param_count` int NOT NULL DEFAULT 0, + `synced_at` datetime NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_wa_template` (`company_id`, `name`, `language`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/openspec/changes/add-whatsapp-inbox/sql/02-whatsapp-modules.sql b/openspec/changes/add-whatsapp-inbox/sql/02-whatsapp-modules.sql new file mode 100644 index 0000000..ed20464 --- /dev/null +++ b/openspec/changes/add-whatsapp-inbox/sql/02-whatsapp-modules.sql @@ -0,0 +1,9 @@ +-- Co-Lite change add-whatsapp-inbox: the WhatsApp inbox and WhatsApp admin back-office modules (area BO). +-- Target: `service-system`.`module`. Additive only. Run once, after the release package. +-- No role grant: super admins see every module; they grant BO_WHATSAPP and BO_WHATSAPP_ADMIN to other roles under Roles. +-- BO_WHATSAPP_ADMIN has no url and no icon (like BO_EVENT_GUESTS), so it stays out of the sidebar and only gates actions. +USE `service-system`; + +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (41200000, 'BO_WHATSAPP', 'WhatsApp', 'BO', 'M', 40000000, '/whatsapp', 'MessageCircle'), + (41300000, 'BO_WHATSAPP_ADMIN', 'WhatsApp admin', 'BO', 'M', 40000000, NULL, NULL); diff --git a/openspec/changes/add-whatsapp-inbox/sql/99-rollback.sql b/openspec/changes/add-whatsapp-inbox/sql/99-rollback.sql new file mode 100644 index 0000000..e641053 --- /dev/null +++ b/openspec/changes/add-whatsapp-inbox/sql/99-rollback.sql @@ -0,0 +1,6 @@ +-- Co-Lite change add-whatsapp-inbox: rollback of 01-02. Destroys every stored WhatsApp conversation and message. +USE `service-system`; +DELETE FROM `modules_roles` WHERE `module_id` IN (41200000, 41300000); +DELETE FROM `module` WHERE `id` IN (41200000, 41300000); + +DROP DATABASE IF EXISTS `service-whatsapp`; -- 2.54.1 From 3ac3e108ff0256c35acbc79829ae053043edc683 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 01:09:59 +0800 Subject: [PATCH 03/23] feat: WhatsApp service skeleton, settings, gateway route and mock Adds solvway-services-whatsapp with per-company WhatsApp settings (secrets masked), the gateway route /whatsapp/**, compose entries for the service and a local whatsapp-mock, the example env keys, and the service in CI. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .gitea/workflows/ci.yml | 3 +- local/.env.example | 12 +++ local/docker-compose.yml | 9 +++ local/whatsapp-mock/Dockerfile | 6 ++ local/whatsapp-mock/server.js | 11 +++ openspec/changes/add-whatsapp-inbox/tasks.md | 4 +- pom.xml | 1 + .../src/main/resources/application.yml | 5 ++ solvway-services-whatsapp/.dockerignore | 3 + solvway-services-whatsapp/.gitignore | 4 + solvway-services-whatsapp/Dockerfile | 8 ++ solvway-services-whatsapp/pom.xml | 54 ++++++++++++++ .../SolvwayServicesWhatsappApplication.java | 12 +++ .../whatsapp/config/WhatsAppSettings.java | 74 +++++++++++++++++++ .../src/main/resources/application-local.yml | 1 + .../src/main/resources/application.yml | 34 +++++++++ .../whatsapp/config/WhatsAppSettingsTest.java | 71 ++++++++++++++++++ 17 files changed, 309 insertions(+), 3 deletions(-) create mode 100644 local/whatsapp-mock/Dockerfile create mode 100644 local/whatsapp-mock/server.js create mode 100644 solvway-services-whatsapp/.dockerignore create mode 100644 solvway-services-whatsapp/.gitignore create mode 100644 solvway-services-whatsapp/Dockerfile create mode 100644 solvway-services-whatsapp/pom.xml create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/SolvwayServicesWhatsappApplication.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/config/WhatsAppSettings.java create mode 100644 solvway-services-whatsapp/src/main/resources/application-local.yml create mode 100644 solvway-services-whatsapp/src/main/resources/application.yml create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/config/WhatsAppSettingsTest.java diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 9e9c9f9..3c2b2a1 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -41,6 +41,7 @@ jobs: service-member:solvway-services-member service-log:solvway-services-log service-email:solvway-services-email + service-whatsapp:solvway-services-whatsapp admin-portal:solvway-admin-portal steps: - name: Checkout @@ -49,7 +50,7 @@ jobs: - name: Build and test the services run: | mvn -T 1C -B -Dmaven.repo.local=/root/.m2/repository-co-lite verify \ - -pl solvway-api-gateway,solvway-mobile-api,solvway-services-auth,solvway-services-system,solvway-services-counter,solvway-services-member,solvway-services-log,solvway-services-email -am + -pl solvway-api-gateway,solvway-mobile-api,solvway-services-auth,solvway-services-system,solvway-services-counter,solvway-services-member,solvway-services-log,solvway-services-email,solvway-services-whatsapp -am - name: Registry login env: diff --git a/local/.env.example b/local/.env.example index 4f33232..c1bd500 100644 --- a/local/.env.example +++ b/local/.env.example @@ -18,3 +18,15 @@ APIKEY=colite-local-gateway-key-000000000000 # Inbound keys clients send to mobile-api: ":" (APP or CP). AUTH_API_KEYS=colite-local-app-key:APP,colite-local-cp-key:CP JAVA_OPTS=-Xmx384m +# WhatsApp inbox. Mock-safe dummy values; the service talks to whatsapp-mock, never to Meta. +WHATSAPP_COMPANIES=INS,CV +WHATSAPP_INS_PHONE_NUMBER_ID=100000000000001 +WHATSAPP_INS_WABA_ID=200000000000001 +WHATSAPP_INS_ACCESS_TOKEN=mock-token-ins +WHATSAPP_INS_APP_SECRET=mock-secret-ins +WHATSAPP_CV_PHONE_NUMBER_ID=100000000000002 +WHATSAPP_CV_WABA_ID=200000000000002 +WHATSAPP_CV_ACCESS_TOKEN=mock-token-cv +WHATSAPP_CV_APP_SECRET=mock-secret-cv +WHATSAPP_VERIFY_TOKEN=mock-verify +WHATSAPP_GRAPH_BASE_URL=http://whatsapp-mock:8080 diff --git a/local/docker-compose.yml b/local/docker-compose.yml index c648f3c..276e4f3 100644 --- a/local/docker-compose.yml +++ b/local/docker-compose.yml @@ -112,5 +112,14 @@ services: mysql: {condition: service_healthy} redis: {condition: service_healthy} pubsub-init: {condition: service_completed_successfully} + service-whatsapp: + build: + context: ../solvway-services-whatsapp + args: {BUILD_PROFILE: local} + env_file: .env + depends_on: + mysql: {condition: service_healthy} + whatsapp-mock: + build: ./whatsapp-mock volumes: mysql-data: diff --git a/local/whatsapp-mock/Dockerfile b/local/whatsapp-mock/Dockerfile new file mode 100644 index 0000000..3c56492 --- /dev/null +++ b/local/whatsapp-mock/Dockerfile @@ -0,0 +1,6 @@ +FROM node:24-alpine +WORKDIR /app +COPY server.js . +EXPOSE 8080 +USER node +CMD ["node", "server.js"] diff --git a/local/whatsapp-mock/server.js b/local/whatsapp-mock/server.js new file mode 100644 index 0000000..fa93adf --- /dev/null +++ b/local/whatsapp-mock/server.js @@ -0,0 +1,11 @@ +// Local stand-in for the WhatsApp Cloud (Graph) API. Later tasks add Graph endpoints and signed webhooks. +const http = require('node:http'); + +http.createServer((req, res) => { + if (req.method === 'GET' && req.url === '/health') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + return res.end('{"status":"UP"}'); + } + res.writeHead(404, { 'Content-Type': 'application/json' }); + res.end('{"error":"not found"}'); +}).listen(8080); diff --git a/openspec/changes/add-whatsapp-inbox/tasks.md b/openspec/changes/add-whatsapp-inbox/tasks.md index d588344..1431ad9 100644 --- a/openspec/changes/add-whatsapp-inbox/tasks.md +++ b/openspec/changes/add-whatsapp-inbox/tasks.md @@ -8,11 +8,11 @@ Verify commands: ## Wave 1 (serial: contracts and hotspots) -- [ ] 1.1 Schema and modules: `sql/01-whatsapp-schema.sql`, `sql/02-whatsapp-modules.sql` and `sql/99-rollback.sql` in this change folder, mirrored into `local/seed/`. +- [x] 1.1 Schema and modules: `sql/01-whatsapp-schema.sql`, `sql/02-whatsapp-modules.sql` and `sql/99-rollback.sql` in this change folder, mirrored into `local/seed/`. - Depends on: none - Scope: `openspec/changes/add-whatsapp-inbox/sql/**`, `local/seed/**` - Verify: load the seed into a fresh local MySQL volume (compose `down -v` on a throwaway project name, then `up mysql`) and list the tables. -- [ ] 1.2 Service skeleton: `solvway-services-whatsapp` module (pom, Dockerfile, `application.yml`, settings binding, health), root pom module entry, the gateway route `Path=/whatsapp/**`, and compose entries for the service and `whatsapp-mock`. The mock is a skeleton that answers health. +- [x] 1.2 Service skeleton: `solvway-services-whatsapp` module (pom, Dockerfile, `application.yml`, settings binding, health), root pom module entry, the gateway route `Path=/whatsapp/**`, and compose entries for the service and `whatsapp-mock`. The mock is a skeleton that answers health. - Depends on: 1.1 - Scope: `solvway-services-whatsapp/**`, `pom.xml`, `solvway-api-gateway/src/main/resources/application.yml`, `local/docker-compose.yml`, `local/whatsapp-mock/**`, `local/.env.example` - Verify: `mvn -T 1C -q -pl solvway-services-whatsapp,solvway-api-gateway verify` diff --git a/pom.xml b/pom.xml index 912ab57..28aecea 100644 --- a/pom.xml +++ b/pom.xml @@ -19,5 +19,6 @@ solvway-services-member solvway-services-log solvway-services-email + solvway-services-whatsapp diff --git a/solvway-api-gateway/src/main/resources/application.yml b/solvway-api-gateway/src/main/resources/application.yml index ba231e5..8e336df 100644 --- a/solvway-api-gateway/src/main/resources/application.yml +++ b/solvway-api-gateway/src/main/resources/application.yml @@ -19,6 +19,7 @@ app: name: auth: service-auth email: service-email + whatsapp: service-whatsapp system: service-system member: service-member log: service-log @@ -176,6 +177,10 @@ spring: uri: http://${app.services.name.email} predicates: - Path=/email/** + - id: whatsapp + uri: http://${app.services.name.whatsapp} + predicates: + - Path=/whatsapp/** - id: printTicket uri: http://${app.services.name.system} predicates: diff --git a/solvway-services-whatsapp/.dockerignore b/solvway-services-whatsapp/.dockerignore new file mode 100644 index 0000000..8881e96 --- /dev/null +++ b/solvway-services-whatsapp/.dockerignore @@ -0,0 +1,3 @@ +# The image needs only the built jar; nothing else from the module enters the build context. +* +!target/*.jar diff --git a/solvway-services-whatsapp/.gitignore b/solvway-services-whatsapp/.gitignore new file mode 100644 index 0000000..6813a30 --- /dev/null +++ b/solvway-services-whatsapp/.gitignore @@ -0,0 +1,4 @@ +target/ +.idea +*.iml +.vscode/ diff --git a/solvway-services-whatsapp/Dockerfile b/solvway-services-whatsapp/Dockerfile new file mode 100644 index 0000000..9a87038 --- /dev/null +++ b/solvway-services-whatsapp/Dockerfile @@ -0,0 +1,8 @@ +FROM gitea.containerverse.dev/solvway/docker-java-21 +ARG BUILD_PROFILE +ENV BUILD_PROFILE ${BUILD_PROFILE:-default} +VOLUME /tmp +ADD target/*.jar app.jar +RUN sh -c 'touch /app.jar' +ENV JAVA_OPTS="" +ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Dspring.profiles.active=$BUILD_PROFILE -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ] diff --git a/solvway-services-whatsapp/pom.xml b/solvway-services-whatsapp/pom.xml new file mode 100644 index 0000000..520296f --- /dev/null +++ b/solvway-services-whatsapp/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.2.8 + + + + com.solvway.services.whatsapp + solvway-services-whatsapp + 0.0.1-SNAPSHOT + solvway-services-whatsapp + WhatsApp inbox service + + + UTF-8 + UTF-8 + 21 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-actuator + + + com.mysql + mysql-connector-j + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/SolvwayServicesWhatsappApplication.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/SolvwayServicesWhatsappApplication.java new file mode 100644 index 0000000..54a42f1 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/SolvwayServicesWhatsappApplication.java @@ -0,0 +1,12 @@ +package com.solvway.services.whatsapp; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SolvwayServicesWhatsappApplication { + + public static void main(String[] args) { + SpringApplication.run(SolvwayServicesWhatsappApplication.class, args); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/config/WhatsAppSettings.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/config/WhatsAppSettings.java new file mode 100644 index 0000000..88654a4 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/config/WhatsAppSettings.java @@ -0,0 +1,74 @@ +package com.solvway.services.whatsapp.config; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * WhatsApp Cloud API settings from env: WHATSAPP_COMPANIES (comma-separated codes) and, per code, + * WHATSAPP_<CODE>_PHONE_NUMBER_ID / _WABA_ID / _ACCESS_TOKEN / _APP_SECRET. No companies means WhatsApp is off. + */ +@Component +public class WhatsAppSettings { + + private static final Logger log = LoggerFactory.getLogger(WhatsAppSettings.class); + private static final String[] KEYS = {"PHONE_NUMBER_ID", "WABA_ID", "ACCESS_TOKEN", "APP_SECRET"}; + + public record CompanyConfig(String code, String phoneNumberId, String wabaId, String accessToken, String appSecret) { + @Override + public String toString() { + return "CompanyConfig[code=" + code + ", phoneNumberId=" + phoneNumberId + ", wabaId=" + wabaId + ", secrets=***]"; + } + } + + private final List companies = new ArrayList<>(); + private final String verifyToken; + private final String graphBaseUrl; + + public WhatsAppSettings(Environment env) { + for (String raw : env.getProperty("WHATSAPP_COMPANIES", "").split(",")) { + String code = raw.trim().toUpperCase(); + if (code.isEmpty()) { + continue; + } + String[] values = new String[KEYS.length]; + boolean complete = true; + for (int i = 0; i < KEYS.length; i++) { + String key = "WHATSAPP_" + code + "_" + KEYS[i]; + values[i] = env.getProperty(key); + if (!StringUtils.hasText(values[i])) { + log.warn("WhatsApp company {} skipped: {} is not set", code, key); + complete = false; + break; + } + } + if (complete) { + companies.add(new CompanyConfig(code, values[0], values[1], values[2], values[3])); + } + } + verifyToken = env.getProperty("WHATSAPP_VERIFY_TOKEN", ""); + graphBaseUrl = env.getProperty("WHATSAPP_GRAPH_BASE_URL", "https://graph.facebook.com/v21.0"); + } + + public List companies() { + return List.copyOf(companies); + } + + public Optional findByPhoneNumberId(String phoneNumberId) { + return companies.stream().filter(c -> c.phoneNumberId().equals(phoneNumberId)).findFirst(); + } + + public String verifyToken() { + return verifyToken; + } + + public String graphBaseUrl() { + return graphBaseUrl; + } +} diff --git a/solvway-services-whatsapp/src/main/resources/application-local.yml b/solvway-services-whatsapp/src/main/resources/application-local.yml new file mode 100644 index 0000000..ba032f6 --- /dev/null +++ b/solvway-services-whatsapp/src/main/resources/application-local.yml @@ -0,0 +1 @@ +# Local docker-compose stack only (BUILD_PROFILE=local). WhatsApp settings come from WHATSAPP_* env (local/.env). diff --git a/solvway-services-whatsapp/src/main/resources/application.yml b/solvway-services-whatsapp/src/main/resources/application.yml new file mode 100644 index 0000000..0fb347b --- /dev/null +++ b/solvway-services-whatsapp/src/main/resources/application.yml @@ -0,0 +1,34 @@ +info: + app: + name: Solvway WhatsApp Service + description: WhatsApp inbox service + version: 1.0.0 + +management: + health: + probes: + enabled: true + db: + enabled: true + defaults: + enabled: true + endpoint: + health: + show-details: always +server: + port: 80 + servlet: + encoding: + charset: UTF-8 + force: true +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://${MYSQLHOST}:${MYSQLPORT}/service-whatsapp?useSSL=false&allowPublicKeyRetrieval=true&sslMode=DISABLED&serverTimezone=Asia/Kuala_Lumpur&characterEncoding=UTF-8 + username: ${MYSQLUSER} + password: ${MYSQLPWD} + jpa: + open-in-view: false + threads: + virtual: + enabled: true diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/config/WhatsAppSettingsTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/config/WhatsAppSettingsTest.java new file mode 100644 index 0000000..cb37feb --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/config/WhatsAppSettingsTest.java @@ -0,0 +1,71 @@ +package com.solvway.services.whatsapp.config; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.env.MockEnvironment; + +import static org.assertj.core.api.Assertions.assertThat; + +class WhatsAppSettingsTest { + + private static MockEnvironment company(MockEnvironment env, String code, String phoneId) { + return env.withProperty("WHATSAPP_" + code + "_PHONE_NUMBER_ID", phoneId) + .withProperty("WHATSAPP_" + code + "_WABA_ID", "waba-" + code) + .withProperty("WHATSAPP_" + code + "_ACCESS_TOKEN", "token-" + code) + .withProperty("WHATSAPP_" + code + "_APP_SECRET", "secret-" + code); + } + + @Test + void bindsTwoCompaniesAndLooksUpByPhoneNumberId() { + MockEnvironment env = new MockEnvironment().withProperty("WHATSAPP_COMPANIES", "INS, cv"); + company(env, "INS", "111"); + company(env, "CV", "222"); + WhatsAppSettings s = new WhatsAppSettings(env); + + assertThat(s.companies()).extracting(WhatsAppSettings.CompanyConfig::code).containsExactly("INS", "CV"); + WhatsAppSettings.CompanyConfig cv = s.findByPhoneNumberId("222").orElseThrow(); + assertThat(cv.code()).isEqualTo("CV"); + assertThat(cv.wabaId()).isEqualTo("waba-CV"); + assertThat(cv.accessToken()).isEqualTo("token-CV"); + assertThat(cv.appSecret()).isEqualTo("secret-CV"); + assertThat(s.findByPhoneNumberId("999")).isEmpty(); + } + + @Test + void skipsCompanyMissingAKey() { + MockEnvironment env = new MockEnvironment().withProperty("WHATSAPP_COMPANIES", "INS,CV"); + company(env, "INS", "111"); + env.withProperty("WHATSAPP_CV_PHONE_NUMBER_ID", "222"); // the other three keys are missing + WhatsAppSettings s = new WhatsAppSettings(env); + + assertThat(s.companies()).extracting(WhatsAppSettings.CompanyConfig::code).containsExactly("INS"); + assertThat(s.findByPhoneNumberId("222")).isEmpty(); + } + + @Test + void emptyWhenNoWhatsAppEnv() { + WhatsAppSettings s = new WhatsAppSettings(new MockEnvironment()); + + assertThat(s.companies()).isEmpty(); + assertThat(s.verifyToken()).isEmpty(); + assertThat(s.graphBaseUrl()).isEqualTo("https://graph.facebook.com/v21.0"); + } + + @Test + void readsVerifyTokenAndGraphBaseUrl() { + WhatsAppSettings s = new WhatsAppSettings(new MockEnvironment() + .withProperty("WHATSAPP_VERIFY_TOKEN", "vt") + .withProperty("WHATSAPP_GRAPH_BASE_URL", "http://whatsapp-mock:8080")); + + assertThat(s.verifyToken()).isEqualTo("vt"); + assertThat(s.graphBaseUrl()).isEqualTo("http://whatsapp-mock:8080"); + } + + @Test + void toStringMasksSecrets() { + MockEnvironment env = new MockEnvironment().withProperty("WHATSAPP_COMPANIES", "INS"); + company(env, "INS", "111"); + String text = new WhatsAppSettings(env).companies().get(0).toString(); + + assertThat(text).contains("INS", "111").doesNotContain("token-INS").doesNotContain("secret-INS"); + } +} -- 2.54.1 From 6d63cc74d1e3a3ffe6af8172486185b95e70880e Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 01:30:37 +0800 Subject: [PATCH 04/23] feat: WhatsApp contract between mobile-api, the service and the counter Shared DTOs on both sides with identical JSON keys, the service API constants with the access convention (the service enforces company, owner and admin), Snowflake ids as strings towards the portal, and the counter's WhatsApp contact type. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-whatsapp-inbox/tasks.md | 2 +- .../api/RestApiWhatsappServiceConstants.java | 36 ++++++++++ .../api/dto/whatsapp/AssignRequest.java | 4 ++ .../api/dto/whatsapp/ConversationPage.java | 5 ++ .../api/dto/whatsapp/ConversationView.java | 10 +++ .../api/dto/whatsapp/LeadChangedRequest.java | 3 + .../mobile/api/dto/whatsapp/MessageView.java | 10 +++ .../api/dto/whatsapp/SendMessageRequest.java | 6 ++ .../api/dto/whatsapp/StartChatRequest.java | 8 +++ .../mobile/api/dto/whatsapp/TemplateView.java | 3 + .../mobile/api/dto/whatsapp/ThreadView.java | 5 ++ .../mobile/api/dto/whatsapp/UnreadCount.java | 4 ++ .../api/dto/whatsapp/UserChangedRequest.java | 3 + .../dto/whatsapp/WebhookIngestRequest.java | 7 ++ .../mobile/api/dto/whatsapp/DtoJsonTest.java | 70 +++++++++++++++++++ .../services/counter/dto/WhatsappContact.java | 4 ++ .../whatsapp/constants/CounterApi.java | 9 +++ .../services/whatsapp/dto/AssignRequest.java | 4 ++ .../whatsapp/dto/ConversationPage.java | 5 ++ .../whatsapp/dto/ConversationView.java | 8 +++ .../whatsapp/dto/LeadChangedRequest.java | 3 + .../services/whatsapp/dto/MessageView.java | 10 +++ .../whatsapp/dto/SendMessageRequest.java | 6 ++ .../whatsapp/dto/StartChatRequest.java | 4 ++ .../services/whatsapp/dto/TemplateView.java | 3 + .../services/whatsapp/dto/ThreadView.java | 5 ++ .../services/whatsapp/dto/UnreadCount.java | 4 ++ .../whatsapp/dto/UserChangedRequest.java | 3 + .../whatsapp/dto/WebhookIngestRequest.java | 7 ++ .../whatsapp/dto/WhatsappContact.java | 4 ++ .../services/whatsapp/dto/package-info.java | 18 +++++ .../services/whatsapp/dto/DtoJsonTest.java | 60 ++++++++++++++++ 32 files changed, 332 insertions(+), 1 deletion(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiWhatsappServiceConstants.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/AssignRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/ConversationPage.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/ConversationView.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/LeadChangedRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/MessageView.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/SendMessageRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/StartChatRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/TemplateView.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/ThreadView.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/UnreadCount.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/UserChangedRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/WebhookIngestRequest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/dto/whatsapp/DtoJsonTest.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/WhatsappContact.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/constants/CounterApi.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/AssignRequest.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/ConversationPage.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/ConversationView.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/LeadChangedRequest.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/MessageView.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/SendMessageRequest.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/StartChatRequest.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/TemplateView.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/ThreadView.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/UnreadCount.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/UserChangedRequest.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WebhookIngestRequest.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WhatsappContact.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/package-info.java create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/dto/DtoJsonTest.java diff --git a/openspec/changes/add-whatsapp-inbox/tasks.md b/openspec/changes/add-whatsapp-inbox/tasks.md index 1431ad9..b7cb72c 100644 --- a/openspec/changes/add-whatsapp-inbox/tasks.md +++ b/openspec/changes/add-whatsapp-inbox/tasks.md @@ -16,7 +16,7 @@ Verify commands: - Depends on: 1.1 - Scope: `solvway-services-whatsapp/**`, `pom.xml`, `solvway-api-gateway/src/main/resources/application.yml`, `local/docker-compose.yml`, `local/whatsapp-mock/**`, `local/.env.example` - Verify: `mvn -T 1C -q -pl solvway-services-whatsapp,solvway-api-gateway verify` -- [ ] 1.3 Shared DTOs and API constants: the webhook ingest body, conversation and message views, and `RestApiWhatsappServiceConstants` in mobile-api. +- [x] 1.3 Shared DTOs and API constants: the webhook ingest body, conversation and message views, and `RestApiWhatsappServiceConstants` in mobile-api. - Depends on: 1.2 - Scope: `solvway-services-whatsapp/src/main/java/**/dto/**`, `solvway-mobile-api/src/main/java/**/constant/api/RestApiWhatsappServiceConstants.java`, `solvway-mobile-api/src/main/java/**/dto/whatsapp/**` - Verify: `mvn -T 1C -q -pl solvway-services-whatsapp,solvway-mobile-api verify` diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiWhatsappServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiWhatsappServiceConstants.java new file mode 100644 index 0000000..cb5b54d --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiWhatsappServiceConstants.java @@ -0,0 +1,36 @@ +package com.solvway.mobile.api.constant.api; + +/** + * Caller context and access (the SERVICE enforces it; mobile-api only supplies trusted values): + * - per-conversation calls (thread, send, read, media, assign, start) and the list carry query params + * companyId (null ONLY for a super admin = all companies), userId (the acting staff user) and + * admin (true when the caller holds BO_WHATSAPP_ADMIN or is a super admin). + * - mobile-api resolves companyId through AdminCompanyScope.scope and admin from the caller's modules, never from + * the request; it does NOT re-check conversation ownership. + * - the service answers 404 for a conversation of another company, always; with admin=false also for a conversation + * not owned by userId. Exception: start returns the conversation's ConversationView (owner fields set, no + * messages) even when owned by someone else, so the UI can say who owns it. + * Response contracts: unreadCount returns UnreadCount {"count": long}; start returns ConversationView; media answers + * 410 ProblemDetail detail MEDIA_EXPIRED when Meta no longer has it, 404 when not visible; send answers 409 detail + * WINDOW_CLOSED (text outside the 24 h window) or 400 detail TEMPLATE_PARAMS (missing template parameters); + * WhatsApp not configured for the company answers 409 detail WHATSAPP_NOT_CONFIGURED. + * "Exactly one of" request validation is done by the mobile-api admin layer, not the DTOs. + */ +public class RestApiWhatsappServiceConstants { + + private RestApiWhatsappServiceConstants() {} + + public static final String API_REST_WHATSAPP_WEBHOOK_INGEST = "/whatsapp/webhook/ingest"; + public static final String API_REST_WHATSAPP_CONVERSATIONS = "/whatsapp/conversations"; + public static final String API_REST_WHATSAPP_CONVERSATION = "/whatsapp/conversations/{uuid}"; + public static final String API_REST_WHATSAPP_CONVERSATION_SEND = "/whatsapp/conversations/{uuid}/messages"; + public static final String API_REST_WHATSAPP_CONVERSATION_READ = "/whatsapp/conversations/{uuid}/read"; + public static final String API_REST_WHATSAPP_CONVERSATION_ASSIGN = "/whatsapp/conversations/{uuid}/assign"; + public static final String API_REST_WHATSAPP_CONVERSATION_START = "/whatsapp/conversations/start"; + public static final String API_REST_WHATSAPP_TEMPLATES = "/whatsapp/templates"; + public static final String API_REST_WHATSAPP_TEMPLATES_SYNC = "/whatsapp/templates/sync"; + public static final String API_REST_WHATSAPP_MEDIA = "/whatsapp/media/{messageUuid}"; + public static final String API_REST_WHATSAPP_UNREAD_COUNT = "/whatsapp/unreadCount"; + public static final String API_REST_WHATSAPP_OWNERSHIP_LEAD_CHANGED = "/whatsapp/ownership/leadChanged"; + public static final String API_REST_WHATSAPP_OWNERSHIP_USER_CHANGED = "/whatsapp/ownership/userChanged"; +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/AssignRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/AssignRequest.java new file mode 100644 index 0000000..62165da --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/AssignRequest.java @@ -0,0 +1,4 @@ +package com.solvway.mobile.api.dto.whatsapp; + +/** userId assigns manually; automatic=true returns the chat to automatic ownership. */ +public record AssignRequest(Long userId, Boolean automatic) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/ConversationPage.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/ConversationPage.java new file mode 100644 index 0000000..10bb3d7 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/ConversationPage.java @@ -0,0 +1,5 @@ +package com.solvway.mobile.api.dto.whatsapp; + +import java.util.List; + +public record ConversationPage(List items, long total, int page, int size) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/ConversationView.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/ConversationView.java new file mode 100644 index 0000000..c7a6ac0 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/ConversationView.java @@ -0,0 +1,10 @@ +package com.solvway.mobile.api.dto.whatsapp; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import java.time.LocalDateTime; + +/** leadUuid is a Snowflake id, written as a JSON string toward the portal (reads accept the service number). Caller context (companyId, userId) travels as query params, never in this body. ownerName is filled by mobile-api. */ +public record ConversationView(String uuid, Long companyId, String contactWaId, String contactName, @JsonSerialize(using = ToStringSerializer.class) Long leadUuid, String leadName, + Long ownerUserId, String ownerName, boolean ownerManual, LocalDateTime lastInboundAt, + LocalDateTime lastMessageAt, String lastMessagePreview, boolean windowOpen, long unreadCount) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/LeadChangedRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/LeadChangedRequest.java new file mode 100644 index 0000000..daef1d6 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/LeadChangedRequest.java @@ -0,0 +1,3 @@ +package com.solvway.mobile.api.dto.whatsapp; + +public record LeadChangedRequest(Long companyId, String mobileE164) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/MessageView.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/MessageView.java new file mode 100644 index 0000000..3b4b88e --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/MessageView.java @@ -0,0 +1,10 @@ +package com.solvway.mobile.api.dto.whatsapp; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** Never carries media_id or wamid. */ +public record MessageView(String uuid, String direction, String type, String body, String templateName, String mediaMime, + String mediaFilename, BigDecimal locationLat, BigDecimal locationLng, String locationName, + String status, String errorCode, String errorTitle, Long sentByUserId, LocalDateTime createdAt, + LocalDateTime statusAt) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/SendMessageRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/SendMessageRequest.java new file mode 100644 index 0000000..acf5c70 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/SendMessageRequest.java @@ -0,0 +1,6 @@ +package com.solvway.mobile.api.dto.whatsapp; + +import java.util.List; + +/** Exactly one of text or template (with language and params). */ +public record SendMessageRequest(String text, String template, String language, List params) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/StartChatRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/StartChatRequest.java new file mode 100644 index 0000000..416f8b2 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/StartChatRequest.java @@ -0,0 +1,8 @@ +package com.solvway.mobile.api.dto.whatsapp; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; + +/** Exactly one of leadUuid or eventLeadUuid. */ +public record StartChatRequest(@JsonSerialize(using = ToStringSerializer.class) Long leadUuid, + @JsonSerialize(using = ToStringSerializer.class) Long eventLeadUuid) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/TemplateView.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/TemplateView.java new file mode 100644 index 0000000..8e548d2 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/TemplateView.java @@ -0,0 +1,3 @@ +package com.solvway.mobile.api.dto.whatsapp; + +public record TemplateView(String name, String language, String category, String bodyText, int paramCount, boolean supported) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/ThreadView.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/ThreadView.java new file mode 100644 index 0000000..0fca359 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/ThreadView.java @@ -0,0 +1,5 @@ +package com.solvway.mobile.api.dto.whatsapp; + +import java.util.List; + +public record ThreadView(ConversationView conversation, List messages, boolean hasOlder) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/UnreadCount.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/UnreadCount.java new file mode 100644 index 0000000..4d4c12f --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/UnreadCount.java @@ -0,0 +1,4 @@ +package com.solvway.mobile.api.dto.whatsapp; + +/** GET /whatsapp/unreadCount response. */ +public record UnreadCount(long count) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/UserChangedRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/UserChangedRequest.java new file mode 100644 index 0000000..4cccfa9 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/UserChangedRequest.java @@ -0,0 +1,3 @@ +package com.solvway.mobile.api.dto.whatsapp; + +public record UserChangedRequest(Long userId) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/WebhookIngestRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/WebhookIngestRequest.java new file mode 100644 index 0000000..8f67809 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/WebhookIngestRequest.java @@ -0,0 +1,7 @@ +package com.solvway.mobile.api.dto.whatsapp; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.List; + +/** mobile-api to service, POST /whatsapp/webhook/ingest: the signature-matched company codes and the raw Meta payload. */ +public record WebhookIngestRequest(List matchedCompanyCodes, JsonNode payload) {} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/dto/whatsapp/DtoJsonTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/dto/whatsapp/DtoJsonTest.java new file mode 100644 index 0000000..77b2184 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/dto/whatsapp/DtoJsonTest.java @@ -0,0 +1,70 @@ +package com.solvway.mobile.api.dto.whatsapp; + + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** The service and mobile-api sides must serialise to the same key sets. */ +class DtoJsonTest { + + // same shape as Spring Boot's default mapper: java.time as ISO strings + private final ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule()) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + + private Set keys(Object o) { + JsonNode n = mapper.valueToTree(o); + Set k = new TreeSet<>(); + n.fieldNames().forEachRemaining(k::add); + return k; + } + + @Test + void conversationViewKeys() throws Exception { + LocalDateTime t = LocalDateTime.of(2026, 12, 1, 10, 0); + ConversationView v = new ConversationView("u", 1L, "27820000000", "Ann", 2L, "Lead Ann", 3L, "Bob", true, t, t, "hi", true, 4); + assertEquals(new TreeSet<>(List.of("uuid", "companyId", "contactWaId", "contactName", "leadUuid", "leadName", "ownerUserId", + "ownerName", "ownerManual", "lastInboundAt", "lastMessageAt", "lastMessagePreview", "windowOpen", + "unreadCount")), keys(v)); + assertEquals("2026-12-01T10:00:00", mapper.valueToTree(v).get("lastInboundAt").asText()); + assertEquals(v, mapper.readValue(mapper.writeValueAsString(v), ConversationView.class)); + } + + @Test + void snowflakeIdsAreWrittenAsStrings() throws Exception { + ConversationView v = new ConversationView("u", 1L, "w", "n", 1234567890123456789L, "l", null, null, false, null, null, null, false, 0); + assertEquals("1234567890123456789", mapper.valueToTree(v).get("leadUuid").asText()); + assertEquals(true, mapper.valueToTree(v).get("leadUuid").isTextual()); + assertEquals(true, mapper.valueToTree(new StartChatRequest(1L, 2L)).get("eventLeadUuid").isTextual()); + assertEquals(1234567890123456789L, mapper.readValue("{\"leadUuid\":1234567890123456789}", ConversationView.class).leadUuid()); + assertEquals(1L, mapper.readValue("{\"leadUuid\":\"1\"}", StartChatRequest.class).leadUuid()); + } + + @Test + void messageViewKeys() throws Exception { + LocalDateTime t = LocalDateTime.of(2026, 12, 1, 10, 0); + MessageView v = new MessageView("u", "in", "text", "hi", "tpl", "image/png", "a.png", new BigDecimal("1.5"), + new BigDecimal("2.5"), "Spot", "sent", "131047", "Re-engagement", 3L, t, t); + assertEquals(new TreeSet<>(List.of("uuid", "direction", "type", "body", "templateName", "mediaMime", + "mediaFilename", "locationLat", "locationLng", "locationName", "status", "errorCode", "errorTitle", + "sentByUserId", "createdAt", "statusAt")), keys(v)); + assertEquals(v, mapper.readValue(mapper.writeValueAsString(v), MessageView.class)); + } + + @Test + void webhookIngestRequestKeys() throws Exception { + WebhookIngestRequest r = new WebhookIngestRequest(List.of("INS"), mapper.readTree("{\"entry\":[]}")); + assertEquals(new TreeSet<>(List.of("matchedCompanyCodes", "payload")), keys(r)); + assertEquals(r, mapper.readValue(mapper.writeValueAsString(r), WebhookIngestRequest.class)); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/WhatsappContact.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/WhatsappContact.java new file mode 100644 index 0000000..2541881 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/WhatsappContact.java @@ -0,0 +1,4 @@ +package com.solvway.services.counter.dto; + +/** Counter GET /counter/lead/whatsappContact response; the newest lead for the mobile. */ +public record WhatsappContact(Long leadUuid, String name, Long latestSalespersonUserId) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/constants/CounterApi.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/constants/CounterApi.java new file mode 100644 index 0000000..b21063a --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/constants/CounterApi.java @@ -0,0 +1,9 @@ +package com.solvway.services.whatsapp.constants; + +public final class CounterApi { + + private CounterApi() {} + + /** GET, query params companyId and mobileE164; returns WhatsappContact. */ + public static final String WHATSAPP_CONTACT = "/counter/lead/whatsappContact"; +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/AssignRequest.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/AssignRequest.java new file mode 100644 index 0000000..e0ee4fd --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/AssignRequest.java @@ -0,0 +1,4 @@ +package com.solvway.services.whatsapp.dto; + +/** userId assigns manually; automatic=true returns the chat to automatic ownership. */ +public record AssignRequest(Long userId, Boolean automatic) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/ConversationPage.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/ConversationPage.java new file mode 100644 index 0000000..5f572c8 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/ConversationPage.java @@ -0,0 +1,5 @@ +package com.solvway.services.whatsapp.dto; + +import java.util.List; + +public record ConversationPage(List items, long total, int page, int size) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/ConversationView.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/ConversationView.java new file mode 100644 index 0000000..3587ec5 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/ConversationView.java @@ -0,0 +1,8 @@ +package com.solvway.services.whatsapp.dto; + +import java.time.LocalDateTime; + +/** Caller context (companyId, userId) travels as query params, never in this body. ownerName is filled by mobile-api. */ +public record ConversationView(String uuid, Long companyId, String contactWaId, String contactName, Long leadUuid, String leadName, + Long ownerUserId, String ownerName, boolean ownerManual, LocalDateTime lastInboundAt, + LocalDateTime lastMessageAt, String lastMessagePreview, boolean windowOpen, long unreadCount) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/LeadChangedRequest.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/LeadChangedRequest.java new file mode 100644 index 0000000..b05254b --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/LeadChangedRequest.java @@ -0,0 +1,3 @@ +package com.solvway.services.whatsapp.dto; + +public record LeadChangedRequest(Long companyId, String mobileE164) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/MessageView.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/MessageView.java new file mode 100644 index 0000000..dcfef4e --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/MessageView.java @@ -0,0 +1,10 @@ +package com.solvway.services.whatsapp.dto; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** Never carries media_id or wamid. */ +public record MessageView(String uuid, String direction, String type, String body, String templateName, String mediaMime, + String mediaFilename, BigDecimal locationLat, BigDecimal locationLng, String locationName, + String status, String errorCode, String errorTitle, Long sentByUserId, LocalDateTime createdAt, + LocalDateTime statusAt) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/SendMessageRequest.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/SendMessageRequest.java new file mode 100644 index 0000000..5bab3cc --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/SendMessageRequest.java @@ -0,0 +1,6 @@ +package com.solvway.services.whatsapp.dto; + +import java.util.List; + +/** Exactly one of text or template (with language and params). */ +public record SendMessageRequest(String text, String template, String language, List params) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/StartChatRequest.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/StartChatRequest.java new file mode 100644 index 0000000..6f1e971 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/StartChatRequest.java @@ -0,0 +1,4 @@ +package com.solvway.services.whatsapp.dto; + +/** Exactly one of leadUuid or eventLeadUuid. */ +public record StartChatRequest(Long leadUuid, Long eventLeadUuid) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/TemplateView.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/TemplateView.java new file mode 100644 index 0000000..08215af --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/TemplateView.java @@ -0,0 +1,3 @@ +package com.solvway.services.whatsapp.dto; + +public record TemplateView(String name, String language, String category, String bodyText, int paramCount, boolean supported) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/ThreadView.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/ThreadView.java new file mode 100644 index 0000000..b5780e2 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/ThreadView.java @@ -0,0 +1,5 @@ +package com.solvway.services.whatsapp.dto; + +import java.util.List; + +public record ThreadView(ConversationView conversation, List messages, boolean hasOlder) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/UnreadCount.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/UnreadCount.java new file mode 100644 index 0000000..8479995 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/UnreadCount.java @@ -0,0 +1,4 @@ +package com.solvway.services.whatsapp.dto; + +/** GET /whatsapp/unreadCount response. */ +public record UnreadCount(long count) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/UserChangedRequest.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/UserChangedRequest.java new file mode 100644 index 0000000..3afea46 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/UserChangedRequest.java @@ -0,0 +1,3 @@ +package com.solvway.services.whatsapp.dto; + +public record UserChangedRequest(Long userId) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WebhookIngestRequest.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WebhookIngestRequest.java new file mode 100644 index 0000000..a3a4dc0 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WebhookIngestRequest.java @@ -0,0 +1,7 @@ +package com.solvway.services.whatsapp.dto; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.List; + +/** mobile-api to service, POST /whatsapp/webhook/ingest: the signature-matched company codes and the raw Meta payload. */ +public record WebhookIngestRequest(List matchedCompanyCodes, JsonNode payload) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WhatsappContact.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WhatsappContact.java new file mode 100644 index 0000000..2504603 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WhatsappContact.java @@ -0,0 +1,4 @@ +package com.solvway.services.whatsapp.dto; + +/** Counter GET /counter/lead/whatsappContact response; the newest lead for the mobile. */ +public record WhatsappContact(Long leadUuid, String name, Long latestSalespersonUserId) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/package-info.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/package-info.java new file mode 100644 index 0000000..f57a028 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/package-info.java @@ -0,0 +1,18 @@ +/** + * Caller context and access (the SERVICE enforces it; mobile-api only supplies trusted values): + * - per-conversation calls (thread, send, read, media, assign, start) and the list carry query params + * companyId (null ONLY for a super admin = all companies), userId (the acting staff user) and + * admin (true when the caller holds BO_WHATSAPP_ADMIN or is a super admin). + * - mobile-api resolves companyId through AdminCompanyScope.scope and admin from the caller's modules, never from + * the request; it does NOT re-check conversation ownership. + * - the service answers 404 for a conversation of another company, always; with admin=false also for a conversation + * not owned by userId. Exception: start returns the conversation's ConversationView (owner fields set, no + * messages) even when owned by someone else, so the UI can say who owns it. + * Response contracts: unreadCount returns UnreadCount {"count": long}; start returns ConversationView; media answers + * 410 ProblemDetail detail MEDIA_EXPIRED when Meta no longer has it, 404 when not visible; send answers 409 detail + * WINDOW_CLOSED (text outside the 24 h window) or 400 detail TEMPLATE_PARAMS (missing template parameters); + * WhatsApp not configured for the company answers 409 detail WHATSAPP_NOT_CONFIGURED. + * "Exactly one of" request validation is done by the mobile-api admin layer, not the DTOs. + * Same contract as mobile-api RestApiWhatsappServiceConstants (keep in sync). + */ +package com.solvway.services.whatsapp.dto; diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/dto/DtoJsonTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/dto/DtoJsonTest.java new file mode 100644 index 0000000..ea3248f --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/dto/DtoJsonTest.java @@ -0,0 +1,60 @@ +package com.solvway.services.whatsapp.dto; + + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** The service and mobile-api sides must serialise to the same key sets. */ +class DtoJsonTest { + + // same shape as Spring Boot's default mapper: java.time as ISO strings + private final ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule()) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + + private Set keys(Object o) { + JsonNode n = mapper.valueToTree(o); + Set k = new TreeSet<>(); + n.fieldNames().forEachRemaining(k::add); + return k; + } + + @Test + void conversationViewKeys() throws Exception { + LocalDateTime t = LocalDateTime.of(2026, 12, 1, 10, 0); + ConversationView v = new ConversationView("u", 1L, "27820000000", "Ann", 2L, "Lead Ann", 3L, "Bob", true, t, t, "hi", true, 4); + assertEquals(new TreeSet<>(List.of("uuid", "companyId", "contactWaId", "contactName", "leadUuid", "leadName", "ownerUserId", + "ownerName", "ownerManual", "lastInboundAt", "lastMessageAt", "lastMessagePreview", "windowOpen", + "unreadCount")), keys(v)); + assertEquals("2026-12-01T10:00:00", mapper.valueToTree(v).get("lastInboundAt").asText()); + assertEquals(v, mapper.readValue(mapper.writeValueAsString(v), ConversationView.class)); + } + + @Test + void messageViewKeys() throws Exception { + LocalDateTime t = LocalDateTime.of(2026, 12, 1, 10, 0); + MessageView v = new MessageView("u", "in", "text", "hi", "tpl", "image/png", "a.png", new BigDecimal("1.5"), + new BigDecimal("2.5"), "Spot", "sent", "131047", "Re-engagement", 3L, t, t); + assertEquals(new TreeSet<>(List.of("uuid", "direction", "type", "body", "templateName", "mediaMime", + "mediaFilename", "locationLat", "locationLng", "locationName", "status", "errorCode", "errorTitle", + "sentByUserId", "createdAt", "statusAt")), keys(v)); + assertEquals(v, mapper.readValue(mapper.writeValueAsString(v), MessageView.class)); + } + + @Test + void webhookIngestRequestKeys() throws Exception { + WebhookIngestRequest r = new WebhookIngestRequest(List.of("INS"), mapper.readTree("{\"entry\":[]}")); + assertEquals(new TreeSet<>(List.of("matchedCompanyCodes", "payload")), keys(r)); + assertEquals(r, mapper.readValue(mapper.writeValueAsString(r), WebhookIngestRequest.class)); + } +} -- 2.54.1 From b13e39ac758af6f35172df0155e27a6ddea96c7f Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 01:48:10 +0800 Subject: [PATCH 05/23] feat: WhatsApp webhook ingest for messages and delivery statuses Stores inbound messages once per wamid in the conversation of the company that owns the receiving number (only companies whose app secret matched), keeps INS and CV apart, moves statuses only forward (failed always), and updates conversations in place without touching ownership. Company codes resolve through the system service with a 30 s retry cooldown. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../whatsapp/controller/ErrorHandler.java | 23 ++ .../controller/WebhookController.java | 25 ++ .../whatsapp/model/WaConversation.java | 26 ++ .../services/whatsapp/model/WaMessage.java | 34 ++ .../services/whatsapp/model/WaRead.java | 14 + .../services/whatsapp/model/WaReadId.java | 5 + .../services/whatsapp/model/WaTemplate.java | 22 ++ .../repository/WaConversationRepository.java | 30 ++ .../repository/WaMessageRepository.java | 12 + .../whatsapp/repository/WaReadRepository.java | 7 + .../repository/WaTemplateRepository.java | 6 + .../whatsapp/service/CompanyDirectory.java | 92 +++++ .../whatsapp/service/IngestResult.java | 4 + .../service/WebhookIngestService.java | 209 ++++++++++ .../controller/WebhookControllerTest.java | 60 +++ .../service/CompanyDirectoryTest.java | 129 +++++++ .../service/WebhookIngestServiceTest.java | 362 ++++++++++++++++++ .../src/test/resources/whatsapp/document.json | 1 + .../src/test/resources/whatsapp/image.json | 1 + .../src/test/resources/whatsapp/location.json | 1 + .../src/test/resources/whatsapp/reaction.json | 1 + .../resources/whatsapp/status-failed.json | 1 + .../src/test/resources/whatsapp/status.json | 1 + .../src/test/resources/whatsapp/text.json | 1 + 24 files changed, 1067 insertions(+) create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/controller/ErrorHandler.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/controller/WebhookController.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaConversation.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaMessage.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaRead.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaReadId.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaTemplate.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaMessageRepository.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaReadRepository.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaTemplateRepository.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/IngestResult.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/controller/WebhookControllerTest.java create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/CompanyDirectoryTest.java create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java create mode 100644 solvway-services-whatsapp/src/test/resources/whatsapp/document.json create mode 100644 solvway-services-whatsapp/src/test/resources/whatsapp/image.json create mode 100644 solvway-services-whatsapp/src/test/resources/whatsapp/location.json create mode 100644 solvway-services-whatsapp/src/test/resources/whatsapp/reaction.json create mode 100644 solvway-services-whatsapp/src/test/resources/whatsapp/status-failed.json create mode 100644 solvway-services-whatsapp/src/test/resources/whatsapp/status.json create mode 100644 solvway-services-whatsapp/src/test/resources/whatsapp/text.json diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/controller/ErrorHandler.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/controller/ErrorHandler.java new file mode 100644 index 0000000..409567e --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/controller/ErrorHandler.java @@ -0,0 +1,23 @@ +package com.solvway.services.whatsapp.controller; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ProblemDetail; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +/** Errors are ProblemDetail with the reason in {@code detail}; ResponseStatusException(status, reason) already maps so. */ +@RestControllerAdvice +public class ErrorHandler extends ResponseEntityExceptionHandler { + + @Override + protected ResponseEntity handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, + HttpStatusCode status, WebRequest request) { + return handleExceptionInternal(ex, ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"), + headers, HttpStatus.BAD_REQUEST, request); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/controller/WebhookController.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/controller/WebhookController.java new file mode 100644 index 0000000..f238e03 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/controller/WebhookController.java @@ -0,0 +1,25 @@ +package com.solvway.services.whatsapp.controller; + +import com.solvway.services.whatsapp.dto.WebhookIngestRequest; +import com.solvway.services.whatsapp.service.IngestResult; +import com.solvway.services.whatsapp.service.WebhookIngestService; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/whatsapp/webhook") +public class WebhookController { + + private final WebhookIngestService service; + + public WebhookController(WebhookIngestService service) { + this.service = service; + } + + @PostMapping("/ingest") + public IngestResult ingest(@RequestBody WebhookIngestRequest request) { + return service.ingest(request); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaConversation.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaConversation.java new file mode 100644 index 0000000..cdb07e1 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaConversation.java @@ -0,0 +1,26 @@ +package com.solvway.services.whatsapp.model; + +import jakarta.persistence.*; + +import java.time.LocalDateTime; + +// ponytail: public fields instead of getters/setters (no Lombok in this module); switch if a mapper needs bean accessors. +@Entity +@Table(name = "wa_conversation") +public class WaConversation { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public String uuid; + public Long companyId; + public String phoneNumberId; + public String contactWaId; + public String contactName; + public Long leadUuid; + public Long ownerUserId; + public boolean ownerManual; + public LocalDateTime lastInboundAt; + public LocalDateTime lastMessageAt; + public String lastMessagePreview; + public LocalDateTime createdAt; +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaMessage.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaMessage.java new file mode 100644 index 0000000..f6bf455 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaMessage.java @@ -0,0 +1,34 @@ +package com.solvway.services.whatsapp.model; + +import jakarta.persistence.*; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Entity +@Table(name = "wa_message") +public class WaMessage { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public String uuid; + public Long conversationId; + public String direction; + public String wamid; + public String type; + @Column(columnDefinition = "text") + public String body; + public String templateName; + public String mediaId; + public String mediaMime; + public String mediaFilename; + public BigDecimal locationLat; + public BigDecimal locationLng; + public String locationName; + public String status; + public String errorCode; + public String errorTitle; + public Long sentByUserId; + public LocalDateTime createdAt; + public LocalDateTime statusAt; +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaRead.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaRead.java new file mode 100644 index 0000000..dd8fae3 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaRead.java @@ -0,0 +1,14 @@ +package com.solvway.services.whatsapp.model; + +import jakarta.persistence.*; + +@Entity +@Table(name = "wa_read") +@IdClass(WaReadId.class) +public class WaRead { + @Id + public Long conversationId; + @Id + public Long userId; + public Long lastReadMessageId; +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaReadId.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaReadId.java new file mode 100644 index 0000000..e66bb7f --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaReadId.java @@ -0,0 +1,5 @@ +package com.solvway.services.whatsapp.model; + +import java.io.Serializable; + +public record WaReadId(Long conversationId, Long userId) implements Serializable {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaTemplate.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaTemplate.java new file mode 100644 index 0000000..38b011b --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaTemplate.java @@ -0,0 +1,22 @@ +package com.solvway.services.whatsapp.model; + +import jakarta.persistence.*; + +import java.time.LocalDateTime; + +@Entity +@Table(name = "wa_template") +public class WaTemplate { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public Long companyId; + public String name; + public String language; + public String category; + public String status; + @Column(columnDefinition = "text") + public String bodyText; + public int paramCount; + public LocalDateTime syncedAt; +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java new file mode 100644 index 0000000..0d4f9f1 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java @@ -0,0 +1,30 @@ +package com.solvway.services.whatsapp.repository; + +import com.solvway.services.whatsapp.model.WaConversation; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.Optional; + +public interface WaConversationRepository extends JpaRepository { + Optional findByCompanyIdAndContactWaId(Long companyId, String contactWaId); + + /** + * Records an inbound message on the conversation. Touches only the inbound columns, never owner_user_id, + * owner_manual or lead_uuid, which linking and manual reassignment write concurrently. Timestamps only move + * forward and an older message never replaces a newer preview (MySQL applies SET left to right, so the preview + * is decided before last_message_at moves). A null name keeps the stored one. + */ + @Transactional + @Modifying + @Query(value = "UPDATE wa_conversation SET contact_name = COALESCE(:name, contact_name), phone_number_id = :phoneNumberId, " + + "last_inbound_at = GREATEST(COALESCE(last_inbound_at, :at), :at), " + + "last_message_preview = CASE WHEN last_message_at IS NULL OR :at >= last_message_at THEN :preview ELSE last_message_preview END, " + + "last_message_at = GREATEST(COALESCE(last_message_at, :at), :at) WHERE id = :id", nativeQuery = true) + int recordInbound(@Param("id") Long id, @Param("name") String name, @Param("phoneNumberId") String phoneNumberId, + @Param("at") LocalDateTime at, @Param("preview") String preview); +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaMessageRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaMessageRepository.java new file mode 100644 index 0000000..e888ca1 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaMessageRepository.java @@ -0,0 +1,12 @@ +package com.solvway.services.whatsapp.repository; + +import com.solvway.services.whatsapp.model.WaMessage; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface WaMessageRepository extends JpaRepository { + boolean existsByWamid(String wamid); + + Optional findByWamidAndDirection(String wamid, String direction); +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaReadRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaReadRepository.java new file mode 100644 index 0000000..4346e82 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaReadRepository.java @@ -0,0 +1,7 @@ +package com.solvway.services.whatsapp.repository; + +import com.solvway.services.whatsapp.model.WaRead; +import com.solvway.services.whatsapp.model.WaReadId; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface WaReadRepository extends JpaRepository {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaTemplateRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaTemplateRepository.java new file mode 100644 index 0000000..090b3f4 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaTemplateRepository.java @@ -0,0 +1,6 @@ +package com.solvway.services.whatsapp.repository; + +import com.solvway.services.whatsapp.model.WaTemplate; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface WaTemplateRepository extends JpaRepository {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java new file mode 100644 index 0000000..ab029cd --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java @@ -0,0 +1,92 @@ +package com.solvway.services.whatsapp.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.solvway.services.whatsapp.config.WhatsAppSettings; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Maps each configured WhatsApp number to its company id, resolved through the system service's + * {@code GET /company/findByCode/{code}} (service id address, like the other services' SystemService). + * A code with no company is skipped for good; a code whose lookup failed is retried on the next use. + */ +@Component +public class CompanyDirectory { + + public record Company(long id, String code) {} + + private static final Logger log = LoggerFactory.getLogger(CompanyDirectory.class); + private static final Duration RETRY_COOLDOWN = Duration.ofSeconds(30); + private static final String FIND_BY_CODE = "http://service-system/company/findByCode/{code}"; + + private final WhatsAppSettings settings; + private final RestTemplate rest; + private final Clock clock; + private volatile Instant lastFailure; + private final Map byPhoneNumberId = new ConcurrentHashMap<>(); + private final Set unresolved = ConcurrentHashMap.newKeySet(); + + @Autowired + public CompanyDirectory(WhatsAppSettings settings, RestTemplateBuilder builder) { + this(settings, builder.setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(5)).build(), Clock.systemUTC()); + } + + CompanyDirectory(WhatsAppSettings settings, RestTemplate rest, Clock clock) { + this.settings = settings; + this.rest = rest; + this.clock = clock; + settings.companies().forEach(c -> unresolved.add(c.code())); + } + + @EventListener(ApplicationReadyEvent.class) + void resolveAtStartup() { + resolve(); + } + + public Optional byPhoneNumberId(String phoneNumberId) { + if (!unresolved.isEmpty() && !coolingDown()) { + resolve(); + } + return Optional.ofNullable(byPhoneNumberId.get(phoneNumberId)); + } + + private boolean coolingDown() { + Instant failed = lastFailure; + return failed != null && clock.instant().isBefore(failed.plus(RETRY_COOLDOWN)); + } + + // ponytail: unreachable system service is retried at most every 30 s (flat cooldown); exponential backoff if that is ever noisy. + private synchronized void resolve() { + for (WhatsAppSettings.CompanyConfig c : settings.companies()) { + if (!unresolved.contains(c.code())) { + continue; + } + try { + JsonNode company = rest.getForObject(FIND_BY_CODE, JsonNode.class, c.code()); + if (company != null && company.hasNonNull("id")) { + byPhoneNumberId.put(c.phoneNumberId(), new Company(company.get("id").asLong(), c.code())); + } else { + log.warn("WhatsApp company {} skipped: no company with that code", c.code()); + } + unresolved.remove(c.code()); + } catch (RuntimeException e) { + lastFailure = clock.instant(); + log.warn("WhatsApp company {} not resolved yet, system service unreachable; will retry after the cooldown", c.code()); + } + } + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/IngestResult.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/IngestResult.java new file mode 100644 index 0000000..a24315a --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/IngestResult.java @@ -0,0 +1,4 @@ +package com.solvway.services.whatsapp.service; + +/** Counts only: messages stored, redeliveries skipped, items dropped (number not matched), statuses applied or ignored. */ +public record IngestResult(int accepted, int duplicates, int dropped, int statusesApplied, int statusesIgnored) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java new file mode 100644 index 0000000..546c870 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java @@ -0,0 +1,209 @@ +package com.solvway.services.whatsapp.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.solvway.services.whatsapp.dto.WebhookIngestRequest; +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.model.WaMessage; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import com.solvway.services.whatsapp.repository.WaMessageRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +/** + * Stores Meta webhook messages and delivery statuses. Deliberately not transactional: each repository call is its own + * transaction, so a unique-wamid violation on a redelivery cannot poison the rest of the batch. The conversation is + * updated through a targeted UPDATE, never a whole-entity save, so it cannot overwrite owner or lead columns that + * linking and manual reassignment write concurrently. + * Logs ids and counts only, never message text, numbers or names. + */ +@Service +public class WebhookIngestService { + + private static final Logger log = LoggerFactory.getLogger(WebhookIngestService.class); + private static final Set MEDIA = Set.of("image", "document", "audio", "video", "sticker"); + private static final List STATUS_RANK = List.of("pending", "sent", "delivered", "read"); + private static final int PREVIEW_MAX = 80; + + private static final class Counts { + int accepted, duplicates, dropped, applied, ignored; + } + + private final CompanyDirectory companies; + private final WaConversationRepository conversations; + private final WaMessageRepository messages; + + public WebhookIngestService(CompanyDirectory companies, WaConversationRepository conversations, WaMessageRepository messages) { + this.companies = companies; + this.conversations = conversations; + this.messages = messages; + } + + public IngestResult ingest(WebhookIngestRequest request) { + JsonNode entries = request.payload() == null ? null : request.payload().get("entry"); + if (entries == null || !entries.isArray()) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); + } + Set matched = request.matchedCompanyCodes() == null ? Set.of() + : request.matchedCompanyCodes().stream().map(String::toUpperCase).collect(Collectors.toSet()); + Counts c = new Counts(); + for (JsonNode entry : entries) { + for (JsonNode change : entry.path("changes")) { + if (!"messages".equals(change.path("field").asText())) { + continue; + } + JsonNode value = change.path("value"); + String phoneNumberId = value.path("metadata").path("phone_number_id").asText(""); + CompanyDirectory.Company company = companies.byPhoneNumberId(phoneNumberId) + .filter(co -> matched.contains(co.code().toUpperCase())).orElse(null); + if (company == null) { + c.dropped += value.path("messages").size() + value.path("statuses").size(); + continue; + } + value.path("messages").forEach(m -> message(company, phoneNumberId, value, m, c)); + value.path("statuses").forEach(s -> status(s, c)); + } + } + log.info("WhatsApp webhook: accepted={} duplicates={} dropped={} statusesApplied={} statusesIgnored={}", + c.accepted, c.duplicates, c.dropped, c.applied, c.ignored); + return new IngestResult(c.accepted, c.duplicates, c.dropped, c.applied, c.ignored); + } + + private void message(CompanyDirectory.Company company, String phoneNumberId, JsonNode value, JsonNode m, Counts c) { + String wamid = text(m, "id"); + String from = text(m, "from"); + if (wamid == null || from == null) { + c.dropped++; + return; + } + if (messages.existsByWamid(wamid)) { + c.duplicates++; + return; + } + LocalDateTime at = time(text(m, "timestamp")); + WaMessage msg = toMessage(m, wamid, at); + WaConversation conv = conversations.findByCompanyIdAndContactWaId(company.id(), from) + .orElseGet(() -> newConversation(company.id(), from)); + msg.conversationId = conv.id; + try { + messages.save(msg); + } catch (DataIntegrityViolationException e) { // a concurrent delivery of the same wamid won the unique key + c.duplicates++; + return; + } + conversations.recordInbound(conv.id, cut(contactName(value, from), 255), phoneNumberId, at, preview(msg)); + c.accepted++; + } + + /** The one place a conversation is first created; lead and owner linking hooks in here. */ + private WaConversation newConversation(Long companyId, String contactWaId) { + WaConversation conv = new WaConversation(); + conv.uuid = UUID.randomUUID().toString(); + conv.companyId = companyId; + conv.contactWaId = contactWaId; + conv.phoneNumberId = ""; + conv.createdAt = LocalDateTime.now(); + try { + return conversations.save(conv); + } catch (DataIntegrityViolationException e) { // a concurrent first message created it + return conversations.findByCompanyIdAndContactWaId(companyId, contactWaId).orElseThrow(() -> e); + } + } + + private WaMessage toMessage(JsonNode m, String wamid, LocalDateTime at) { + WaMessage msg = new WaMessage(); + msg.uuid = UUID.randomUUID().toString(); + msg.direction = "IN"; + msg.wamid = wamid; + msg.createdAt = at; + String type = text(m, "type"); + if ("text".equals(type)) { + msg.type = "text"; + msg.body = text(m.path("text"), "body"); + } else if (type != null && MEDIA.contains(type)) { + JsonNode media = m.path(type); + msg.type = type; + msg.mediaId = text(media, "id"); + msg.mediaMime = text(media, "mime_type"); + msg.mediaFilename = text(media, "filename"); + msg.body = text(media, "caption"); + } else if ("location".equals(type) && m.path("location").hasNonNull("latitude") && m.path("location").hasNonNull("longitude")) { + JsonNode loc = m.path("location"); + msg.type = "location"; + msg.locationLat = loc.get("latitude").decimalValue(); + msg.locationLng = loc.get("longitude").decimalValue(); + msg.locationName = text(loc, "name"); + } else { + msg.type = "unsupported"; + } + return msg; + } + + private void status(JsonNode s, Counts c) { + WaMessage msg = messages.findByWamidAndDirection(text(s, "id") == null ? "" : text(s, "id"), "OUT").orElse(null); + String next = s.path("status").asText(); + if (msg == null) { + c.ignored++; + return; + } + String current = msg.status == null ? "pending" : msg.status; + boolean failed = "failed".equals(next); + // ponytail: read-modify-write, a racing older status could win; a conditional UPDATE on rank if that ever shows up. + boolean apply = !"failed".equals(current) + && (failed || STATUS_RANK.indexOf(next) > STATUS_RANK.indexOf(current)); + if (!apply) { + c.ignored++; + return; + } + msg.status = next; + msg.statusAt = time(text(s, "timestamp")); + if (failed) { + JsonNode error = s.path("errors").path(0); + msg.errorCode = cut(text(error, "code"), 32); + msg.errorTitle = cut(text(error, "title"), 255); + } + messages.save(msg); + c.applied++; + } + + private static String contactName(JsonNode value, String from) { + for (JsonNode contact : value.path("contacts")) { + if (from.equals(text(contact, "wa_id"))) { + return text(contact.path("profile"), "name"); + } + } + return null; + } + + private static String preview(WaMessage msg) { + String text = "text".equals(msg.type) && msg.body != null ? msg.body : "[" + msg.type + "]"; + return text.codePointCount(0, text.length()) <= PREVIEW_MAX ? text : text.substring(0, text.offsetByCodePoints(0, PREVIEW_MAX)); + } + + private static String cut(String s, int max) { + return s == null || s.length() <= max ? s : s.substring(0, max); + } + + private static String text(JsonNode node, String field) { + return node.hasNonNull(field) ? node.get(field).asText() : null; + } + + private static LocalDateTime time(String epochSeconds) { + try { + return LocalDateTime.ofInstant(Instant.ofEpochSecond(Long.parseLong(epochSeconds)), ZoneId.systemDefault()); + } catch (RuntimeException e) { // missing or malformed timestamp: use arrival time + return LocalDateTime.now(); + } + } +} diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/controller/WebhookControllerTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/controller/WebhookControllerTest.java new file mode 100644 index 0000000..2f3f997 --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/controller/WebhookControllerTest.java @@ -0,0 +1,60 @@ +package com.solvway.services.whatsapp.controller; + +import com.solvway.services.whatsapp.dto.WebhookIngestRequest; +import com.solvway.services.whatsapp.service.IngestResult; +import com.solvway.services.whatsapp.service.WebhookIngestService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.server.ResponseStatusException; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class WebhookControllerTest { + + private WebhookIngestService service; + private MockMvc mvc; + + @BeforeEach + void setUp() { + service = mock(WebhookIngestService.class); + mvc = MockMvcBuilders.standaloneSetup(new WebhookController(service)).setControllerAdvice(new ErrorHandler()).build(); + } + + @Test + void answersWithTheCounts() throws Exception { + when(service.ingest(any(WebhookIngestRequest.class))).thenReturn(new IngestResult(2, 1, 3, 0, 0)); + + mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON) + .content("{\"matchedCompanyCodes\":[\"INS\"],\"payload\":{\"entry\":[]}}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.accepted").value(2)) + .andExpect(jsonPath("$.duplicates").value(1)) + .andExpect(jsonPath("$.dropped").value(3)); + } + + @Test + void anUnreadableBodyIsInvalidPayload() throws Exception { + mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON).content("{not json")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.detail").value("INVALID_PAYLOAD")); + } + + @Test + void aPayloadTheServiceRejectsIsInvalidPayload() throws Exception { + when(service.ingest(any(WebhookIngestRequest.class))) + .thenThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD")); + + mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON).content("{\"payload\":{}}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.detail").value("INVALID_PAYLOAD")); + } +} diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/CompanyDirectoryTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/CompanyDirectoryTest.java new file mode 100644 index 0000000..7b332b5 --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/CompanyDirectoryTest.java @@ -0,0 +1,129 @@ +package com.solvway.services.whatsapp.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.services.whatsapp.config.WhatsAppSettings; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class CompanyDirectoryTest { + + private static final ObjectMapper JSON = new ObjectMapper(); + private RestTemplate rest; + private WhatsAppSettings settings; + private final MutableClock clock = new MutableClock(); + + @BeforeEach + void setUp() { + rest = mock(RestTemplate.class); + MockEnvironment env = new MockEnvironment().withProperty("WHATSAPP_COMPANIES", "INS,CV"); + for (String[] c : new String[][] {{"INS", "111"}, {"CV", "222"}}) { + env.withProperty("WHATSAPP_" + c[0] + "_PHONE_NUMBER_ID", c[1]) + .withProperty("WHATSAPP_" + c[0] + "_WABA_ID", "w") + .withProperty("WHATSAPP_" + c[0] + "_ACCESS_TOKEN", "t") + .withProperty("WHATSAPP_" + c[0] + "_APP_SECRET", "s"); + } + settings = new WhatsAppSettings(env); + } + + private static JsonNode company(long id) throws Exception { + return JSON.readTree("{\"id\":" + id + ",\"code\":\"X\",\"name\":\"Co\",\"status\":\"A\"}"); + } + + @Test + void mapsPhoneNumberIdToCompanyAtStartup() throws Exception { + when(rest.getForObject(anyString(), eq(JsonNode.class), eq("INS"))).thenReturn(company(1)); + when(rest.getForObject(anyString(), eq(JsonNode.class), eq("CV"))).thenReturn(company(2)); + CompanyDirectory d = new CompanyDirectory(settings, rest, clock); + + d.resolveAtStartup(); + + assertThat(d.byPhoneNumberId("111")).contains(new CompanyDirectory.Company(1, "INS")); + assertThat(d.byPhoneNumberId("222")).contains(new CompanyDirectory.Company(2, "CV")); + assertThat(d.byPhoneNumberId("999")).isEmpty(); + } + + @Test + void skipsACodeWithNoCompany() throws Exception { + when(rest.getForObject(anyString(), eq(JsonNode.class), eq("INS"))).thenReturn(company(1)); + when(rest.getForObject(anyString(), eq(JsonNode.class), eq("CV"))).thenReturn(null); + CompanyDirectory d = new CompanyDirectory(settings, rest, clock); + + d.resolveAtStartup(); + + assertThat(d.byPhoneNumberId("111")).isPresent(); + assertThat(d.byPhoneNumberId("222")).isEmpty(); + } + + @Test + void retriesLazilyWhenTheSystemServiceWasDownAtStartup() throws Exception { + when(rest.getForObject(anyString(), eq(JsonNode.class), eq("INS"))) + .thenThrow(new ResourceAccessException("down")) + .thenReturn(company(1)); + when(rest.getForObject(anyString(), eq(JsonNode.class), eq("CV"))).thenThrow(new ResourceAccessException("down")) + .thenReturn(company(2)); + CompanyDirectory d = new CompanyDirectory(settings, rest, clock); + + d.resolveAtStartup(); // must not throw + clock.advance(Duration.ofSeconds(30)); + + assertThat(d.byPhoneNumberId("111")).contains(new CompanyDirectory.Company(1, "INS")); + assertThat(d.byPhoneNumberId("222")).contains(new CompanyDirectory.Company(2, "CV")); + } + + @Test + void waitsThirtySecondsAfterAFailedResolveBeforeTryingAgain() { + when(rest.getForObject(anyString(), eq(JsonNode.class), anyString())).thenThrow(new ResourceAccessException("down")); + CompanyDirectory d = new CompanyDirectory(settings, rest, clock); + + d.resolveAtStartup(); + clock.advance(Duration.ofSeconds(29)); + d.byPhoneNumberId("111"); + d.byPhoneNumberId("111"); + verify(rest, times(2)).getForObject(anyString(), eq(JsonNode.class), anyString()); // startup only: INS and CV + + clock.advance(Duration.ofSeconds(1)); + d.byPhoneNumberId("111"); + verify(rest, times(4)).getForObject(anyString(), eq(JsonNode.class), anyString()); // one more round + } + + private static final class MutableClock extends Clock { + private Instant now = Instant.parse("2026-12-02T00:00:00Z"); + + void advance(Duration d) { + now = now.plus(d); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now; + } + } +} diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java new file mode 100644 index 0000000..f83b66f --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java @@ -0,0 +1,362 @@ +package com.solvway.services.whatsapp.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.services.whatsapp.dto.WebhookIngestRequest; +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.model.WaMessage; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import com.solvway.services.whatsapp.repository.WaMessageRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.web.server.ResponseStatusException; + +import java.io.IOException; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class WebhookIngestServiceTest { + + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String INS_PHONE = "111"; + private static final String CV_PHONE = "222"; + + private final Map conversations = new LinkedHashMap<>(); + private final List messages = new ArrayList<>(); + private boolean existsAlwaysFalse; + private long seq; + private WaConversationRepository convRepo; + private WebhookIngestService service; + + @BeforeEach + void setUp() { + CompanyDirectory companies = mock(CompanyDirectory.class); + when(companies.byPhoneNumberId(INS_PHONE)).thenReturn(Optional.of(new CompanyDirectory.Company(1, "INS"))); + when(companies.byPhoneNumberId(CV_PHONE)).thenReturn(Optional.of(new CompanyDirectory.Company(2, "CV"))); + when(companies.byPhoneNumberId("999")).thenReturn(Optional.empty()); + + convRepo = mock(WaConversationRepository.class); + when(convRepo.findByCompanyIdAndContactWaId(any(), any())) + .thenAnswer(i -> Optional.ofNullable(conversations.get(i.getArgument(0) + "/" + i.getArgument(1)))); + when(convRepo.save(any())).thenAnswer(i -> { + WaConversation c = i.getArgument(0); + if (c.id == null) { + c.id = ++seq; + } + conversations.put(c.companyId + "/" + c.contactWaId, c); + return c; + }); + + // mirrors the SQL of WaConversationRepository.recordInbound + when(convRepo.recordInbound(any(), any(), any(), any(), any())).thenAnswer(i -> { + WaConversation c = conversations.values().stream().filter(x -> i.getArgument(0).equals(x.id)).findFirst().orElseThrow(); + LocalDateTime at = i.getArgument(3); + if (i.getArgument(1) != null) { + c.contactName = i.getArgument(1); + } + c.phoneNumberId = i.getArgument(2); + c.lastInboundAt = c.lastInboundAt == null || at.isAfter(c.lastInboundAt) ? at : c.lastInboundAt; + if (c.lastMessageAt == null || !at.isBefore(c.lastMessageAt)) { + c.lastMessagePreview = i.getArgument(4); + c.lastMessageAt = at; + } + return 1; + }); + + WaMessageRepository msgRepo = mock(WaMessageRepository.class); + when(msgRepo.existsByWamid(any())).thenAnswer(i -> !existsAlwaysFalse && byWamid(i.getArgument(0)).isPresent()); + when(msgRepo.findByWamidAndDirection(any(), any())).thenAnswer(i -> byWamid(i.getArgument(0)) + .filter(m -> m.direction.equals(i.getArgument(1)))); + when(msgRepo.save(any())).thenAnswer(i -> { + WaMessage m = i.getArgument(0); + if (m.id == null) { + if (m.wamid != null && byWamid(m.wamid).isPresent()) { + throw new DataIntegrityViolationException("uk_wa_message_wamid"); + } + m.id = ++seq; + messages.add(m); + } + return m; + }); + service = new WebhookIngestService(companies, convRepo, msgRepo); + } + + private Optional byWamid(String wamid) { + return messages.stream().filter(m -> wamid.equals(m.wamid)).findFirst(); + } + + private static JsonNode payload(String file, String... kv) throws IOException { + String text = new String(WebhookIngestServiceTest.class.getResourceAsStream("/whatsapp/" + file).readAllBytes(), + StandardCharsets.UTF_8); + Map v = new HashMap<>(Map.of("PHONE_ID", INS_PHONE, "FROM", "60111222333", "WAMID", "wamid.1", + "TS", "1764662400", "NAME", "Aisyah", "BODY", "hello", "STATUS", "sent")); + for (int i = 0; i < kv.length; i += 2) { + v.put(kv[i], kv[i + 1]); + } + for (Map.Entry e : v.entrySet()) { + text = text.replace("${" + e.getKey() + "}", e.getValue()); + } + return JSON.readTree(text); + } + + private IngestResult ingest(JsonNode payload, String... codes) { + return service.ingest(new WebhookIngestRequest(List.of(codes), payload)); + } + + private WaMessage seedOut(String wamid, String status) { + WaMessage m = new WaMessage(); + m.id = ++seq; + m.direction = "OUT"; + m.wamid = wamid; + m.type = "text"; + m.status = status; + messages.add(m); + return m; + } + + @Test + void truncatesAContactNameTo255() throws Exception { + ingest(payload("text.json", "NAME", "N".repeat(300)), "INS"); + + assertThat(conversations.get("1/60111222333").contactName).hasSize(255); + } + + @Test + void anExistingConversationIsUpdatedInPlaceNeverRewrittenWhole() throws Exception { + ingest(payload("text.json"), "INS"); + ingest(payload("text.json", "WAMID", "wamid.2", "TS", "1764662500"), "INS"); + + verify(convRepo, times(1)).save(any()); // only the insert of the new conversation + verify(convRepo, times(2)).recordInbound(any(), any(), any(), any(), any()); + } + + @Test + void anOlderMessageNeverOverwritesANewerPreview() throws Exception { + ingest(payload("text.json", "WAMID", "wamid.2", "TS", "1764662500", "BODY", "newer"), "INS"); + ingest(payload("text.json", "WAMID", "wamid.1", "TS", "1764662400", "BODY", "older"), "INS"); + + WaConversation c = conversations.get("1/60111222333"); + assertThat(c.lastMessagePreview).isEqualTo("newer"); + assertThat(c.lastMessageAt).isEqualTo(LocalDateTime.ofInstant(Instant.ofEpochSecond(1764662500L), ZoneId.systemDefault())); + } + + @Test + void ingestIsNotTransactionalSoEachRepositoryCallIsItsOwnTransaction() throws Exception { + assertThat(WebhookIngestService.class.getAnnotation(org.springframework.transaction.annotation.Transactional.class)).isNull(); + assertThat(WebhookIngestService.class.getAnnotation(jakarta.transaction.Transactional.class)).isNull(); + var ingest = WebhookIngestService.class.getMethod("ingest", WebhookIngestRequest.class); + assertThat(ingest.getAnnotation(org.springframework.transaction.annotation.Transactional.class)).isNull(); + assertThat(ingest.getAnnotation(jakarta.transaction.Transactional.class)).isNull(); + } + + @Test + void acceptsOnlyTheMatchedCompanysNumber() throws Exception { + IngestResult own = ingest(payload("text.json"), "INS"); + IngestResult other = ingest(payload("text.json", "PHONE_ID", CV_PHONE, "WAMID", "wamid.2"), "INS"); + + assertThat(own.accepted()).isEqualTo(1); + assertThat(other.accepted()).isZero(); + assertThat(other.dropped()).isEqualTo(1); + assertThat(conversations).containsOnlyKeys("1/60111222333"); + assertThat(messages).hasSize(1); + } + + @Test + void dropsAnUnknownNumber() throws Exception { + IngestResult r = ingest(payload("text.json", "PHONE_ID", "999"), "INS", "CV"); + + assertThat(r.dropped()).isEqualTo(1); + assertThat(conversations).isEmpty(); + assertThat(messages).isEmpty(); + } + + @Test + void keepsInsAndCvApart() throws Exception { + ingest(payload("text.json"), "INS", "CV"); + ingest(payload("text.json", "PHONE_ID", CV_PHONE, "WAMID", "wamid.2"), "INS", "CV"); + + assertThat(conversations).containsOnlyKeys("1/60111222333", "2/60111222333"); + assertThat(conversations.get("1/60111222333").phoneNumberId).isEqualTo(INS_PHONE); + assertThat(conversations.get("2/60111222333").phoneNumberId).isEqualTo(CV_PHONE); + assertThat(messages).extracting(m -> m.conversationId).doesNotHaveDuplicates(); + } + + @Test + void storesARedeliveredMessageOnce() throws Exception { + ingest(payload("text.json"), "INS"); + IngestResult again = ingest(payload("text.json"), "INS"); + + assertThat(messages).hasSize(1); + assertThat(again.accepted()).isZero(); + assertThat(again.duplicates()).isEqualTo(1); + } + + @Test + void survivesAConcurrentDuplicateRacingPastTheExistsCheck() throws Exception { + ingest(payload("text.json"), "INS"); + existsAlwaysFalse = true; // the other delivery inserted between our check and our insert + + IngestResult r = ingest(payload("text.json"), "INS"); + + assertThat(r.duplicates()).isEqualTo(1); + assertThat(messages).hasSize(1); + } + + @Test + void createsTheConversationFromTheFirstMessage() throws Exception { + ingest(payload("text.json"), "INS"); + + WaConversation c = conversations.get("1/60111222333"); + LocalDateTime at = LocalDateTime.ofInstant(Instant.ofEpochSecond(1764662400L), ZoneId.systemDefault()); + assertThat(c.contactName).isEqualTo("Aisyah"); + assertThat(c.uuid).isNotBlank(); + assertThat(c.leadUuid).isNull(); + assertThat(c.ownerUserId).isNull(); + assertThat(c.lastInboundAt).isEqualTo(at); + assertThat(c.lastMessageAt).isEqualTo(at); + assertThat(c.lastMessagePreview).isEqualTo("hello"); + WaMessage m = messages.get(0); + assertThat(m.direction).isEqualTo("IN"); + assertThat(m.type).isEqualTo("text"); + assertThat(m.body).isEqualTo("hello"); + assertThat(m.conversationId).isEqualTo(c.id); + } + + @Test + void updatesAnExistingConversationAndTakesTheLatestContactName() throws Exception { + ingest(payload("text.json"), "INS"); + ingest(payload("text.json", "WAMID", "wamid.2", "TS", "1764662500", "NAME", "Aisyah R", "BODY", "again"), "INS"); + + assertThat(conversations).hasSize(1); + WaConversation c = conversations.get("1/60111222333"); + assertThat(c.contactName).isEqualTo("Aisyah R"); + assertThat(c.lastMessagePreview).isEqualTo("again"); + assertThat(c.lastMessageAt).isEqualTo(LocalDateTime.ofInstant(Instant.ofEpochSecond(1764662500L), ZoneId.systemDefault())); + } + + @Test + void truncatesThePreviewAtEightyCharactersButKeepsTheFullBody() throws Exception { + String body = "x".repeat(100); + ingest(payload("text.json", "BODY", body), "INS"); + + assertThat(conversations.get("1/60111222333").lastMessagePreview).hasSize(80); + assertThat(messages.get(0).body).isEqualTo(body); + } + + @Test + void storesAnImageWithItsCaption() throws Exception { + ingest(payload("image.json"), "INS"); + + WaMessage m = messages.get(0); + assertThat(m.type).isEqualTo("image"); + assertThat(m.mediaId).isEqualTo("MEDIA-IMG-1"); + assertThat(m.mediaMime).isEqualTo("image/jpeg"); + assertThat(m.body).isEqualTo("BRIDAL"); + assertThat(conversations.get("1/60111222333").lastMessagePreview).isEqualTo("[image]"); + } + + @Test + void storesADocumentWithItsFilename() throws Exception { + ingest(payload("document.json"), "INS"); + + WaMessage m = messages.get(0); + assertThat(m.type).isEqualTo("document"); + assertThat(m.mediaFilename).isEqualTo("quote.pdf"); + assertThat(m.mediaMime).isEqualTo("application/pdf"); + assertThat(m.body).isNull(); + } + + @Test + void storesALocation() throws Exception { + ingest(payload("location.json"), "INS"); + + WaMessage m = messages.get(0); + assertThat(m.type).isEqualTo("location"); + assertThat(m.locationLat).isEqualByComparingTo(new BigDecimal("3.139")); + assertThat(m.locationLng).isEqualByComparingTo(new BigDecimal("101.6869")); + assertThat(m.locationName).isEqualTo("KLCC"); + } + + @Test + void storesAnUnsupportedType() throws Exception { + ingest(payload("reaction.json"), "INS"); + + assertThat(messages.get(0).type).isEqualTo("unsupported"); + assertThat(conversations.get("1/60111222333").lastMessagePreview).isEqualTo("[unsupported]"); + } + + @Test + void readThenDeliveredStaysRead() throws Exception { + WaMessage out = seedOut("wamid.out", "sent"); + + ingest(payload("status.json", "WAMID", "wamid.out", "STATUS", "read", "TS", "1764662500"), "INS"); + IngestResult late = ingest(payload("status.json", "WAMID", "wamid.out", "STATUS", "delivered", "TS", "1764662600"), "INS"); + + assertThat(out.status).isEqualTo("read"); + assertThat(out.statusAt).isEqualTo(LocalDateTime.ofInstant(Instant.ofEpochSecond(1764662500L), ZoneId.systemDefault())); + assertThat(late.statusesIgnored()).isEqualTo(1); + } + + @Test + void movesForwardThroughSentDeliveredRead() throws Exception { + WaMessage out = seedOut("wamid.out", "pending"); + for (String s : List.of("sent", "delivered", "read")) { + ingest(payload("status.json", "WAMID", "wamid.out", "STATUS", s), "INS"); + assertThat(out.status).isEqualTo(s); + } + } + + @Test + void failedAfterDeliveredRecordsTheError() throws Exception { + WaMessage out = seedOut("wamid.out", "delivered"); + + IngestResult r = ingest(payload("status-failed.json", "WAMID", "wamid.out"), "INS"); + + assertThat(out.status).isEqualTo("failed"); + assertThat(out.errorCode).isEqualTo("131047"); + assertThat(out.errorTitle).isEqualTo("Re-engagement message"); + assertThat(r.statusesApplied()).isEqualTo(1); + } + + @Test + void ignoresAStatusForAnUnknownWamid() throws Exception { + IngestResult r = ingest(payload("status.json", "WAMID", "wamid.nope"), "INS"); + + assertThat(r.statusesIgnored()).isEqualTo(1); + assertThat(messages).isEmpty(); + } + + @Test + void dropsAStatusFromAnUnmatchedNumber() throws Exception { + WaMessage out = seedOut("wamid.out", "sent"); + + IngestResult r = ingest(payload("status.json", "WAMID", "wamid.out", "STATUS", "read", "PHONE_ID", CV_PHONE), "INS"); + + assertThat(r.dropped()).isEqualTo(1); + assertThat(out.status).isEqualTo("sent"); + } + + @Test + void rejectsAMalformedPayload() { + assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(List.of("INS"), null))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode().value()).isEqualTo(400); + assertThat(e.getReason()).isEqualTo("INVALID_PAYLOAD"); + }); + assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(List.of("INS"), JSON.createObjectNode()))) + .isInstanceOf(ResponseStatusException.class); + } +} diff --git a/solvway-services-whatsapp/src/test/resources/whatsapp/document.json b/solvway-services-whatsapp/src/test/resources/whatsapp/document.json new file mode 100644 index 0000000..e7ee07d --- /dev/null +++ b/solvway-services-whatsapp/src/test/resources/whatsapp/document.json @@ -0,0 +1 @@ +{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"contacts":[{"profile":{"name":"${NAME}"},"wa_id":"${FROM}"}],"messages":[{"from":"${FROM}","id":"${WAMID}","timestamp":"${TS}","type":"document","document":{"filename":"quote.pdf","mime_type":"application/pdf","sha256":"abc","id":"MEDIA-DOC-1"}}]}}]}]} diff --git a/solvway-services-whatsapp/src/test/resources/whatsapp/image.json b/solvway-services-whatsapp/src/test/resources/whatsapp/image.json new file mode 100644 index 0000000..0cdb222 --- /dev/null +++ b/solvway-services-whatsapp/src/test/resources/whatsapp/image.json @@ -0,0 +1 @@ +{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"contacts":[{"profile":{"name":"${NAME}"},"wa_id":"${FROM}"}],"messages":[{"from":"${FROM}","id":"${WAMID}","timestamp":"${TS}","type":"image","image":{"caption":"BRIDAL","mime_type":"image/jpeg","sha256":"abc","id":"MEDIA-IMG-1"}}]}}]}]} diff --git a/solvway-services-whatsapp/src/test/resources/whatsapp/location.json b/solvway-services-whatsapp/src/test/resources/whatsapp/location.json new file mode 100644 index 0000000..55f5c77 --- /dev/null +++ b/solvway-services-whatsapp/src/test/resources/whatsapp/location.json @@ -0,0 +1 @@ +{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"contacts":[{"profile":{"name":"${NAME}"},"wa_id":"${FROM}"}],"messages":[{"from":"${FROM}","id":"${WAMID}","timestamp":"${TS}","type":"location","location":{"latitude":3.139,"longitude":101.6869,"name":"KLCC"}}]}}]}]} diff --git a/solvway-services-whatsapp/src/test/resources/whatsapp/reaction.json b/solvway-services-whatsapp/src/test/resources/whatsapp/reaction.json new file mode 100644 index 0000000..e32d57e --- /dev/null +++ b/solvway-services-whatsapp/src/test/resources/whatsapp/reaction.json @@ -0,0 +1 @@ +{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"contacts":[{"profile":{"name":"${NAME}"},"wa_id":"${FROM}"}],"messages":[{"from":"${FROM}","id":"${WAMID}","timestamp":"${TS}","type":"reaction","reaction":{"message_id":"wamid.X","emoji":"👍"}}]}}]}]} diff --git a/solvway-services-whatsapp/src/test/resources/whatsapp/status-failed.json b/solvway-services-whatsapp/src/test/resources/whatsapp/status-failed.json new file mode 100644 index 0000000..620e9f3 --- /dev/null +++ b/solvway-services-whatsapp/src/test/resources/whatsapp/status-failed.json @@ -0,0 +1 @@ +{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"statuses":[{"id":"${WAMID}","status":"failed","timestamp":"${TS}","recipient_id":"60111222333","errors":[{"code":131047,"title":"Re-engagement message","message":"x","error_data":{"details":"d"}}]}]}}]}]} diff --git a/solvway-services-whatsapp/src/test/resources/whatsapp/status.json b/solvway-services-whatsapp/src/test/resources/whatsapp/status.json new file mode 100644 index 0000000..49d98cf --- /dev/null +++ b/solvway-services-whatsapp/src/test/resources/whatsapp/status.json @@ -0,0 +1 @@ +{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"statuses":[{"id":"${WAMID}","status":"${STATUS}","timestamp":"${TS}","recipient_id":"60111222333"}]}}]}]} diff --git a/solvway-services-whatsapp/src/test/resources/whatsapp/text.json b/solvway-services-whatsapp/src/test/resources/whatsapp/text.json new file mode 100644 index 0000000..cd03199 --- /dev/null +++ b/solvway-services-whatsapp/src/test/resources/whatsapp/text.json @@ -0,0 +1 @@ +{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"contacts":[{"profile":{"name":"${NAME}"},"wa_id":"${FROM}"}],"messages":[{"from":"${FROM}","id":"${WAMID}","timestamp":"${TS}","type":"text","text":{"body":"${BODY}"}}]}}]}]} -- 2.54.1 From ae96e316ecd21cebe549e8a081e29e10aa3f94b7 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 01:44:35 +0800 Subject: [PATCH 06/23] feat: counter WhatsApp contact lookup and lead-changed notify GET /counter/lead/whatsappContact returns the company's newest lead for a mobile with its latest salesperson (the Leads list's definition). Event lead capture, registration and salesperson changes notify the WhatsApp service after commit, best effort, never logging the mobile. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../RestApiWhatsappServiceConstant.java | 6 + .../counter/controller/LeadController.java | 6 + .../services/counter/repo/LeadRepository.java | 12 +- .../counter/service/EventLeadService.java | 23 ++- .../services/counter/service/LeadService.java | 8 + .../counter/service/RegistrationService.java | 2 + .../counter/service/WhatsappNotifier.java | 58 +++++++ .../counter/service/InvitationWiringTest.java | 2 +- .../counter/service/WhatsappLookupTest.java | 94 +++++++++++ .../counter/service/WhatsappNotifierTest.java | 80 ++++++++++ .../service/WhatsappNotifyOnSaveTest.java | 148 ++++++++++++++++++ 11 files changed, 434 insertions(+), 5 deletions(-) create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/constant/RestApiWhatsappServiceConstant.java create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/WhatsappNotifier.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappLookupTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappNotifierTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappNotifyOnSaveTest.java diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/constant/RestApiWhatsappServiceConstant.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/constant/RestApiWhatsappServiceConstant.java new file mode 100644 index 0000000..26b8644 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/constant/RestApiWhatsappServiceConstant.java @@ -0,0 +1,6 @@ +package com.solvway.services.counter.constant; + +public class RestApiWhatsappServiceConstant { + public static final String SERVICE_ID_WHATSAPP = "service-whatsapp"; + public static final String API_REST_WHATSAPP_OWNERSHIP_LEAD_CHANGED = "/whatsapp/ownership/leadChanged"; +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java index 21efd54..6fc11a9 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java @@ -23,6 +23,12 @@ public class LeadController { @GetMapping("/lead/detail/{leadUuid}") public LeadDetail detail(@PathVariable("leadUuid") long leadUuid) { return leadService.detail(null, leadUuid); } + @GetMapping("/lead/whatsappContact") + public WhatsappContact whatsappContact(@RequestParam("companyId") long companyId, + @RequestParam("mobileE164") String mobileE164) { + return leadService.whatsappContact(companyId, mobileE164); + } + @PostMapping("/lead/update") public LeadDetail update(@RequestBody LeadUpdateRequest req) { return leadService.update(req); } } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java index 62a4a4a..4520e39 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java @@ -46,13 +46,16 @@ public interface LeadRepository extends JpaRepository { String SEARCH_WHERE = " WHERE (:companyId IS NULL OR l.company_id = :companyId) AND ((:q IS NULL AND :digits IS NULL) OR LOWER(l.name) LIKE :q ESCAPE '\\\\'" + " OR l.email_normalised LIKE :q ESCAPE '\\\\' OR (:digits IS NOT NULL AND l.mobile_e164 LIKE :digits))"; + /** The most recently captured event lead that has a salesperson, per lead; alias sp. Shared by search and the WhatsApp lookup. */ + String LATEST_SALESPERSON_JOIN = " LEFT JOIN (SELECT lead_uuid, salesperson_user_id, ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) rn" + + " FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId) AND salesperson_user_id IS NOT NULL) sp ON sp.lead_uuid = l.uuid AND sp.rn = 1"; + String SEARCH_FROM = " FROM `lead` l" + " LEFT JOIN (SELECT lead_uuid, COUNT(*) cnt FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId) GROUP BY lead_uuid) c ON c.lead_uuid = l.uuid" + " LEFT JOIN (SELECT lead_uuid, event_uuid, captured_at, ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) rn" + " FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId)) last ON last.lead_uuid = l.uuid AND last.rn = 1" + " LEFT JOIN `event` ev ON ev.uuid = last.event_uuid" - + " LEFT JOIN (SELECT lead_uuid, salesperson_user_id, ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) rn" - + " FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId) AND salesperson_user_id IS NOT NULL) sp ON sp.lead_uuid = l.uuid AND sp.rn = 1" + + LATEST_SALESPERSON_JOIN + SEARCH_WHERE; /** @@ -69,4 +72,9 @@ public interface LeadRepository extends JpaRepository { countQuery = "SELECT COUNT(*) FROM `lead` l" + SEARCH_WHERE) Page search(@Param("companyId") Long companyId, @Param("q") String q, @Param("digits") String digits, Pageable pageable); + + /** Salesperson of the lead's most recently captured event lead that has one; null when none. */ + @Query(nativeQuery = true, value = "SELECT sp.salesperson_user_id FROM `lead` l" + LATEST_SALESPERSON_JOIN + + " WHERE l.company_id = :companyId AND l.uuid = :leadUuid") + Long latestSalespersonUserId(@Param("companyId") long companyId, @Param("leadUuid") long leadUuid); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java index 13a5739..5ad25eb 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java @@ -53,12 +53,28 @@ public class EventLeadService { private final EventLeadStatusChangeRepository eventLeadStatusChangeRepository; private final EventRepository eventRepository; private final GuestLinker guestLinker; + private final WhatsappNotifier whatsappNotifier; - // ponytail: null event repository and linker keep the pre-invitation wiring working; drop once callers pass both. + // ponytail: null event repository, linker and notifier keep older wiring working; drop once callers pass all. public EventLeadService(LeadRepository leadRepository, EventLeadRepository eventLeadRepository, EventLeadInterestRepository eventLeadInterestRepository, EventLeadStatusChangeRepository eventLeadStatusChangeRepository) { - this(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository, null, null); + this(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository, null, null, null); + } + + public EventLeadService(LeadRepository leadRepository, EventLeadRepository eventLeadRepository, + EventLeadInterestRepository eventLeadInterestRepository, + EventLeadStatusChangeRepository eventLeadStatusChangeRepository, + EventRepository eventRepository, GuestLinker guestLinker) { + this(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository, + eventRepository, guestLinker, null); + } + + /** The one place every capture or salesperson change tells the WhatsApp service; skipped for a lead with no mobile. */ + public void notifyLeadChanged(Lead lead) { + if (whatsappNotifier != null && lead.getMobileE164() != null) { + whatsappNotifier.leadChanged(lead.getCompanyId(), lead.getMobileE164(), lead.getUuid()); + } } /** True when today is one of the event's days. */ @@ -144,6 +160,7 @@ public class EventLeadService { recordStatusChange(eventLead, null, eventLead.getStatus(), eventLead.getCapturedAt(), req.doneBy()); linkGuest(req.eventUuid(), eventLead, lead); List interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds()); + notifyLeadChanged(lead); return detail(eventLead, lead, interestIds); } @@ -180,6 +197,7 @@ public class EventLeadService { requireCompany(req.companyId()); EventLead eventLead = eventLeadRepository.findByUuidAndCompanyId(req.eventLeadUuid(), req.companyId()) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + boolean salespersonChanged = !Objects.equals(eventLead.getSalespersonUserId(), req.salespersonUserId()); eventLead.setSalespersonUserId(req.salespersonUserId()); eventLead.setTemperature(blankToNull(req.temperature())); String oldStatus = eventLead.getStatus(); @@ -201,6 +219,7 @@ public class EventLeadService { List interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds()); Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), req.companyId()) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + if (salespersonChanged) notifyLeadChanged(lead); return detail(eventLead, lead, interestIds); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java index 97bc7db..89ac5e0 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java @@ -6,6 +6,7 @@ import com.solvway.services.counter.dto.LeadSearchRequest; import com.solvway.services.counter.dto.LeadSummary; import com.solvway.services.counter.dto.LeadUpdateRequest; import com.solvway.services.counter.dto.SharedContact; +import com.solvway.services.counter.dto.WhatsappContact; import com.solvway.services.counter.model.Event; import com.solvway.services.counter.model.EventLead; import com.solvway.services.counter.model.Lead; @@ -51,6 +52,13 @@ public class LeadService { : find(companyId, leadUuid)); } + /** The newest lead of the company with this mobile and its latest salesperson; 404 when there is none. */ + public WhatsappContact whatsappContact(long companyId, String mobileE164) { + Lead l = leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(companyId, mobileE164) + .orElseThrow(LeadService::notFound); + return new WhatsappContact(l.getUuid(), l.getName(), leadRepository.latestSalespersonUserId(companyId, l.getUuid())); + } + @Transactional public LeadDetail update(LeadUpdateRequest req) { if (req.companyId() == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java index 7cbe3c2..cc65fda 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/RegistrationService.java @@ -119,6 +119,7 @@ public class RegistrationService { eventLeadService.recordStatusChange(e, null, "OPEN", e.getCapturedAt(), QR); eventLeadService.saveInterests(e.getId(), req.companyId(), req.interestIds()); link(req, e, lead); + eventLeadService.notifyLeadChanged(lead); return new RegisterResult(match.isEmpty() ? "CREATED" : "LINKED", String.valueOf(e.getUuid())); } @@ -133,6 +134,7 @@ public class RegistrationService { eventLeadRepository.save(e); } link(req, e, lead); + if (assign) eventLeadService.notifyLeadChanged(lead); return new RegisterResult(assign ? "ASSIGNED" : "ALREADY_CAPTURED", String.valueOf(e.getUuid())); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/WhatsappNotifier.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/WhatsappNotifier.java new file mode 100644 index 0000000..ee3a293 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/WhatsappNotifier.java @@ -0,0 +1,58 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.constant.RestApiWhatsappServiceConstant; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.web.client.RestTemplate; + +import java.util.Map; + +/** + * Tells the WhatsApp service an event lead was captured or its salesperson changed, so it can re-run ownership + * (a lead's mobile edit does not notify; the nightly repair covers it). Best effort: it runs + * after the surrounding transaction commits, never throws, and logs the lead uuid only (never the mobile). + */ +@Component +@Slf4j +public class WhatsappNotifier { + private static final int TIMEOUT_MS = 2000; + private static final String URL = "http://" + RestApiWhatsappServiceConstant.SERVICE_ID_WHATSAPP + + RestApiWhatsappServiceConstant.API_REST_WHATSAPP_OWNERSHIP_LEAD_CHANGED; + + private final RestTemplate restTemplate; + + @Autowired + public WhatsappNotifier() { + // The shared RestTemplate bean has 5 s timeouts; this call must never hold a request thread that long. + SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory(); + f.setConnectTimeout(TIMEOUT_MS); + f.setReadTimeout(TIMEOUT_MS); + this.restTemplate = new RestTemplate(f); + } + + WhatsappNotifier(RestTemplate restTemplate) { this.restTemplate = restTemplate; } + + public void leadChanged(long companyId, String mobileE164, long leadUuid) { + if (mobileE164 == null || mobileE164.isBlank()) return; + if (!TransactionSynchronizationManager.isSynchronizationActive()) { + send(companyId, mobileE164, leadUuid); + return; + } + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override public void afterCommit() { send(companyId, mobileE164, leadUuid); } + }); + } + + private void send(long companyId, String mobileE164, long leadUuid) { + try { + restTemplate.postForLocation(URL, Map.of("companyId", companyId, "mobileE164", mobileE164)); + } catch (Exception e) { + // ponytail: no retry; the WhatsApp service also re-resolves ownership when it next sees the contact. + log.warn("WhatsApp ownership notify failed for lead {}: {}", leadUuid, e.getClass().getSimpleName()); + } + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InvitationWiringTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InvitationWiringTest.java index 8e815a2..20b08f4 100644 --- a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InvitationWiringTest.java +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InvitationWiringTest.java @@ -29,7 +29,7 @@ class InvitationWiringTest { RedisUtil.class, TransactionTemplate.class}) { mockBean(ctx, c); } - ctx.register(GuestLinker.class, EventLeadService.class, RegistrationService.class, EventService.class, + ctx.register(GuestLinker.class, WhatsappNotifier.class, EventLeadService.class, RegistrationService.class, EventService.class, EventHeadcountService.class); ctx.refresh(); diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappLookupTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappLookupTest.java new file mode 100644 index 0000000..1d1bbaf --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappLookupTest.java @@ -0,0 +1,94 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.controller.LeadController; +import com.solvway.services.counter.dto.WhatsappContact; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.LeadRepository; +import org.junit.jupiter.api.Test; +import org.springframework.data.jpa.repository.Query; +import org.springframework.http.HttpStatus; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.server.ResponseStatusException; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** GET /counter/lead/whatsappContact: newest lead for the mobile in one company, with its latest salesperson. */ +class WhatsappLookupTest { + private static final long COMPANY = 42L; + private static final String MOBILE = "+60123456789"; + + private final LeadRepository leads = mock(LeadRepository.class); + private final LeadService service = new LeadService(leads, mock(EventLeadRepository.class)); + + private static Lead lead(String name) { + Lead l = new Lead(); + l.setCompanyId(COMPANY); + l.setName(name); + l.setMobileE164(MOBILE); + return l; + } + + @Test + void newestLeadOfTheCompanyWinsAndCarriesTheLatestSalesperson() { + Lead newest = lead("Newest"); + when(leads.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(newest)); + when(leads.latestSalespersonUserId(COMPANY, newest.getUuid())).thenReturn(7L); + + assertThat(service.whatsappContact(COMPANY, MOBILE)) + .isEqualTo(new WhatsappContact(newest.getUuid(), "Newest", 7L)); + } + + @Test + void noSalespersonYieldsNullNotAnError() { + Lead l = lead("A"); + when(leads.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(l)); + when(leads.latestSalespersonUserId(COMPANY, l.getUuid())).thenReturn(null); + + assertThat(service.whatsappContact(COMPANY, MOBILE).latestSalespersonUserId()).isNull(); + } + + @Test + void otherCompanyOrUnknownMobileIs404() { + when(leads.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.whatsappContact(COMPANY, MOBILE)) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + @Test + void latestSalespersonQueryReusesTheSearchWindowAndSkipsEventLeadsWithoutOne() throws Exception { + String sql = LeadRepository.class.getMethod("latestSalespersonUserId", long.class, long.class) + .getAnnotation(Query.class).value(); + + assertThat(sql).contains(LeadRepository.LATEST_SALESPERSON_JOIN) + .contains("salesperson_user_id IS NOT NULL").contains("ORDER BY captured_at DESC, id DESC"); + assertThat(LeadRepository.SEARCH_FROM).contains(LeadRepository.LATEST_SALESPERSON_JOIN); + } + + @Test + void httpMapsFoundNotFoundAndMissingCompany() throws Exception { + LeadService svc = mock(LeadService.class); + when(svc.whatsappContact(COMPANY, MOBILE)).thenReturn(new WhatsappContact(9L, "A", 7L)); + when(svc.whatsappContact(1L, MOBILE)).thenThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new LeadController(svc)).build(); + + mvc.perform(get("/counter/lead/whatsappContact").param("companyId", "42").param("mobileE164", MOBILE)) + .andExpect(status().isOk()).andExpect(jsonPath("$.leadUuid").value(9)) + .andExpect(jsonPath("$.latestSalespersonUserId").value(7)); + mvc.perform(get("/counter/lead/whatsappContact").param("companyId", "1").param("mobileE164", MOBILE)) + .andExpect(status().isNotFound()); + mvc.perform(get("/counter/lead/whatsappContact").param("mobileE164", MOBILE)) + .andExpect(status().isBadRequest()); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappNotifierTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappNotifierTest.java new file mode 100644 index 0000000..515fb57 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappNotifierTest.java @@ -0,0 +1,80 @@ +package com.solvway.services.counter.service; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.web.client.RestTemplate; + +import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +import static org.assertj.core.api.Assertions.assertThatCode; + +class WhatsappNotifierTest { + private static final String URL = "http://service-whatsapp/whatsapp/ownership/leadChanged"; + + private final RestTemplate rest = new RestTemplate(); + private final MockRestServiceServer server = MockRestServiceServer.bindTo(rest).build(); + private final WhatsappNotifier notifier = new WhatsappNotifier(rest); + + @AfterEach + void clear() { + if (TransactionSynchronizationManager.isSynchronizationActive()) TransactionSynchronizationManager.clearSynchronization(); + } + + @Test + void postsCompanyAndMobile() { + server.expect(requestTo(URL)).andExpect(method(HttpMethod.POST)) + .andExpect(content().json("{\"companyId\":42,\"mobileE164\":\"+60123456789\"}")) + .andRespond(withSuccess()); + + notifier.leadChanged(42L, "+60123456789", 9L); + + server.verify(); + } + + @Test + void noMobileMeansNoCall() { + notifier.leadChanged(42L, null, 9L); + notifier.leadChanged(42L, " ", 9L); + + server.verify(); // no expectation set: any call would have failed + } + + @Test + void serverErrorAndConnectionFailureAreSwallowed() { + server.expect(requestTo(URL)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + server.expect(requestTo(URL)).andRespond(r -> { throw new java.net.ConnectException("refused"); }); + + assertThatCode(() -> notifier.leadChanged(42L, "+60123456789", 9L)).doesNotThrowAnyException(); + assertThatCode(() -> notifier.leadChanged(42L, "+60123456789", 9L)).doesNotThrowAnyException(); + } + + @Test + void insideATransactionTheCallWaitsForCommit() { + server.expect(requestTo(URL)).andRespond(withSuccess()); + TransactionSynchronizationManager.initSynchronization(); + + notifier.leadChanged(42L, "+60123456789", 9L); + TransactionSynchronizationManager.getSynchronizations().forEach(TransactionSynchronization::afterCommit); + + server.verify(); + } + + @Test + void aRolledBackTransactionNotifiesNobody() { + TransactionSynchronizationManager.initSynchronization(); + + notifier.leadChanged(42L, "+60123456789", 9L); + TransactionSynchronizationManager.getSynchronizations() + .forEach(s -> s.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK)); + + server.verify(); // no expectation set: any call would have failed + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappNotifyOnSaveTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappNotifyOnSaveTest.java new file mode 100644 index 0000000..52b4513 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappNotifyOnSaveTest.java @@ -0,0 +1,148 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.dto.EventLeadCaptureRequest; +import com.solvway.services.counter.dto.EventLeadUpdateRequest; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadInterestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventLeadStatusChangeRepository; +import com.solvway.services.counter.repo.LeadRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +import java.util.Optional; + +import static org.mockito.AdditionalAnswers.returnsFirstArg; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Every save path that creates an event lead or changes its salesperson tells the WhatsApp service, best effort. */ +class WhatsappNotifyOnSaveTest { + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + private static final String MOBILE = "+60123456789"; + + private final LeadRepository leads = mock(LeadRepository.class); + private final EventLeadRepository eventLeads = mock(EventLeadRepository.class); + private final WhatsappNotifier notifier = mock(WhatsappNotifier.class); + private EventLeadService service; + private RegistrationService registration; + + @BeforeEach + void setUp() { + service = new EventLeadService(leads, eventLeads, mock(EventLeadInterestRepository.class), + mock(EventLeadStatusChangeRepository.class), null, null, notifier); + registration = new RegistrationService(new TransactionTemplate(mock(PlatformTransactionManager.class)), + leads, eventLeads, service); + when(leads.saveAndFlush(any(Lead.class))).then(returnsFirstArg()); + when(eventLeads.saveAndFlush(any(EventLead.class))).then(i -> { + EventLead e = i.getArgument(0); + e.setId(1L); + return e; + }); + } + + private static Lead lead(String mobile) { + Lead l = new Lead(); + l.setCompanyId(COMPANY); + l.setMobileE164(mobile); + return l; + } + + private static EventLeadCaptureRequest capture(String mobile) { + return new EventLeadCaptureRequest(COMPANY, EVENT, null, "Aisyah", mobile, null, null, null, 7L, null, null, null, null, null, "staff"); + } + + @Test + void staffCaptureNotifiesWithTheLeadMobile() { + service.capture(capture(MOBILE)); + + verify(notifier).leadChanged(eq(COMPANY), eq(MOBILE), anyLong()); + } + + @Test + void captureWithoutMobileDoesNotNotify() { + service.capture(capture(null)); + + verify(notifier, never()).leadChanged(anyLong(), any(), anyLong()); + } + + @Test + void qrRegistrationNotifies() { + registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "A", MOBILE, null, null, null, + null, null, null)); + + verify(notifier).leadChanged(eq(COMPANY), eq(MOBILE), anyLong()); + } + + @Test + void qrRegistrationAssigningASalespersonToAnExistingCaptureNotifies() { + Lead l = lead(MOBILE); + EventLead existing = new EventLead(); + existing.setLeadUuid(l.getUuid()); + when(leads.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(l)); + when(eventLeads.findByEventUuidAndLeadUuid(EVENT, l.getUuid())).thenReturn(Optional.of(existing)); + + registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "A", MOBILE, null, null, null, + null, null, null)); + + verify(notifier).leadChanged(COMPANY, MOBILE, l.getUuid()); + } + + @Test + void qrRegistrationOfAnAlreadyOwnedCaptureDoesNotNotify() { + Lead l = lead(MOBILE); + EventLead existing = new EventLead(); + existing.setSalespersonUserId(5L); + when(leads.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(l)); + when(eventLeads.findByEventUuidAndLeadUuid(EVENT, l.getUuid())).thenReturn(Optional.of(existing)); + + registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "A", MOBILE, null, null, null, + null, null, null)); + + verify(notifier, never()).leadChanged(anyLong(), any(), anyLong()); + } + + private EventLeadUpdateRequest update(Long salesperson) { + return new EventLeadUpdateRequest(COMPANY, 555L, salesperson, null, null, null, null, null, "bo"); + } + + private EventLead stubUpdate(Long currentSalesperson) { + Lead l = lead(MOBILE); + EventLead e = new EventLead(); + e.setCompanyId(COMPANY); + e.setLeadUuid(l.getUuid()); + e.setId(1L); + e.setSalespersonUserId(currentSalesperson); + when(eventLeads.findByUuidAndCompanyId(555L, COMPANY)).thenReturn(Optional.of(e)); + when(eventLeads.saveAndFlush(any(EventLead.class))).then(returnsFirstArg()); + when(leads.findByUuidAndCompanyId(l.getUuid(), COMPANY)).thenReturn(Optional.of(l)); + return e; + } + + @Test + void salespersonChangeNotifies() { + stubUpdate(5L); + + service.update(update(7L)); + + verify(notifier).leadChanged(eq(COMPANY), eq(MOBILE), anyLong()); + } + + @Test + void updateKeepingTheSameSalespersonDoesNotNotify() { + stubUpdate(5L); + + service.update(update(5L)); + + verify(notifier, never()).leadChanged(anyLong(), any(), anyLong()); + } +} -- 2.54.1 From 73d06795aa12957ef424d4ad0d8b9e0357bcdf09 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 01:49:23 +0800 Subject: [PATCH 07/23] docs: tick WhatsApp wave 2 tasks Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-whatsapp-inbox/tasks.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openspec/changes/add-whatsapp-inbox/tasks.md b/openspec/changes/add-whatsapp-inbox/tasks.md index b7cb72c..5c203c7 100644 --- a/openspec/changes/add-whatsapp-inbox/tasks.md +++ b/openspec/changes/add-whatsapp-inbox/tasks.md @@ -23,7 +23,7 @@ Verify commands: ## Wave 2 (parallel: 2.1 and 2.2) -- [ ] 2.1 Service ingest: +- [x] 2.1 Service ingest: - number-to-company routing restricted to the matched companies; - conversation upsert and the message insert, idempotent on `wamid`; - the status ranking; @@ -31,7 +31,7 @@ Verify commands: - Depends on: 1.3 - Scope: `solvway-services-whatsapp/src/main/java/**` except `meta/**` and `dto/**`, `solvway-services-whatsapp/src/test/**` - Verify: `mvn -T 0.5C -q -pl solvway-services-whatsapp verify` -- [ ] 2.2 Counter lead lookup: `GET /counter/lead/whatsappContact` (newest lead by mobile, its latest salesperson), and the best-effort `leadChanged` notify on the event lead save paths (capture, salesperson change). +- [x] 2.2 Counter lead lookup: `GET /counter/lead/whatsappContact` (newest lead by mobile, its latest salesperson), and the best-effort `leadChanged` notify on the event lead save paths (capture, salesperson change). - Depends on: 1.3 - Scope: `solvway-services-counter/**` - Verify: `mvn -T 0.5C -q -pl solvway-services-counter verify` -- 2.54.1 From 846c22697ee666776c77db74c75365c86429a507 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 02:05:21 +0800 Subject: [PATCH 08/23] feat: WhatsApp chat ownership, manual assignment and nightly repair Conversations follow the lead's latest salesperson who is active with BO_WHATSAPP, keep the current owner otherwise, and go unassigned when nobody qualifies. Automatic writes are compare-and-set so they never overwrite a WhatsApp Admin's manual assignment. leadChanged, userChanged and assign endpoints, a 03:00 nightly job, and a system-service read of the users of a company holding a module. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../system/controller/UserController.java | 8 + .../services/system/service/UserService.java | 22 ++ .../UserControllerActiveWithModuleTest.java | 35 ++ .../UserServiceActiveWithModuleTest.java | 122 ++++++ .../SolvwayServicesWhatsappApplication.java | 2 + .../services/whatsapp/job/OwnershipJob.java | 72 ++++ .../ownership/OwnershipController.java | 40 ++ .../whatsapp/ownership/OwnershipService.java | 179 +++++++++ .../repository/WaConversationRepository.java | 26 ++ .../service/WebhookIngestService.java | 14 +- .../whatsapp/job/OwnershipJobTest.java | 122 ++++++ .../whatsapp/ownership/OwnershipTest.java | 369 ++++++++++++++++++ .../service/WebhookIngestServiceTest.java | 23 +- 13 files changed, 1031 insertions(+), 3 deletions(-) create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerActiveWithModuleTest.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/service/UserServiceActiveWithModuleTest.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/job/OwnershipJob.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipController.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipService.java create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/job/OwnershipJobTest.java create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/ownership/OwnershipTest.java diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java b/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java index b7febbb..6184445 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java @@ -51,6 +51,7 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.lang.reflect.Type; @@ -233,6 +234,13 @@ public class UserController { .isPresent(); } + /** Ids of the company's enabled admins whose roles grant the module (used by the WhatsApp service for chat ownership). */ + @GetMapping("/activeWithModule") + public List activeWithModule(@RequestParam("companyId") Long companyId, + @RequestParam("module") String module) { + return userService.findActiveAdminIdsWithModule(companyId, module); + } + @RequestMapping("/findByEmail/{email}") public User findByEmail(@PathVariable("email") String email) { User user = userService.findByEmail(email); diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/service/UserService.java b/solvway-services-system/src/main/java/com/solvway/services/system/service/UserService.java index 56166f2..35e2551 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/service/UserService.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/service/UserService.java @@ -2,9 +2,12 @@ package com.solvway.services.system.service; import com.solvway.core.enums.GeneralEnum.FlagYesNo; import com.solvway.core.enums.UserEnum.UserType; +import com.solvway.services.system.constant.SystemConstants.Area; import com.solvway.services.system.constant.SystemConstants.LoginStatus; import com.solvway.services.system.model.User; import com.solvway.services.system.model.User.UserStatus; +import com.solvway.services.system.model.Role; +import com.solvway.services.system.repo.ModuleRepository; import com.solvway.services.system.repo.UserRepository; import com.solvway.services.system.util.paging.PageableRest; import org.springframework.beans.factory.annotation.Autowired; @@ -20,12 +23,18 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; @Service public class UserService { @Autowired private UserRepository userRepository; + + @Autowired + private ModuleRepository moduleRepository; + public List findAll() { return userRepository.findAll(); } @@ -165,4 +174,17 @@ public class UserService { public List findUserByRoleName(String roleName){ return userRepository.findUserByRoleName(roleName); } + + /** Ids of the company's enabled admins whose roles grant the module; no company (super admins) means none. */ + public List findActiveAdminIdsWithModule(Long companyId, String module) { + if (companyId == null) { + return List.of(); + } + // ROLE_ADMIN (id 2) is injected into every admin and grants no modules; only back office modules count + Set roleIds = moduleRepository.findByName(module).filter(m -> m.getArea() == Area.BO) + .map(m -> m.getRoles().stream().map(Role::getId).filter(id -> !Long.valueOf(2L).equals(id)).collect(Collectors.toSet())).orElse(Set.of()); + return userRepository.findByCompanyIdAndType(companyId, UserType.A).stream() + .filter(u -> u.isEnabled() && u.getRoles().stream().anyMatch(r -> roleIds.contains(r.getId()))) + .map(User::getId).toList(); + } } diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerActiveWithModuleTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerActiveWithModuleTest.java new file mode 100644 index 0000000..c453355 --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerActiveWithModuleTest.java @@ -0,0 +1,35 @@ +package com.solvway.services.system.controller; + +import com.solvway.services.system.service.UserService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class UserControllerActiveWithModuleTest { + + @Mock private UserService userService; + @InjectMocks private UserController controller; + + @Test + void returnsTheIdsTheServiceFindsForTheCompanyAndModule() { + when(userService.findActiveAdminIdsWithModule(2L, "BO_WHATSAPP")).thenReturn(List.of(10L, 11L)); + + assertThat(controller.activeWithModule(2L, "BO_WHATSAPP")).containsExactly(10L, 11L); + } + + @Test + void noMatchingUsersIsAnEmptyList() { + assertThat(controller.activeWithModule(3L, "BO_WHATSAPP")).isEmpty(); + } +} diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/service/UserServiceActiveWithModuleTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/service/UserServiceActiveWithModuleTest.java new file mode 100644 index 0000000..d4421fd --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/service/UserServiceActiveWithModuleTest.java @@ -0,0 +1,122 @@ +package com.solvway.services.system.service; + +import com.solvway.core.enums.UserEnum.UserType; +import com.solvway.services.system.constant.SystemConstants.Area; +import com.solvway.services.system.model.Module; +import com.solvway.services.system.model.Role; +import com.solvway.services.system.model.User; +import com.solvway.services.system.repo.ModuleRepository; +import com.solvway.services.system.repo.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class UserServiceActiveWithModuleTest { + + @Mock private UserRepository userRepository; + @Mock private ModuleRepository moduleRepository; + @InjectMocks private UserService service; + + private final Role withModule = role(1L); + private final Role withoutModule = role(3L); + private final Role injectedAdmin = role(2L); // ROLE_ADMIN, added to every admin, never a module grant + + @BeforeEach + void setUp() { + Module m = new Module(); + m.setName("BO_WHATSAPP"); + m.setArea(Area.BO); + m.setRoles(List.of(withModule, injectedAdmin)); + when(moduleRepository.findByName("BO_WHATSAPP")).thenReturn(Optional.of(m)); + } + + private static Role role(long id) { + Role r = new Role(); + r.setId(id); + return r; + } + + private static User user(long id, boolean enabled, Role... roles) { + User u = new User(); + u.setId(id); + u.setEnabled(enabled); + u.setRoles(List.of(roles)); + return u; + } + + @Test + void enabledAdminWhoseRoleGrantsTheModuleIsIncluded() { + when(userRepository.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(user(10L, true, withoutModule, withModule))); + + assertThat(service.findActiveAdminIdsWithModule(2L, "BO_WHATSAPP")).containsExactly(10L); + } + + @Test + void disabledAdminIsExcluded() { + when(userRepository.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(user(10L, false, withModule))); + + assertThat(service.findActiveAdminIdsWithModule(2L, "BO_WHATSAPP")).isEmpty(); + } + + @Test + void roleWithoutTheModuleIsExcluded() { + when(userRepository.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(user(10L, true, withoutModule))); + + assertThat(service.findActiveAdminIdsWithModule(2L, "BO_WHATSAPP")).isEmpty(); + } + + @Test + void usersOfAnotherCompanyAreNeverLoaded() { + when(userRepository.findByCompanyIdAndType(3L, UserType.A)).thenReturn(List.of()); + + assertThat(service.findActiveAdminIdsWithModule(3L, "BO_WHATSAPP")).isEmpty(); + verify(userRepository).findByCompanyIdAndType(3L, UserType.A); + } + + @Test + void noCompanyMeansNoUsersNotTheCompanylessSuperAdmins() { + assertThat(service.findActiveAdminIdsWithModule(null, "BO_WHATSAPP")).isEmpty(); + verifyNoInteractions(userRepository); + } + + @Test + void unknownModuleMeansNoUsers() { + when(userRepository.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(user(10L, true, withModule))); + + assertThat(service.findActiveAdminIdsWithModule(2L, "NOPE")).isEmpty(); + } + + @Test + void injectedRoleAdminNeverGrantsTheModule() { + when(userRepository.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(user(10L, true, injectedAdmin))); + + assertThat(service.findActiveAdminIdsWithModule(2L, "BO_WHATSAPP")).isEmpty(); + } + + @Test + void moduleOutsideTheBackOfficeAreaMeansNoUsers() { + Module m = new Module(); + m.setName("MEMBER_WHATSAPP"); + m.setArea(Area.M); + m.setRoles(List.of(withModule)); + when(moduleRepository.findByName("MEMBER_WHATSAPP")).thenReturn(Optional.of(m)); + when(userRepository.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(user(10L, true, withModule))); + + assertThat(service.findActiveAdminIdsWithModule(2L, "MEMBER_WHATSAPP")).isEmpty(); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/SolvwayServicesWhatsappApplication.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/SolvwayServicesWhatsappApplication.java index 54a42f1..424964f 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/SolvwayServicesWhatsappApplication.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/SolvwayServicesWhatsappApplication.java @@ -2,8 +2,10 @@ package com.solvway.services.whatsapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication +@EnableScheduling public class SolvwayServicesWhatsappApplication { public static void main(String[] args) { diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/job/OwnershipJob.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/job/OwnershipJob.java new file mode 100644 index 0000000..b897493 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/job/OwnershipJob.java @@ -0,0 +1,72 @@ +package com.solvway.services.whatsapp.job; + +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.ownership.OwnershipService; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.PageRequest; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Set; + +/** Nightly repair: drops owners who lost access, then recomputes every automatic conversation, company by company. */ +@Component +public class OwnershipJob { + + public record Counts(int scanned, int unassigned, int recomputed, int changed, int failed) {} + + private static final Logger log = LoggerFactory.getLogger(OwnershipJob.class); + private static final int PAGE = 200; + + private final WaConversationRepository conversations; + private final OwnershipService ownership; + + public OwnershipJob(WaConversationRepository conversations, OwnershipService ownership) { + this.conversations = conversations; + this.ownership = ownership; + } + + @Scheduled(cron = "${whatsapp.ownership.cron:0 0 3 * * *}", zone = "Asia/Kuala_Lumpur") + public void nightly() { + run(); + } + + Counts run() { + int scanned = 0, unassigned = 0, recomputed = 0, changed = 0, failed = 0, skipped = 0; + for (Long companyId : conversations.companyIds()) { + Set active = ownership.activeUsers(companyId); + if (active == null) { + skipped++; + continue; + } + long after = 0; + List page; + while (!(page = conversations.findByCompanyIdAndIdGreaterThanOrderByIdAsc(companyId, after, PageRequest.of(0, PAGE))).isEmpty()) { + for (WaConversation c : page) { + scanned++; + after = c.id; + try { + if (ownership.dropIfNoAccess(c, active)) { + unassigned++; + } + if (!c.ownerManual) { + recomputed++; + if (ownership.recompute(c, active)) { + changed++; + } + } + } catch (RuntimeException e) { + failed++; + log.warn("WhatsApp ownership job: conversation {} failed ({})", c.uuid, e.getClass().getSimpleName()); + } + } + } + } + log.info("WhatsApp ownership job: scanned={} unassigned={} recomputed={} changed={} failed={} companiesSkipped={}", + scanned, unassigned, recomputed, changed, failed, skipped); + return new Counts(scanned, unassigned, recomputed, changed, failed); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipController.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipController.java new file mode 100644 index 0000000..d6fe44e --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipController.java @@ -0,0 +1,40 @@ +package com.solvway.services.whatsapp.ownership; + +import com.solvway.services.whatsapp.dto.AssignRequest; +import com.solvway.services.whatsapp.dto.ConversationView; +import com.solvway.services.whatsapp.dto.LeadChangedRequest; +import com.solvway.services.whatsapp.dto.UserChangedRequest; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/whatsapp") +public class OwnershipController { + + private final OwnershipService service; + + public OwnershipController(OwnershipService service) { + this.service = service; + } + + @PostMapping("/ownership/leadChanged") + public void leadChanged(@RequestBody LeadChangedRequest request) { + service.leadChanged(request); + } + + @PostMapping("/ownership/userChanged") + public void userChanged(@RequestBody UserChangedRequest request) { + service.userChanged(request.userId()); + } + + @PostMapping("/conversations/{uuid}/assign") + public ConversationView assign(@PathVariable String uuid, @RequestParam(required = false) Long companyId, + @RequestParam(required = false) Long userId, @RequestParam boolean admin, + @RequestBody AssignRequest request) { + return service.assign(uuid, companyId, admin, request); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipService.java new file mode 100644 index 0000000..8806f66 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipService.java @@ -0,0 +1,179 @@ +package com.solvway.services.whatsapp.ownership; + +import com.solvway.services.whatsapp.constants.CounterApi; +import com.solvway.services.whatsapp.dto.AssignRequest; +import com.solvway.services.whatsapp.dto.ConversationView; +import com.solvway.services.whatsapp.dto.LeadChangedRequest; +import com.solvway.services.whatsapp.dto.WhatsappContact; +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.server.ResponseStatusException; + +import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Decides who owns each chat. Writes only owner_user_id, owner_manual and lead_uuid through a targeted UPDATE, never a + * whole-entity save, because ingest updates the other columns of the same row concurrently. When the counter or system + * service is unreachable the conversation is left unchanged. Logs conversation ids only, never numbers or names, + * and never exception messages (they can carry the request URL). + */ +@Service +public class OwnershipService { + + static final String MODULE = "BO_WHATSAPP"; + private static final Logger log = LoggerFactory.getLogger(OwnershipService.class); + + private final WaConversationRepository conversations; + private final RestTemplate rest; + + @Autowired + public OwnershipService(WaConversationRepository conversations, RestTemplateBuilder builder) { + this(conversations, builder.setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(10)).build()); + } + + OwnershipService(WaConversationRepository conversations, RestTemplate rest) { + this.conversations = conversations; + this.rest = rest; + } + + /** Users of the company who are enabled admins with BO_WHATSAPP; null when the system service is unreachable. */ + public Set activeUsers(Long companyId) { + try { + Long[] ids = rest.getForObject( + URI.create("http://service-system/user/activeWithModule?companyId=" + companyId + "&module=" + MODULE), Long[].class); + return ids == null ? Set.of() : new HashSet<>(Arrays.asList(ids)); + } catch (RuntimeException e) { + log.warn("WhatsApp ownership: active users of company {} unavailable ({})", companyId, e.getClass().getSimpleName()); + return null; + } + } + + /** Automatic owner for one conversation; a manual owner is never touched. */ + public void recompute(WaConversation c) { + if (c.ownerManual) { + return; + } + Set active = activeUsers(c.companyId); + if (active != null) { + recompute(c, active); + } + } + + /** Latest salesperson if they have access, else the current owner if they still do, else nobody. Returns true when it changed. */ + public boolean recompute(WaConversation c, Set active) { + WhatsappContact contact; + try { + contact = lookup(c); + } catch (RuntimeException e) { + log.warn("WhatsApp ownership: counter lookup failed for conversation {} ({})", c.uuid, e.getClass().getSimpleName()); + return false; + } + Long salesperson = contact == null ? null : contact.latestSalespersonUserId(); + Long owner = salesperson != null && active.contains(salesperson) ? salesperson + : c.ownerUserId != null && active.contains(c.ownerUserId) ? c.ownerUserId : null; + return cas(c, owner, contact == null ? null : contact.leadUuid()); + } + + /** The userChanged rule: an owner without access loses the chat and the manual flag. Returns true when it did. */ + public boolean dropIfNoAccess(WaConversation c, Set active) { + return c.ownerUserId != null && !active.contains(c.ownerUserId) && cas(c, null, c.leadUuid); + } + + public void leadChanged(LeadChangedRequest request) { + if (request.companyId() == null || request.mobileE164() == null) { + return; + } + conversations.findByCompanyIdAndContactWaId(request.companyId(), request.mobileE164().replace("+", "")) + .ifPresent(this::recompute); + } + + public void userChanged(Long userId) { + if (userId == null) { + return; + } + conversations.findByOwnerUserId(userId).stream().collect(Collectors.groupingBy(c -> c.companyId)).forEach((companyId, owned) -> { + Set active = activeUsers(companyId); + if (active != null) { + owned.forEach(c -> dropIfNoAccess(c, active)); + } + }); + } + + public ConversationView assign(String uuid, Long companyId, boolean admin, AssignRequest request) { + if (!admin) { + throw notFound(); + } + WaConversation c = conversations.findByUuid(uuid).filter(x -> companyId == null || companyId.equals(x.companyId)) + .orElseThrow(OwnershipService::notFound); + if (request == null || (request.userId() == null && !Boolean.TRUE.equals(request.automatic()))) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); + } + if (Boolean.TRUE.equals(request.automatic())) { + conversations.updateOwnership(c.id, c.ownerUserId, false, c.leadUuid); + c.ownerManual = false; + recompute(c); + } else { + Set active = activeUsers(c.companyId); + if (active == null) { + throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "USERS_UNAVAILABLE"); + } + if (!active.contains(request.userId())) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ASSIGNEE_NOT_ALLOWED"); + } + conversations.updateOwnership(c.id, request.userId(), true, c.leadUuid); + c.ownerUserId = request.userId(); + c.ownerManual = true; + } + // ponytail: minimal view (no leadName, unreadCount 0) until the read task; the mobile-api layer fills ownerName. + return new ConversationView(c.uuid, c.companyId, c.contactWaId, c.contactName, c.leadUuid, null, c.ownerUserId, null, + c.ownerManual, c.lastInboundAt, c.lastMessageAt, c.lastMessagePreview, + c.lastInboundAt != null && c.lastInboundAt.isAfter(LocalDateTime.now().minusHours(24)), 0); + } + + private WhatsappContact lookup(WaConversation c) { + String mobile = URLEncoder.encode("+" + c.contactWaId, StandardCharsets.UTF_8); + try { + return rest.getForObject(URI.create("http://service-counter" + CounterApi.WHATSAPP_CONTACT + + "?companyId=" + c.companyId + "&mobileE164=" + mobile), WhatsappContact.class); + } catch (HttpClientErrorException.NotFound e) { + return null; // no lead for this number + } + } + + /** Automatic write, compare-and-set on what was read; 0 rows means someone changed it meanwhile, so leave it. */ + private boolean cas(WaConversation c, Long owner, Long lead) { + if (Objects.equals(c.ownerUserId, owner) && !c.ownerManual && Objects.equals(c.leadUuid, lead)) { + return false; + } + if (conversations.casOwnership(c.id, owner, lead, c.ownerManual, c.ownerUserId) == 0) { + log.info("WhatsApp ownership: conversation {} changed concurrently, left as is", c.uuid); + return false; + } + c.ownerUserId = owner; + c.ownerManual = false; + c.leadUuid = lead; + return true; + } + + private static ResponseStatusException notFound() { + return new ResponseStatusException(HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND"); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java index 0d4f9f1..c66ac11 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java @@ -1,6 +1,7 @@ package com.solvway.services.whatsapp.repository; import com.solvway.services.whatsapp.model.WaConversation; +import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; @@ -8,6 +9,7 @@ import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; +import java.util.List; import java.util.Optional; public interface WaConversationRepository extends JpaRepository { @@ -27,4 +29,28 @@ public interface WaConversationRepository extends JpaRepository findByUuid(String uuid); + + List findByOwnerUserId(Long ownerUserId); + + /** Keyset paging (stable while rows are updated underneath), used by the nightly job. */ + List findByCompanyIdAndIdGreaterThanOrderByIdAsc(Long companyId, Long afterId, Pageable page); + + @Query("select distinct c.companyId from WaConversation c") + List companyIds(); + + /** Writes only the ownership columns, never the inbound ones that ingest updates concurrently. */ + @Transactional + @Modifying + @Query(value = "UPDATE wa_conversation SET owner_user_id = :owner, owner_manual = :manual, lead_uuid = :lead WHERE id = :id", nativeQuery = true) + int updateOwnership(@Param("id") Long id, @Param("owner") Long owner, @Param("manual") boolean manual, @Param("lead") Long lead); + + /** Compare-and-set for automatic writes: applies only if the row still has the flag and owner that recompute read. */ + @Transactional + @Modifying + @Query(value = "UPDATE wa_conversation SET owner_user_id = :owner, owner_manual = false, lead_uuid = :lead " + + "WHERE id = :id AND owner_manual = :prevManual AND owner_user_id <=> :prevOwner", nativeQuery = true) + int casOwnership(@Param("id") Long id, @Param("owner") Long owner, @Param("lead") Long lead, + @Param("prevManual") boolean prevManual, @Param("prevOwner") Long prevOwner); } diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java index 546c870..0319c3d 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.solvway.services.whatsapp.dto.WebhookIngestRequest; import com.solvway.services.whatsapp.model.WaConversation; import com.solvway.services.whatsapp.model.WaMessage; +import com.solvway.services.whatsapp.ownership.OwnershipService; import com.solvway.services.whatsapp.repository.WaConversationRepository; import com.solvway.services.whatsapp.repository.WaMessageRepository; import org.slf4j.Logger; @@ -43,11 +44,14 @@ public class WebhookIngestService { private final CompanyDirectory companies; private final WaConversationRepository conversations; private final WaMessageRepository messages; + private final OwnershipService ownership; - public WebhookIngestService(CompanyDirectory companies, WaConversationRepository conversations, WaMessageRepository messages) { + public WebhookIngestService(CompanyDirectory companies, WaConversationRepository conversations, WaMessageRepository messages, + OwnershipService ownership) { this.companies = companies; this.conversations = conversations; this.messages = messages; + this.ownership = ownership; } public IngestResult ingest(WebhookIngestRequest request) { @@ -115,7 +119,13 @@ public class WebhookIngestService { conv.phoneNumberId = ""; conv.createdAt = LocalDateTime.now(); try { - return conversations.save(conv); + WaConversation saved = conversations.save(conv); + try { + ownership.recompute(saved); + } catch (RuntimeException e) { // ownership must never fail ingest; the nightly job repairs it + log.warn("WhatsApp ownership: recompute failed for new conversation {} ({})", saved.uuid, e.getClass().getSimpleName()); + } + return saved; } catch (DataIntegrityViolationException e) { // a concurrent first message created it return conversations.findByCompanyIdAndContactWaId(companyId, contactWaId).orElseThrow(() -> e); } diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/job/OwnershipJobTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/job/OwnershipJobTest.java new file mode 100644 index 0000000..f5bc8b7 --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/job/OwnershipJobTest.java @@ -0,0 +1,122 @@ +package com.solvway.services.whatsapp.job; + +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.ownership.OwnershipService; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.data.domain.Pageable; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class OwnershipJobTest { + + private WaConversationRepository repo; + private OwnershipService ownership; + private OwnershipJob job; + + private static WaConversation conv(long id, long company, Long owner, boolean manual) { + WaConversation c = new WaConversation(); + c.id = id; + c.companyId = company; + c.ownerUserId = owner; + c.ownerManual = manual; + return c; + } + + @BeforeEach + void setUp() { + repo = mock(WaConversationRepository.class); + ownership = mock(OwnershipService.class); + job = new OwnershipJob(repo, ownership); + when(repo.companyIds()).thenReturn(List.of(1L, 2L)); + } + + @Test + void walksEveryCompanyInPagesOf200AndRecomputesNonManualOnes() { + List first = new ArrayList<>(); + for (long i = 1; i <= 200; i++) { + first.add(conv(i, 1, null, false)); + } + List second = List.of(conv(201, 1, null, false), conv(202, 1, 55L, true)); + when(ownership.activeUsers(1L)).thenReturn(Set.of(10L)); + when(ownership.activeUsers(2L)).thenReturn(Set.of()); + when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(0L), any(Pageable.class))).thenReturn(first); + when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(200L), any(Pageable.class))).thenReturn(second); + when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(202L), any(Pageable.class))).thenReturn(List.of()); + when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(2L), anyLong(), any(Pageable.class))).thenReturn(List.of()); + when(ownership.dropIfNoAccess(any(), any())).thenReturn(false); + when(ownership.recompute(any(), any())).thenReturn(true); + + OwnershipJob.Counts counts = job.run(); + + assertThat(counts.scanned()).isEqualTo(202); + assertThat(counts.recomputed()).isEqualTo(201); // the manual one is not recomputed + verify(ownership, times(201)).recompute(any(), eq(Set.of(10L))); + verify(repo).findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(0L), eq(org.springframework.data.domain.PageRequest.of(0, 200))); + } + + @Test + void ownerWhoLostAccessIsUnassignedThenRecomputedWhenAutomatic() { + WaConversation lostManual = conv(1, 1, 55L, true); + WaConversation lostAuto = conv(2, 1, 56L, false); + when(ownership.activeUsers(1L)).thenReturn(Set.of(10L)); + when(ownership.activeUsers(2L)).thenReturn(Set.of()); + when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(0L), any(Pageable.class))).thenReturn(List.of(lostManual, lostAuto)); + when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(2L), any(Pageable.class))).thenReturn(List.of()); + when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(2L), anyLong(), any(Pageable.class))).thenReturn(List.of()); + when(ownership.dropIfNoAccess(any(), any())).thenAnswer(i -> { + WaConversation c = i.getArgument(0); + c.ownerUserId = null; + c.ownerManual = false; + return true; + }); + + OwnershipJob.Counts counts = job.run(); + + assertThat(counts.unassigned()).isEqualTo(2); + verify(ownership, times(2)).recompute(any(), any()); // both were reset to automatic by the drop + } + + @Test + void companyWhoseUserListIsUnavailableIsSkipped() { + when(ownership.activeUsers(1L)).thenReturn(null); + when(ownership.activeUsers(2L)).thenReturn(Set.of()); + when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(2L), anyLong(), any(Pageable.class))).thenReturn(List.of()); + + job.run(); + + verify(repo, never()).findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), anyLong(), any(Pageable.class)); + } + + @Test + void oneFailingConversationDoesNotAbortTheRun() { + WaConversation bad = conv(1, 1, null, false); + WaConversation good = conv(2, 1, null, false); + when(ownership.activeUsers(1L)).thenReturn(Set.of(10L)); + when(ownership.activeUsers(2L)).thenReturn(Set.of()); + when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(0L), any(Pageable.class))).thenReturn(List.of(bad, good)); + when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(2L), any(Pageable.class))).thenReturn(List.of()); + when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(2L), anyLong(), any(Pageable.class))).thenReturn(List.of()); + when(ownership.recompute(eq(bad), any())).thenThrow(new IllegalStateException("boom")); + when(ownership.recompute(eq(good), any())).thenReturn(true); + + OwnershipJob.Counts counts = job.run(); + + assertThat(counts.scanned()).isEqualTo(2); + assertThat(counts.failed()).isEqualTo(1); + assertThat(counts.changed()).isEqualTo(1); + } +} diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/ownership/OwnershipTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/ownership/OwnershipTest.java new file mode 100644 index 0000000..745e0b3 --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/ownership/OwnershipTest.java @@ -0,0 +1,369 @@ +package com.solvway.services.whatsapp.ownership; + +import com.solvway.services.whatsapp.dto.WhatsappContact; +import com.solvway.services.whatsapp.controller.ErrorHandler; +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; + +import java.net.URI; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class OwnershipTest { + + private WaConversationRepository repo; + private RestTemplate rest; + private OwnershipService service; + private MockMvc mvc; + private WhatsappContact contact; // null = counter answers 404 + private boolean counterDown; + private Set active = Set.of(10L, 11L); // users of company 1 with BO_WHATSAPP + private boolean systemDown; + + @BeforeEach + void setUp() { + repo = mock(WaConversationRepository.class); + rest = mock(RestTemplate.class); + when(rest.getForObject(any(URI.class), eq(WhatsappContact.class))).thenAnswer(i -> { + if (counterDown) { + throw new ResourceAccessException("down"); + } + if (contact == null) { + throw HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null); + } + return contact; + }); + when(rest.getForObject(any(URI.class), eq(Long[].class))).thenAnswer(i -> { + if (systemDown) { + throw new ResourceAccessException("down"); + } + return active.toArray(new Long[0]); + }); + when(repo.casOwnership(anyLong(), any(), any(), anyBoolean(), any())).thenReturn(1); + service = new OwnershipService(repo, rest); + mvc = MockMvcBuilders.standaloneSetup(new OwnershipController(service)).setControllerAdvice(new ErrorHandler()).build(); + } + + private static WaConversation conv(Long owner, boolean manual) { + WaConversation c = new WaConversation(); + c.id = 5L; + c.uuid = "u-1"; + c.companyId = 1L; + c.contactWaId = "60111222333"; + c.ownerUserId = owner; + c.ownerManual = manual; + c.lastInboundAt = LocalDateTime.now().minusHours(1); + return c; + } + + // ---- automatic ownership + + @Test + void newConversationGoesToTheLatestSalespersonAndLinksTheLead() { + contact = new WhatsappContact(77L, "Aisyah", 10L); + WaConversation c = conv(null, false); + + service.recompute(c); + + assertThat(c.ownerUserId).isEqualTo(10L); + assertThat(c.leadUuid).isEqualTo(77L); + assertThat(c.ownerManual).isFalse(); + verify(repo).casOwnership(5L, 10L, 77L, false, null); + verify(repo, never()).save(any()); + } + + @Test + void salespersonWithoutAccessLeavesItUnassignedButLinked() { + contact = new WhatsappContact(77L, "Aisyah", 99L); + WaConversation c = conv(null, false); + + service.recompute(c); + + assertThat(c.ownerUserId).isNull(); + assertThat(c.leadUuid).isEqualTo(77L); + } + + @Test + void salespersonWithoutAccessKeepsACurrentOwnerWhoStillHasAccess() { + contact = new WhatsappContact(77L, "Aisyah", 99L); + WaConversation c = conv(11L, false); + + service.recompute(c); + + assertThat(c.ownerUserId).isEqualTo(11L); + } + + @Test + void ownerWhoLostAccessIsDroppedWhenNoSalespersonCanTakeOver() { + contact = new WhatsappContact(77L, "Aisyah", null); + WaConversation c = conv(55L, false); + + service.recompute(c); + + assertThat(c.ownerUserId).isNull(); + } + + @Test + void manualOwnerIsLeftAloneWithoutAnyLookup() { + WaConversation c = conv(55L, true); + + service.recompute(c); + + assertThat(c.ownerUserId).isEqualTo(55L); + verify(rest, never()).getForObject(any(URI.class), eq(WhatsappContact.class)); + verify(repo, never()).casOwnership(anyLong(), any(), any(), anyBoolean(), any()); + } + + @Test + void unknownSenderStaysUnassignedAndUnlinked() { + contact = null; + WaConversation c = conv(null, false); + + service.recompute(c); + + assertThat(c.ownerUserId).isNull(); + assertThat(c.leadUuid).isNull(); + } + + @Test + void counterDownLeavesTheConversationUnchanged() { + counterDown = true; + WaConversation c = conv(10L, false); + + service.recompute(c); + + assertThat(c.ownerUserId).isEqualTo(10L); + verify(repo, never()).casOwnership(anyLong(), any(), any(), anyBoolean(), any()); + } + + @Test + void systemDownLeavesTheConversationUnchanged() { + systemDown = true; + contact = new WhatsappContact(77L, "Aisyah", 10L); + WaConversation c = conv(null, false); + + service.recompute(c); + + assertThat(c.ownerUserId).isNull(); + verify(repo, never()).casOwnership(anyLong(), any(), any(), anyBoolean(), any()); + } + + @Test + void counterLookupAddsAndEncodesThePlus() { + contact = null; + service.recompute(conv(null, false)); + + ArgumentCaptor uri = ArgumentCaptor.forClass(URI.class); + verify(rest).getForObject(uri.capture(), eq(WhatsappContact.class)); + assertThat(uri.getValue().toString()) + .isEqualTo("http://service-counter/counter/lead/whatsappContact?companyId=1&mobileE164=%2B60111222333"); + } + + @Test + void systemLookupAsksForTheCompanyAndModule() { + contact = null; + service.recompute(conv(null, false)); + + ArgumentCaptor uri = ArgumentCaptor.forClass(URI.class); + verify(rest).getForObject(uri.capture(), eq(Long[].class)); + assertThat(uri.getValue().toString()) + .isEqualTo("http://service-system/user/activeWithModule?companyId=1&module=BO_WHATSAPP"); + } + + // ---- leadChanged + + @Test + void leadChangedRecomputesTheContactsConversation() throws Exception { + contact = new WhatsappContact(77L, "Aisyah", 11L); + WaConversation c = conv(null, false); + when(repo.findByCompanyIdAndContactWaId(1L, "60111222333")).thenReturn(Optional.of(c)); + + mvc.perform(post("/whatsapp/ownership/leadChanged").contentType(MediaType.APPLICATION_JSON) + .content("{\"companyId\":1,\"mobileE164\":\"+60111222333\"}")).andExpect(status().isOk()); + + assertThat(c.ownerUserId).isEqualTo(11L); + } + + @Test + void leadChangedLeavesAManualOwner() throws Exception { + WaConversation c = conv(55L, true); + when(repo.findByCompanyIdAndContactWaId(1L, "60111222333")).thenReturn(Optional.of(c)); + + mvc.perform(post("/whatsapp/ownership/leadChanged").contentType(MediaType.APPLICATION_JSON) + .content("{\"companyId\":1,\"mobileE164\":\"+60111222333\"}")).andExpect(status().isOk()); + + assertThat(c.ownerUserId).isEqualTo(55L); + } + + @Test + void leadChangedForAnUnknownContactIsStill200() throws Exception { + when(repo.findByCompanyIdAndContactWaId(any(), any())).thenReturn(Optional.empty()); + + mvc.perform(post("/whatsapp/ownership/leadChanged").contentType(MediaType.APPLICATION_JSON) + .content("{\"companyId\":1,\"mobileE164\":\"+60999\"}")).andExpect(status().isOk()); + } + + // ---- userChanged + + @Test + void userChangedUnassignsConversationsOfAUserWhoLostAccessAndClearsManual() throws Exception { + WaConversation lost = conv(55L, true); + WaConversation kept = conv(10L, true); + kept.id = 6L; + when(repo.findByOwnerUserId(55L)).thenReturn(List.of(lost)); + when(repo.findByOwnerUserId(10L)).thenReturn(List.of(kept)); + + mvc.perform(post("/whatsapp/ownership/userChanged").contentType(MediaType.APPLICATION_JSON) + .content("{\"userId\":55}")).andExpect(status().isOk()); + mvc.perform(post("/whatsapp/ownership/userChanged").contentType(MediaType.APPLICATION_JSON) + .content("{\"userId\":10}")).andExpect(status().isOk()); + + assertThat(lost.ownerUserId).isNull(); + assertThat(lost.ownerManual).isFalse(); + verify(repo).casOwnership(5L, null, null, true, 55L); + assertThat(kept.ownerUserId).isEqualTo(10L); + assertThat(kept.ownerManual).isTrue(); + } + + @Test + void latestEventWithoutSalespersonKeepsTheCurrentOwner() { + contact = new WhatsappContact(77L, "Aisyah", null); + WaConversation c = conv(11L, false); + + service.recompute(c); + + assertThat(c.ownerUserId).isEqualTo(11L); + assertThat(c.leadUuid).isEqualTo(77L); + } + + @Test + void recomputeWhoseCompareAndSetLosesIsNotRetriedNorOverwritten() { + contact = new WhatsappContact(77L, "Aisyah", 10L); + when(repo.casOwnership(anyLong(), any(), any(), anyBoolean(), any())).thenReturn(0); + WaConversation c = conv(null, false); + + assertThat(service.recompute(c, active)).isFalse(); + + verify(repo, times(1)).casOwnership(5L, 10L, 77L, false, null); + verify(repo, never()).updateOwnership(anyLong(), any(), anyBoolean(), any()); + assertThat(c.ownerUserId).isNull(); + } + + @Test + void dropWhoseCompareAndSetLosesLeavesTheConversationAlone() { + when(repo.casOwnership(anyLong(), any(), any(), anyBoolean(), any())).thenReturn(0); + WaConversation c = conv(55L, false); + + assertThat(service.dropIfNoAccess(c, active)).isFalse(); + + assertThat(c.ownerUserId).isEqualTo(55L); + } + + // ---- assign + + private org.springframework.test.web.servlet.ResultActions assign(String query, String body) throws Exception { + return mvc.perform(post("/whatsapp/conversations/u-1/assign?" + query).contentType(MediaType.APPLICATION_JSON).content(body)); + } + + @Test + void adminAssignsManuallyAndGetsTheView() throws Exception { + WaConversation c = conv(null, false); + when(repo.findByUuid("u-1")).thenReturn(Optional.of(c)); + + assign("companyId=1&userId=9&admin=true", "{\"userId\":11}") + .andExpect(status().isOk()) + .andExpect(jsonPath("$.ownerUserId").value(11)) + .andExpect(jsonPath("$.ownerManual").value(true)) + .andExpect(jsonPath("$.windowOpen").value(true)); + + verify(repo).updateOwnership(5L, 11L, true, null); + } + + @Test + void superAdminWithNoCompanyScopeMayAssign() throws Exception { + when(repo.findByUuid("u-1")).thenReturn(Optional.of(conv(null, false))); + + assign("userId=9&admin=true", "{\"userId\":11}").andExpect(status().isOk()); + } + + @Test + void staffCannotAssign() throws Exception { + when(repo.findByUuid("u-1")).thenReturn(Optional.of(conv(9L, false))); + + assign("companyId=1&userId=9&admin=false", "{\"userId\":11}").andExpect(status().isNotFound()); + verify(repo, never()).updateOwnership(anyLong(), any(), anyBoolean(), any()); + } + + @Test + void conversationOfAnotherCompanyIs404() throws Exception { + when(repo.findByUuid("u-1")).thenReturn(Optional.of(conv(null, false))); + + assign("companyId=2&userId=9&admin=true", "{\"userId\":11}").andExpect(status().isNotFound()); + } + + @Test + void unknownConversationIs404() throws Exception { + when(repo.findByUuid("u-1")).thenReturn(Optional.empty()); + + assign("companyId=1&userId=9&admin=true", "{\"userId\":11}").andExpect(status().isNotFound()); + } + + @Test + void assigneeWithoutAccessIs400() throws Exception { + when(repo.findByUuid("u-1")).thenReturn(Optional.of(conv(null, false))); + + assign("companyId=1&userId=9&admin=true", "{\"userId\":99}") + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.detail").value("ASSIGNEE_NOT_ALLOWED")); + verify(repo, never()).updateOwnership(anyLong(), any(), anyBoolean(), any()); + } + + @Test + void automaticClearsManualAndRecomputes() throws Exception { + contact = new WhatsappContact(77L, "Aisyah", 10L); + WaConversation c = conv(11L, true); + when(repo.findByUuid("u-1")).thenReturn(Optional.of(c)); + + assign("companyId=1&userId=9&admin=true", "{\"automatic\":true}") + .andExpect(status().isOk()) + .andExpect(jsonPath("$.ownerUserId").value(10)) + .andExpect(jsonPath("$.ownerManual").value(false)) + .andExpect(jsonPath("$.leadUuid").value(77)); + } + + @Test + void assignWithNeitherFieldIs400() throws Exception { + when(repo.findByUuid("u-1")).thenReturn(Optional.of(conv(null, false))); + + assign("companyId=1&userId=9&admin=true", "{}") + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.detail").value("INVALID_PAYLOAD")); + } +} diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java index f83b66f..037ecf5 100644 --- a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java @@ -6,6 +6,7 @@ import com.solvway.services.whatsapp.dto.WebhookIngestRequest; import com.solvway.services.whatsapp.model.WaConversation; import com.solvway.services.whatsapp.model.WaMessage; import com.solvway.services.whatsapp.repository.WaConversationRepository; +import com.solvway.services.whatsapp.ownership.OwnershipService; import com.solvway.services.whatsapp.repository.WaMessageRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -24,6 +25,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -39,6 +41,7 @@ class WebhookIngestServiceTest { private boolean existsAlwaysFalse; private long seq; private WaConversationRepository convRepo; + private OwnershipService ownership; private WebhookIngestService service; @BeforeEach @@ -91,7 +94,8 @@ class WebhookIngestServiceTest { } return m; }); - service = new WebhookIngestService(companies, convRepo, msgRepo); + ownership = mock(OwnershipService.class); + service = new WebhookIngestService(companies, convRepo, msgRepo, ownership); } private Optional byWamid(String wamid) { @@ -127,6 +131,23 @@ class WebhookIngestServiceTest { return m; } + @Test + void recomputesOwnershipOnlyWhenTheConversationIsFirstCreated() throws Exception { + ingest(payload("text.json", "WAMID", "wamid.a"), "INS"); + ingest(payload("text.json", "WAMID", "wamid.b"), "INS"); + + verify(ownership, times(1)).recompute(any(WaConversation.class)); + } + + @Test + void ownershipFailureNeverFailsIngest() throws Exception { + doThrow(new IllegalStateException("boom")).when(ownership).recompute(any(WaConversation.class)); + + ingest(payload("text.json"), "INS"); + + assertThat(conversations).containsKey("1/60111222333"); + } + @Test void truncatesAContactNameTo255() throws Exception { ingest(payload("text.json", "NAME", "N".repeat(300)), "INS"); -- 2.54.1 From a397de8c30803303c47c85d7fa5f4ef6d50fd199 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 02:26:55 +0800 Subject: [PATCH 09/23] feat: public WhatsApp webhook with signature checks on both sides mobile-api answers Meta's handshake only for the right verify token and accepts events only with a valid X-Hub-Signature-256 under a company's app secret, capped at 1 MB and rate limited per IP, on an exact exemption. It forwards the exact bytes and signature; the WhatsApp service re-verifies them itself, so the ingest trusts no caller. The gateway exempts exactly POST /whatsapp/webhook/ingest from the user JWT, and the log redactor masks the handshake's token and challenge. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../solvway/gateway/filter/JWTAuthFilter.java | 4 +- .../solvway/gateway/filter/LogRedactor.java | 24 ++ ...TAuthFilterPublicRegistrationPathTest.java | 15 + .../gateway/filter/LogRedactorTest.java | 11 + .../api/RestApiWhatsappServiceConstants.java | 4 + .../PublicWhatsAppWebhookController.java | 41 +++ .../dto/whatsapp/WebhookIngestRequest.java | 10 +- .../service/PublicRegistrationService.java | 2 +- .../api/useraccess/AppAccessAspect.java | 31 +- .../api/whatsapp/WhatsAppWebhookService.java | 171 ++++++++++ .../mobile/api/dto/whatsapp/DtoJsonTest.java | 4 +- .../api/whatsapp/WhatsAppWebhookTest.java | 314 ++++++++++++++++++ .../whatsapp/dto/WebhookIngestRequest.java | 10 +- .../services/whatsapp/dto/package-info.java | 4 + .../service/WebhookIngestService.java | 64 +++- .../controller/WebhookControllerTest.java | 15 +- .../services/whatsapp/dto/DtoJsonTest.java | 4 +- .../service/WebhookIngestServiceTest.java | 71 +++- 18 files changed, 759 insertions(+), 40 deletions(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PublicWhatsAppWebhookController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookService.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookTest.java diff --git a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java index 95946f1..24d8f9c 100644 --- a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java +++ b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java @@ -57,7 +57,9 @@ public class JWTAuthFilter implements GlobalFilter, Ordered { publicPath(HttpMethod.POST, "/counter/checkin/lookup"), publicPath(HttpMethod.POST, "/counter/checkin/byGuest"), // Password hint on public password screens: switched-on rule names and numbers only, no user data - publicPath(HttpMethod.GET, "/passwordRule/adminActive")); + publicPath(HttpMethod.GET, "/passwordRule/adminActive"), + // WhatsApp webhook forward from mobile-api: no user token; the service re-verifies Meta's signature itself + publicPath(HttpMethod.POST, "/whatsapp/webhook/ingest")); private static Map.Entry publicPath(HttpMethod method, String regex) { return Map.entry(method, Pattern.compile(regex)); diff --git a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/LogRedactor.java b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/LogRedactor.java index 84c21ef..0d01b52 100644 --- a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/LogRedactor.java +++ b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/LogRedactor.java @@ -37,6 +37,30 @@ final class LogRedactor { return sb.toString(); } + /** Query params whose values never reach a log: Meta's webhook handshake sends the verify token and challenge in the URL. */ + private static final List SENSITIVE_PARAMS = List.of("hub.verify_token=", "hub.challenge="); + + /** The raw query string with the values of the sensitive params masked. */ + static String query(String rawQuery) { + if (rawQuery == null || rawQuery.isEmpty()) { + return rawQuery; + } + StringBuilder sb = new StringBuilder(rawQuery.length()); + int start = 0; + while (start <= rawQuery.length()) { + int amp = rawQuery.indexOf('&', start); + String pair = rawQuery.substring(start, amp < 0 ? rawQuery.length() : amp); + String name = SENSITIVE_PARAMS.stream().filter(pair::startsWith).findFirst().orElse(null); + sb.append(name == null ? pair : name + MASK); + if (amp < 0) { + break; + } + sb.append('&'); + start = amp + 1; + } + return sb.toString(); + } + /** Path prefixes followed by a bearer-style invite, check-in or registration-link token. */ private static final List TOKEN_PREFIXES = List.of("/counter/eventGuest/findByToken/", "/counter/checkin/findEvent/", "/counter/registrationLink/findByToken/"); diff --git a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java index bea7a77..6524a4a 100644 --- a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java +++ b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java @@ -92,4 +92,19 @@ class JWTAuthFilterPublicRegistrationPathTest { assertThat(ex.getResponse().getStatusCode()).as(c[0] + " " + c[1]).isEqualTo(HttpStatus.UNAUTHORIZED); } } + + @Test + void whatsAppIngestIsPublicButOnlyThatExactPostPath() { + assertThat(passes(call(HttpMethod.POST, "/whatsapp/webhook/ingest"))).isTrue(); + for (String[] c : new String[][] { + {"GET", "/whatsapp/webhook/ingest"}, + {"POST", "/whatsapp/webhook/ingest/x"}, + {"POST", "/x/whatsapp/webhook/ingest"}, + {"POST", "/whatsapp/ownership/userChanged"}, + {"GET", "/whatsapp/conversations"} }) { + MockServerWebExchange ex = call(HttpMethod.valueOf(c[0]), c[1]); + assertThat(passes(ex)).as(c[0] + " " + c[1]).isFalse(); + assertThat(ex.getResponse().getStatusCode()).as(c[0] + " " + c[1]).isEqualTo(HttpStatus.UNAUTHORIZED); + } + } } diff --git a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/LogRedactorTest.java b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/LogRedactorTest.java index 3878211..1743473 100644 --- a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/LogRedactorTest.java +++ b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/LogRedactorTest.java @@ -61,4 +61,15 @@ class LogRedactorTest { .isEqualTo("/locationHierarchy/findParentByIdAndType/28/C"); assertTimeoutPreemptively(Duration.ofSeconds(1), () -> LogRedactor.path("/" + "eyJ.".repeat(20_000))); } + + @Test + @DisplayName("query: WhatsApp webhook verify token and challenge values are masked, other params kept") + void queryWebhookParamsMasked() { + assertThat(LogRedactor.query("hub.mode=subscribe&hub.verify_token=S3cretTok&hub.challenge=998877")) + .isEqualTo("hub.mode=subscribe&hub.verify_token=***&hub.challenge=***"); + assertThat(LogRedactor.query("hub.challenge=1&x=y&hub.verify_token=")).isEqualTo("hub.challenge=***&x=y&hub.verify_token=***"); + assertThat(LogRedactor.query("page=2&size=10")).isEqualTo("page=2&size=10"); + assertThat(LogRedactor.query(null)).isNull(); + assertThat(LogRedactor.query("")).isEmpty(); + } } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiWhatsappServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiWhatsappServiceConstants.java index cb5b54d..0734a80 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiWhatsappServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiWhatsappServiceConstants.java @@ -1,6 +1,10 @@ package com.solvway.mobile.api.constant.api; /** + * Webhook ingest: POST /whatsapp/webhook/ingest carries WebhookIngestRequest {"rawBody": Base64 of the exact bytes Meta + * sent, "signature": the X-Hub-Signature-256 header as received}. The service re-verifies the HMAC under every + * configured company app secret (the companies that verify are the matched ones) and answers 401 ProblemDetail detail + * INVALID_SIGNATURE when none does; it never trusts the caller. * Caller context and access (the SERVICE enforces it; mobile-api only supplies trusted values): * - per-conversation calls (thread, send, read, media, assign, start) and the list carry query params * companyId (null ONLY for a super admin = all companies), userId (the acting staff user) and diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PublicWhatsAppWebhookController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PublicWhatsAppWebhookController.java new file mode 100644 index 0000000..5ed626a --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PublicWhatsAppWebhookController.java @@ -0,0 +1,41 @@ +package com.solvway.mobile.api.controller; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.whatsapp.WhatsAppWebhookService; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import java.io.IOException; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** Meta calls this with no api-key and no sign-in; AppAccessAspect exempts exactly this route (see isWhatsAppWebhook). */ +@RestController +@RequestMapping("/api/public/whatsapp/webhook") +@RequiredArgsConstructor +public class PublicWhatsAppWebhookController { + private final WhatsAppWebhookService webhook; + + @AppAuth(skipValidate = true) + @GetMapping(produces = MediaType.TEXT_PLAIN_VALUE) + public ResponseEntity verify(@RequestParam(name = "hub.mode", required = false) String mode, + @RequestParam(name = "hub.verify_token", required = false) String token, + @RequestParam(name = "hub.challenge", required = false) String challenge) { + String echo = webhook.verify(mode, token, challenge); + return echo == null ? ResponseEntity.status(HttpStatus.FORBIDDEN).build() : ResponseEntity.ok(echo); + } + + @AppAuth(skipValidate = true) + @PostMapping + public ResponseEntity receive(HttpServletRequest request, + @RequestHeader(name = "X-Hub-Signature-256", required = false) String signature) throws IOException { + webhook.receive(request, signature); + return ResponseEntity.ok().build(); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/WebhookIngestRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/WebhookIngestRequest.java index 8f67809..c085513 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/WebhookIngestRequest.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/whatsapp/WebhookIngestRequest.java @@ -1,7 +1,7 @@ package com.solvway.mobile.api.dto.whatsapp; -import com.fasterxml.jackson.databind.JsonNode; -import java.util.List; - -/** mobile-api to service, POST /whatsapp/webhook/ingest: the signature-matched company codes and the raw Meta payload. */ -public record WebhookIngestRequest(List matchedCompanyCodes, JsonNode payload) {} +/** + * mobile-api to service, POST /whatsapp/webhook/ingest. rawBody is the exact request bytes Meta sent, Base64-encoded; + * signature is the X-Hub-Signature-256 header as received. The service re-verifies it and never trusts the caller. + */ +public record WebhookIngestRequest(String rawBody, String signature) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java index 0056058..30c4857 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java @@ -213,7 +213,7 @@ public class PublicRegistrationService { limit(key, max, "Too many registrations from this device. Try again later."); } - void limit(String key, int max, String message) { + public void limit(String key, int max, String message) { Long n = redis.opsForValue().increment(key); if (n != null && n == 1) redis.expire(key, WINDOW_MINUTES, TimeUnit.MINUTES); if (n != null && n > max) throw error(HttpStatus.TOO_MANY_REQUESTS, message, "TOO_MANY", null); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java index 8902947..54bc60a 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java @@ -97,15 +97,18 @@ public class AppAccessAspect { long start = System.currentTimeMillis(); String methodSig = joinPoint.getSignature().toShortString(); String apiKey = HttpReqRespUtils.getHeaderValues("api-key"); - if(!StringUtils.hasLength(apiKey)){ - log.warn("[AppAccessAspect] REJECT: missing 'api-key' header for method={}", methodSig); - throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing header 'api-key'"); - } - if(!authAppKey.contains(apiKey)) { - // Never log the allowed keys, even masked: a short key plus its ":PLATFORM" suffix outlives the mask. - log.warn("[AppAccessAspect] REJECT: api-key not in allowed list. received={} allowedKeyCount={}", - maskKey(apiKey), authAppKey.getList().size()); - throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid header 'api-key'"); + // Meta sends no api-key; the webhook authenticates by body signature instead. + if (!isWhatsAppWebhook()) { + if(!StringUtils.hasLength(apiKey)){ + log.warn("[AppAccessAspect] REJECT: missing 'api-key' header for method={}", methodSig); + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing header 'api-key'"); + } + if(!authAppKey.contains(apiKey)) { + // Never log the allowed keys, even masked: a short key plus its ":PLATFORM" suffix outlives the mask. + log.warn("[AppAccessAspect] REJECT: api-key not in allowed list. received={} allowedKeyCount={}", + maskKey(apiKey), authAppKey.getList().size()); + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid header 'api-key'"); + } } User[] admin = new User[1]; Object result = null; @@ -409,6 +412,16 @@ public class AppAccessAspect { } } + /** Exact: the handler mapping resolved to the webhook pattern itself, with GET or POST. Anything else (other paths, other methods) still needs the key. */ + private static boolean isWhatsAppWebhook() { + if (!(RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs)) { + return false; + } + HttpServletRequest request = attrs.getRequest(); + return "/api/public/whatsapp/webhook".equals(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)) + && ("GET".equals(request.getMethod()) || "POST".equals(request.getMethod())); + } + private static boolean isAdminPath() { if (!(RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs)) { return false; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookService.java new file mode 100644 index 0000000..54b7a03 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookService.java @@ -0,0 +1,171 @@ +package com.solvway.mobile.api.whatsapp; + +import java.io.IOException; +import com.fasterxml.jackson.databind.JsonNode; +import jakarta.servlet.http.HttpServletRequest; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.constant.api.RestApiWhatsappServiceConstants; +import com.solvway.mobile.api.dto.whatsapp.WebhookIngestRequest; +import com.solvway.mobile.api.service.PublicRegistrationService; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestClientResponseException; +import org.springframework.web.server.ResponseStatusException; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Meta's public webhook: subscription handshake and signed events. Settings come straight from the Environment like + * the WhatsApp service does (WHATSAPP_COMPANIES, WHATSAPP_<CODE>_APP_SECRET, WHATSAPP_VERIFY_TOKEN), read per + * request so a rotated secret needs no restart. Nothing here logs message content, numbers, signatures or secrets. + */ +@Slf4j +@Service +public class WhatsAppWebhookService { + private static final String PREFIX = "sha256="; + private static final ObjectMapper JSON = new ObjectMapper(); + // ponytail: the shared limiter counts per 10-minute window, so this is 600/min on average; a per-minute window needs its own counter + private static final int IP_LIMIT = 6000; + private static final int MAX_BODY = 1024 * 1024; + private final Set warned = ConcurrentHashMap.newKeySet(); + + private final Environment env; + private final RestTemplateCustomUtil rest; + private final PublicRegistrationService limiter; + + public WhatsAppWebhookService(Environment env, RestTemplateCustomUtil rest, PublicRegistrationService limiter) { + this.env = env; + this.rest = rest; + this.limiter = limiter; + } + + /** The challenge to echo, or null when the mode or verify token is wrong. A blank configured token never matches. */ + public String verify(String mode, String token, String challenge) { + limit(); + String configured = env.getProperty("WHATSAPP_VERIFY_TOKEN", ""); + if (!"subscribe".equals(mode) || !StringUtils.hasText(configured) || token == null + || !MessageDigest.isEqual(configured.getBytes(StandardCharsets.UTF_8), token.getBytes(StandardCharsets.UTF_8))) { + return null; + } + return challenge; + } + + /** 401 unless the body is signed by at least one company's app secret; then forwards with every matching code. */ + public void receive(HttpServletRequest request, String signature) throws IOException { + limit(); + byte[] raw = readCapped(request); + List matched = matchedCompanies(raw, signature); + if (matched.isEmpty()) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); + } + JsonNode payload; + try { + payload = JSON.readTree(raw); + } catch (IOException e) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST); + } + if (payload == null || !payload.isObject()) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST); + } + try { + rest.postForEntity(rest.getURLforApiService(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_WEBHOOK_INGEST), + Void.class, new WebhookIngestRequest(Base64.getEncoder().encodeToString(raw), signature)); + } catch (RestClientException e) { + // Still 200: Meta retries on anything else and the service is idempotent. Status code only, never the message. + log.warn("WhatsApp webhook forward failed: {}", e instanceof RestClientResponseException r ? r.getStatusCode().value() : e.getClass().getSimpleName()); + } + log.info("WhatsApp webhook forwarded for {} company(ies)", matched.size()); + } + + /** Never buffers more than MAX_BODY: 413 on a declared length over the cap, or when the stream runs past it. */ + private static byte[] readCapped(HttpServletRequest request) throws IOException { + if (request.getContentLengthLong() > MAX_BODY) { + throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE); + } + byte[] body = request.getInputStream().readNBytes(MAX_BODY + 1); + if (body.length > MAX_BODY) { + throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE); + } + return body; + } + + private List matchedCompanies(byte[] body, String signature) { + List matched = new ArrayList<>(); + byte[] given = decode(signature); + if (given == null) { + return matched; + } + // Every company is checked, with no early exit, so timing does not reveal which one matched. + for (Map.Entry company : secrets().entrySet()) { + if (MessageDigest.isEqual(given, hmac(company.getValue(), body))) { + matched.add(company.getKey()); + } + } + return matched; + } + + /** code -> app secret, in WHATSAPP_COMPANIES order; a company without a secret is skipped with a WARN naming only the code. */ + private Map secrets() { + Map secrets = new LinkedHashMap<>(); + for (String raw : env.getProperty("WHATSAPP_COMPANIES", "").split(",")) { + String code = raw.trim().toUpperCase(); + if (code.isEmpty()) { + continue; + } + String secret = env.getProperty("WHATSAPP_" + code + "_APP_SECRET"); + if (StringUtils.hasText(secret)) { + secrets.put(code, secret); + } else { + if (warned.add(code)) { // settings are read per request; say it once per code + log.warn("WhatsApp company {} skipped: no app secret configured", code); + } + } + } + return secrets; + } + + /** "sha256=" plus 64 hex chars, as bytes; null for a missing or malformed header. */ + private static byte[] decode(String header) { + if (header == null || !header.startsWith(PREFIX) || header.length() != PREFIX.length() + 64) { + return null; + } + try { + return HexFormat.of().parseHex(header.substring(PREFIX.length())); + } catch (IllegalArgumentException e) { + return null; + } + } + + private static byte[] hmac(String secret, byte[] body) { + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + return mac.doFinal(body); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("HmacSHA256 unavailable", e); + } + } + + private void limit() { + limiter.limit("wa:webhook:" + HttpReqRespUtils.getClientIpAddressIfServletRequestExist(), IP_LIMIT, + "Too many requests. Try again later."); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/dto/whatsapp/DtoJsonTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/dto/whatsapp/DtoJsonTest.java index 77b2184..b340d59 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/dto/whatsapp/DtoJsonTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/dto/whatsapp/DtoJsonTest.java @@ -63,8 +63,8 @@ class DtoJsonTest { @Test void webhookIngestRequestKeys() throws Exception { - WebhookIngestRequest r = new WebhookIngestRequest(List.of("INS"), mapper.readTree("{\"entry\":[]}")); - assertEquals(new TreeSet<>(List.of("matchedCompanyCodes", "payload")), keys(r)); + WebhookIngestRequest r = new WebhookIngestRequest("e30=", "sha256=00"); + assertEquals(new TreeSet<>(List.of("rawBody", "signature")), keys(r)); assertEquals(r, mapper.readValue(mapper.writeValueAsString(r), WebhookIngestRequest.class)); } } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookTest.java new file mode 100644 index 0000000..2e62074 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/whatsapp/WhatsAppWebhookTest.java @@ -0,0 +1,314 @@ +package com.solvway.mobile.api.whatsapp; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import com.google.cloud.spring.pubsub.core.PubSubTemplate; +import com.solvway.core.utils.JwtTokenUtil; +import com.solvway.core.utils.PubSubUtil; +import com.solvway.mobile.api.config.AuthAppKeyConfig; +import com.solvway.mobile.api.config.PubSubConfig; +import com.solvway.mobile.api.controller.PublicWhatsAppWebhookController; +import com.solvway.mobile.api.controller.publicapi.PublicRegistrationController; +import com.solvway.mobile.api.dto.whatsapp.WebhookIngestRequest; +import com.solvway.mobile.api.service.AuthenticationService; +import com.solvway.mobile.api.service.MemberService; +import com.solvway.mobile.api.service.PublicRegistrationService; +import com.solvway.mobile.api.service.UserService; +import com.solvway.mobile.api.useraccess.AppAccessAspect; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.slf4j.LoggerFactory; +import org.springframework.aop.aspectj.annotation.AspectJProxyFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestClientException; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class WhatsAppWebhookTest { + + private static final String INGEST = "http://gw/whatsapp/webhook/ingest"; + private static final String BODY = "{\"entry\":[{\"changes\":[{\"value\":{\"messages\":[{\"text\":{\"body\":\"hello secret text\"}}]}}]}]}"; + + private RestTemplateCustomUtil rest; + private PublicRegistrationService limiter; + private MockEnvironment env; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + when(rest.getURLforApiService("/whatsapp/webhook/ingest")).thenReturn(INGEST); + limiter = mock(PublicRegistrationService.class); + env = new MockEnvironment().withProperty("WHATSAPP_COMPANIES", "INS, cv") + .withProperty("WHATSAPP_INS_APP_SECRET", "ins-secret").withProperty("WHATSAPP_CV_APP_SECRET", "cv-secret") + .withProperty("WHATSAPP_VERIFY_TOKEN", "verify-me"); + } + + private MockMvc mvc() { + return MockMvcBuilders.standaloneSetup(new PublicWhatsAppWebhookController(new WhatsAppWebhookService(env, rest, limiter))).build(); + } + + static String sign(String secret, byte[] body) throws Exception { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + return "sha256=" + HexFormat.of().formatHex(mac.doFinal(body)); + } + + /** The service gets the exact bytes (Base64) and Meta's header untouched; it re-verifies, so no codes are sent. */ + private void assertForwarded(byte[] body, String signature) { + ArgumentCaptor sent = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(INGEST), eq(Void.class), sent.capture()); + WebhookIngestRequest req = (WebhookIngestRequest) sent.getValue(); + assertThat(Base64.getDecoder().decode(req.rawBody())).isEqualTo(body); + assertThat(req.signature()).isEqualTo(signature); + } + + private void neverForwarded() { + verify(rest, never()).postForEntity(anyString(), any(Class.class), any()); + } + + // handshake + + @Test + void handshakeRightTokenEchoesChallenge() throws Exception { + mvc().perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.verify_token", "verify-me").param("hub.challenge", "12345")) + .andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN)).andExpect(content().string("12345")); + } + + @Test + void handshakeWrongTokenIs403WithoutChallenge() throws Exception { + mvc().perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.verify_token", "nope").param("hub.challenge", "12345")) + .andExpect(status().isForbidden()).andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("12345")))); + } + + @Test + void handshakeWrongModeIs403() throws Exception { + mvc().perform(get("/api/public/whatsapp/webhook").param("hub.mode", "unsubscribe").param("hub.verify_token", "verify-me").param("hub.challenge", "12345")) + .andExpect(status().isForbidden()); + } + + @Test + void handshakeBlankConfiguredTokenNeverMatches() throws Exception { + env.setProperty("WHATSAPP_VERIFY_TOKEN", " "); + mvc().perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.verify_token", " ").param("hub.challenge", "12345")) + .andExpect(status().isForbidden()); + mvc().perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.challenge", "12345")) + .andExpect(status().isForbidden()); + } + + @Test + void handshakeUnsetTokenNeverMatches() throws Exception { + env.getPropertySources().remove("test"); + MockEnvironment bare = new MockEnvironment(); + MockMvcBuilders.standaloneSetup(new PublicWhatsAppWebhookController(new WhatsAppWebhookService(bare, rest, limiter))).build() + .perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.verify_token", "").param("hub.challenge", "12345")) + .andExpect(status().isForbidden()); + } + + // signature + + @Test + void validInsSignatureForwardsWithInsOnly() throws Exception { + byte[] body = BODY.getBytes(StandardCharsets.UTF_8); + mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body) + .header("X-Hub-Signature-256", sign("ins-secret", body))).andExpect(status().isOk()); + assertForwarded(body, sign("ins-secret", body)); + } + + @Test + void eventSignedWithCvSecretForwardsOnlyCv() throws Exception { + byte[] body = BODY.getBytes(StandardCharsets.UTF_8); + mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body) + .header("X-Hub-Signature-256", sign("cv-secret", body))).andExpect(status().isOk()); + assertForwarded(body, sign("cv-secret", body)); + } + + @Test + void sharedSecretMatchesEveryCompany() throws Exception { + env.setProperty("WHATSAPP_CV_APP_SECRET", "ins-secret"); + byte[] body = BODY.getBytes(StandardCharsets.UTF_8); + mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body) + .header("X-Hub-Signature-256", sign("ins-secret", body))).andExpect(status().isOk()); + assertForwarded(body, sign("ins-secret", body)); + } + + @Test + void missingOrGarbledSignatureIs401AndNothingForwarded() throws Exception { + byte[] body = BODY.getBytes(StandardCharsets.UTF_8); + String good = sign("ins-secret", body); + mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body)).andExpect(status().isUnauthorized()); + for (String bad : List.of("", "sha256=", "sha256=zz", good.substring("sha256=".length()), "sha1=" + good.substring(7), + good + "00", good.substring(0, good.length() - 2), "sha256=" + "0".repeat(64))) { + mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body) + .header("X-Hub-Signature-256", bad)).andExpect(status().isUnauthorized()); + } + neverForwarded(); + } + + @Test + void bodyAlteredAfterSigningIs401() throws Exception { + String sig = sign("ins-secret", BODY.getBytes(StandardCharsets.UTF_8)); + mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON) + .content((BODY + " ").getBytes(StandardCharsets.UTF_8)).header("X-Hub-Signature-256", sig)).andExpect(status().isUnauthorized()); + neverForwarded(); + } + + @Test + void companyWithoutSecretIsSkippedAndNeverMatches() throws Exception { + env.withProperty("WHATSAPP_COMPANIES", "INS,CV,XX"); + byte[] body = BODY.getBytes(StandardCharsets.UTF_8); + mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body) + .header("X-Hub-Signature-256", sign("x", body))).andExpect(status().isUnauthorized()); + neverForwarded(); + } + + @Test + void declaredOversizeBodyIs413BeforeAnyHmac() throws Exception { + byte[] body = new byte[1024 * 1024 + 1]; + mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body) + .header("X-Hub-Signature-256", sign("ins-secret", body))).andExpect(status().isPayloadTooLarge()); + neverForwarded(); + } + + @Test + void streamExceedingTheCapWithoutContentLengthIs413AndReadsNoMoreThanCapPlusOne() throws Exception { + java.util.concurrent.atomic.AtomicLong read = new java.util.concurrent.atomic.AtomicLong(); + jakarta.servlet.http.HttpServletRequest req = mock(jakarta.servlet.http.HttpServletRequest.class); + when(req.getContentLengthLong()).thenReturn(-1L); + when(req.getInputStream()).thenReturn(new jakarta.servlet.ServletInputStream() { + public int read() { read.incrementAndGet(); return 'a'; } + public int read(byte[] b, int off, int len) { read.addAndGet(len); return len; } + public boolean isFinished() { return false; } + public boolean isReady() { return true; } + public void setReadListener(jakarta.servlet.ReadListener l) { } + }); + WhatsAppWebhookService service = new WhatsAppWebhookService(env, rest, limiter); + + assertThat(org.assertj.core.api.Assertions.catchThrowable(() -> service.receive(req, "sha256=" + "0".repeat(64)))) + .isInstanceOfSatisfying(org.springframework.web.server.ResponseStatusException.class, + e -> assertThat(e.getStatusCode().value()).isEqualTo(413)); + assertThat(read.get()).isLessThanOrEqualTo(1024 * 1024 + 1 + 8192); + neverForwarded(); + } + + @Test + void bodyExactlyAtTheCapIsStillRead() throws Exception { + byte[] body = new byte[1024 * 1024]; + mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body) + .header("X-Hub-Signature-256", sign("ins-secret", body))).andExpect(status().isBadRequest()); // signed, not JSON + } + + @Test + void companyWithoutSecretWarnsOnlyOnce() throws Exception { + env.withProperty("WHATSAPP_COMPANIES", "INS,XX"); + ListAppender logs = new ListAppender<>(); + logs.start(); + Logger logger = (Logger) LoggerFactory.getLogger(WhatsAppWebhookService.class); + logger.addAppender(logs); + try { + MockMvc mvc = mvc(); + byte[] body = BODY.getBytes(StandardCharsets.UTF_8); + for (int i = 0; i < 3; i++) { + mvc.perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body) + .header("X-Hub-Signature-256", sign("x", body))); + } + assertThat(logs.list.stream().filter(e -> e.getFormattedMessage().contains("XX skipped"))).hasSize(1); + } finally { + logger.detachAppender(logs); + } + } + + @Test + void signedButMalformedJsonIs400() throws Exception { + byte[] body = "{not json".getBytes(StandardCharsets.UTF_8); + mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body) + .header("X-Hub-Signature-256", sign("ins-secret", body))).andExpect(status().isBadRequest()); + neverForwarded(); + } + + @Test + void forwardFailureStillAnswers200AndLogsNoContent() throws Exception { + ListAppender logs = new ListAppender<>(); + logs.start(); + Logger logger = (Logger) LoggerFactory.getLogger(WhatsAppWebhookService.class); + logger.addAppender(logs); + try { + when(rest.postForEntity(eq(INGEST), eq(Void.class), any())).thenThrow(new RestClientException("boom hello secret text")); + byte[] body = BODY.getBytes(StandardCharsets.UTF_8); + String sig = sign("ins-secret", body); + mvc().perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body) + .header("X-Hub-Signature-256", sig)).andExpect(status().isOk()); + assertThat(logs.list).isNotEmpty(); + for (ILoggingEvent e : logs.list) { + assertThat(e.getFormattedMessage()).doesNotContain("hello").doesNotContain("secret").doesNotContain(sig).doesNotContain("verify-me"); + assertThat(e.getThrowableProxy()).isNull(); + } + } finally { + logger.detachAppender(logs); + } + } + + @Test + void rateLimitedByIp() throws Exception { + mvc().perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.verify_token", "verify-me").param("hub.challenge", "1")) + .andExpect(status().isOk()); + verify(limiter).limit(org.mockito.ArgumentMatchers.startsWith("wa:webhook:"), anyInt(), anyString()); + } + + // public access through the real AppAccessAspect: no api-key, no JWT + + private T guarded(T controller) { + AuthAppKeyConfig keys = new AuthAppKeyConfig(); + keys.setList(List.of("a-key:APP")); + AppAccessAspect aspect = new AppAccessAspect(mock(MemberService.class), mock(UserService.class), mock(PubSubConfig.class), + mock(PubSubTemplate.class), mock(PubSubUtil.class), keys, mock(AuthenticationService.class), mock(JwtTokenUtil.class), null, null); + AspectJProxyFactory factory = new AspectJProxyFactory(controller); + factory.setProxyTargetClass(true); + factory.addAspect(aspect); + return factory.getProxy(); + } + + @Test + void webhookIsReachableWithoutApiKeyOrJwt() throws Exception { + MockMvc guarded = MockMvcBuilders.standaloneSetup(guarded(new PublicWhatsAppWebhookController(new WhatsAppWebhookService(env, rest, limiter)))).build(); + guarded.perform(get("/api/public/whatsapp/webhook").param("hub.mode", "subscribe").param("hub.verify_token", "verify-me").param("hub.challenge", "77")) + .andExpect(status().isOk()).andExpect(content().string("77")); + byte[] body = BODY.getBytes(StandardCharsets.UTF_8); + guarded.perform(post("/api/public/whatsapp/webhook").contentType(MediaType.APPLICATION_JSON).content(body) + .header("X-Hub-Signature-256", sign("ins-secret", body))).andExpect(status().isOk()); + } + + @Test + void neighbouringPublicRouteStillNeedsAnApiKey() throws Exception { + MockMvc guarded = MockMvcBuilders.standaloneSetup(guarded(new PublicRegistrationController(mock(PublicRegistrationService.class)))).build(); + guarded.perform(get("/api/public/registration/abc")).andExpect(status().isUnauthorized()); + } + + private static int anyInt() { + return org.mockito.ArgumentMatchers.anyInt(); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WebhookIngestRequest.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WebhookIngestRequest.java index a3a4dc0..cb50fc6 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WebhookIngestRequest.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/WebhookIngestRequest.java @@ -1,7 +1,7 @@ package com.solvway.services.whatsapp.dto; -import com.fasterxml.jackson.databind.JsonNode; -import java.util.List; - -/** mobile-api to service, POST /whatsapp/webhook/ingest: the signature-matched company codes and the raw Meta payload. */ -public record WebhookIngestRequest(List matchedCompanyCodes, JsonNode payload) {} +/** + * mobile-api to service, POST /whatsapp/webhook/ingest. rawBody is the exact request bytes Meta sent, Base64-encoded; + * signature is the X-Hub-Signature-256 header as received. The service re-verifies it and never trusts the caller. + */ +public record WebhookIngestRequest(String rawBody, String signature) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/package-info.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/package-info.java index f57a028..3e3dbc9 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/package-info.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/dto/package-info.java @@ -1,4 +1,8 @@ /** + * Webhook ingest: POST /whatsapp/webhook/ingest carries WebhookIngestRequest {"rawBody": Base64 of the exact bytes Meta + * sent, "signature": the X-Hub-Signature-256 header as received}. The service re-verifies the HMAC under every + * configured company app secret (the companies that verify are the matched ones) and answers 401 ProblemDetail detail + * INVALID_SIGNATURE when none does; it never trusts the caller. * Caller context and access (the SERVICE enforces it; mobile-api only supplies trusted values): * - per-conversation calls (thread, send, read, media, assign, start) and the list carry query params * companyId (null ONLY for a super admin = all companies), userId (the acting staff user) and diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java index 0319c3d..eb9bae2 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/WebhookIngestService.java @@ -1,6 +1,8 @@ package com.solvway.services.whatsapp.service; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.services.whatsapp.config.WhatsAppSettings; import com.solvway.services.whatsapp.dto.WebhookIngestRequest; import com.solvway.services.whatsapp.model.WaConversation; import com.solvway.services.whatsapp.model.WaMessage; @@ -14,13 +16,20 @@ import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; +import java.util.Base64; +import java.util.HexFormat; import java.util.List; import java.util.Set; import java.util.UUID; -import java.util.stream.Collectors; /** * Stores Meta webhook messages and delivery statuses. Deliberately not transactional: each repository call is its own @@ -36,6 +45,8 @@ public class WebhookIngestService { private static final Set MEDIA = Set.of("image", "document", "audio", "video", "sticker"); private static final List STATUS_RANK = List.of("pending", "sent", "delivered", "read"); private static final int PREVIEW_MAX = 80; + private static final String SIG_PREFIX = "sha256="; + private static final ObjectMapper JSON = new ObjectMapper(); private static final class Counts { int accepted, duplicates, dropped, applied, ignored; @@ -45,22 +56,39 @@ public class WebhookIngestService { private final WaConversationRepository conversations; private final WaMessageRepository messages; private final OwnershipService ownership; + private final WhatsAppSettings settings; public WebhookIngestService(CompanyDirectory companies, WaConversationRepository conversations, WaMessageRepository messages, - OwnershipService ownership) { + OwnershipService ownership, WhatsAppSettings settings) { + this.settings = settings; this.companies = companies; this.conversations = conversations; this.messages = messages; this.ownership = ownership; } + /** Re-verifies Meta's signature itself (the caller is not trusted); the companies that verify are the matched ones. */ public IngestResult ingest(WebhookIngestRequest request) { - JsonNode entries = request.payload() == null ? null : request.payload().get("entry"); + byte[] raw; + try { + raw = request.rawBody() == null ? null : Base64.getDecoder().decode(request.rawBody()); + } catch (IllegalArgumentException e) { + raw = null; + } + Set matched = raw == null ? Set.of() : matchedCompanies(raw, request.signature()); + if (matched.isEmpty()) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "INVALID_SIGNATURE"); + } + JsonNode payload; + try { + payload = JSON.readTree(raw); + } catch (IOException e) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); + } + JsonNode entries = payload == null ? null : payload.get("entry"); if (entries == null || !entries.isArray()) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); } - Set matched = request.matchedCompanyCodes() == null ? Set.of() - : request.matchedCompanyCodes().stream().map(String::toUpperCase).collect(Collectors.toSet()); Counts c = new Counts(); for (JsonNode entry : entries) { for (JsonNode change : entry.path("changes")) { @@ -84,6 +112,32 @@ public class WebhookIngestService { return new IngestResult(c.accepted, c.duplicates, c.dropped, c.applied, c.ignored); } + /** Every company is checked, no early exit, constant-time compare. */ + private Set matchedCompanies(byte[] raw, String signature) { + if (signature == null || !signature.startsWith(SIG_PREFIX) || signature.length() != SIG_PREFIX.length() + 64) { + return Set.of(); + } + byte[] given; + try { + given = HexFormat.of().parseHex(signature.substring(SIG_PREFIX.length())); + } catch (IllegalArgumentException e) { + return Set.of(); + } + Set matched = new java.util.HashSet<>(); + for (WhatsAppSettings.CompanyConfig company : settings.companies()) { + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(company.appSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + if (MessageDigest.isEqual(given, mac.doFinal(raw))) { + matched.add(company.code().toUpperCase()); + } + } catch (GeneralSecurityException e) { + throw new IllegalStateException("HmacSHA256 unavailable", e); + } + } + return matched; + } + private void message(CompanyDirectory.Company company, String phoneNumberId, JsonNode value, JsonNode m, Counts c) { String wamid = text(m, "id"); String from = text(m, "from"); diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/controller/WebhookControllerTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/controller/WebhookControllerTest.java index 2f3f997..6bbdb84 100644 --- a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/controller/WebhookControllerTest.java +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/controller/WebhookControllerTest.java @@ -34,7 +34,7 @@ class WebhookControllerTest { when(service.ingest(any(WebhookIngestRequest.class))).thenReturn(new IngestResult(2, 1, 3, 0, 0)); mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON) - .content("{\"matchedCompanyCodes\":[\"INS\"],\"payload\":{\"entry\":[]}}")) + .content("{\"rawBody\":\"e30=\",\"signature\":\"sha256=00\"}")) .andExpect(status().isOk()) .andExpect(jsonPath("$.accepted").value(2)) .andExpect(jsonPath("$.duplicates").value(1)) @@ -48,12 +48,23 @@ class WebhookControllerTest { .andExpect(jsonPath("$.detail").value("INVALID_PAYLOAD")); } + @Test + void aBadSignatureIs401WithInvalidSignature() throws Exception { + when(service.ingest(any(WebhookIngestRequest.class))) + .thenThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, "INVALID_SIGNATURE")); + + mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON) + .content("{\"rawBody\":\"e30=\",\"signature\":\"sha256=00\"}")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.detail").value("INVALID_SIGNATURE")); + } + @Test void aPayloadTheServiceRejectsIsInvalidPayload() throws Exception { when(service.ingest(any(WebhookIngestRequest.class))) .thenThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD")); - mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON).content("{\"payload\":{}}")) + mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON).content("{\"rawBody\":\"e30=\"}")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.detail").value("INVALID_PAYLOAD")); } diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/dto/DtoJsonTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/dto/DtoJsonTest.java index ea3248f..236c8d6 100644 --- a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/dto/DtoJsonTest.java +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/dto/DtoJsonTest.java @@ -53,8 +53,8 @@ class DtoJsonTest { @Test void webhookIngestRequestKeys() throws Exception { - WebhookIngestRequest r = new WebhookIngestRequest(List.of("INS"), mapper.readTree("{\"entry\":[]}")); - assertEquals(new TreeSet<>(List.of("matchedCompanyCodes", "payload")), keys(r)); + WebhookIngestRequest r = new WebhookIngestRequest("e30=", "sha256=00"); + assertEquals(new TreeSet<>(List.of("rawBody", "signature")), keys(r)); assertEquals(r, mapper.readValue(mapper.writeValueAsString(r), WebhookIngestRequest.class)); } } diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java index 037ecf5..50a06ec 100644 --- a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/service/WebhookIngestServiceTest.java @@ -2,6 +2,7 @@ package com.solvway.services.whatsapp.service; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.services.whatsapp.config.WhatsAppSettings; import com.solvway.services.whatsapp.dto.WebhookIngestRequest; import com.solvway.services.whatsapp.model.WaConversation; import com.solvway.services.whatsapp.model.WaMessage; @@ -20,6 +21,8 @@ import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.*; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -35,6 +38,7 @@ class WebhookIngestServiceTest { private static final ObjectMapper JSON = new ObjectMapper(); private static final String INS_PHONE = "111"; private static final String CV_PHONE = "222"; + private static final Map SECRETS = Map.of("INS", "ins-secret", "CV", "cv-secret"); private final Map conversations = new LinkedHashMap<>(); private final List messages = new ArrayList<>(); @@ -95,7 +99,11 @@ class WebhookIngestServiceTest { return m; }); ownership = mock(OwnershipService.class); - service = new WebhookIngestService(companies, convRepo, msgRepo, ownership); + WhatsAppSettings settings = mock(WhatsAppSettings.class); + when(settings.companies()).thenReturn(List.of( + new WhatsAppSettings.CompanyConfig("INS", INS_PHONE, "w1", "t1", SECRETS.get("INS")), + new WhatsAppSettings.CompanyConfig("CV", CV_PHONE, "w2", "t2", SECRETS.get("CV")))); + service = new WebhookIngestService(companies, convRepo, msgRepo, ownership, settings); } private Optional byWamid(String wamid) { @@ -116,8 +124,20 @@ class WebhookIngestServiceTest { return JSON.readTree(text); } - private IngestResult ingest(JsonNode payload, String... codes) { - return service.ingest(new WebhookIngestRequest(List.of(codes), payload)); + /** The request mobile-api forwards: the raw bytes plus Meta's signature header, signed with the given company's secret. */ + private static WebhookIngestRequest signed(byte[] raw, String secret) { + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + return new WebhookIngestRequest(Base64.getEncoder().encodeToString(raw), "sha256=" + HexFormat.of().formatHex(mac.doFinal(raw))); + } catch (java.security.GeneralSecurityException e) { + throw new IllegalStateException(e); + } + } + + /** Signs the payload with each named company's secret (first code only matters for single-signer tests). */ + private IngestResult ingest(JsonNode payload, String signer) { + return service.ingest(signed(payload.toString().getBytes(StandardCharsets.UTF_8), SECRETS.get(signer))); } private WaMessage seedOut(String wamid, String status) { @@ -197,7 +217,7 @@ class WebhookIngestServiceTest { @Test void dropsAnUnknownNumber() throws Exception { - IngestResult r = ingest(payload("text.json", "PHONE_ID", "999"), "INS", "CV"); + IngestResult r = ingest(payload("text.json", "PHONE_ID", "999"), "INS"); assertThat(r.dropped()).isEqualTo(1); assertThat(conversations).isEmpty(); @@ -206,8 +226,8 @@ class WebhookIngestServiceTest { @Test void keepsInsAndCvApart() throws Exception { - ingest(payload("text.json"), "INS", "CV"); - ingest(payload("text.json", "PHONE_ID", CV_PHONE, "WAMID", "wamid.2"), "INS", "CV"); + ingest(payload("text.json"), "INS"); + ingest(payload("text.json", "PHONE_ID", CV_PHONE, "WAMID", "wamid.2"), "CV"); assertThat(conversations).containsOnlyKeys("1/60111222333", "2/60111222333"); assertThat(conversations.get("1/60111222333").phoneNumberId).isEqualTo(INS_PHONE); @@ -372,12 +392,47 @@ class WebhookIngestServiceTest { @Test void rejectsAMalformedPayload() { - assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(List.of("INS"), null))) + assertThatThrownBy(() -> service.ingest(signed("not json".getBytes(StandardCharsets.UTF_8), SECRETS.get("INS")))) .isInstanceOfSatisfying(ResponseStatusException.class, e -> { assertThat(e.getStatusCode().value()).isEqualTo(400); assertThat(e.getReason()).isEqualTo("INVALID_PAYLOAD"); }); - assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(List.of("INS"), JSON.createObjectNode()))) + assertThatThrownBy(() -> ingest(JSON.createObjectNode(), "INS")) .isInstanceOf(ResponseStatusException.class); } + + @Test + void aForgedSignatureIsRejectedAndNothingIsStored() throws Exception { + byte[] raw = payload("text.json").toString().getBytes(StandardCharsets.UTF_8); + WebhookIngestRequest forged = new WebhookIngestRequest(signed(raw, "x").rawBody(), signed(raw, "wrong-secret").signature()); + + assertThatThrownBy(() -> service.ingest(forged)).isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode().value()).isEqualTo(401); + assertThat(e.getReason()).isEqualTo("INVALID_SIGNATURE"); + }); + assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(signed(raw, "x").rawBody(), null))) + .isInstanceOf(ResponseStatusException.class); + assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(signed(raw, "x").rawBody(), "sha256=zz"))) + .isInstanceOf(ResponseStatusException.class); + assertThat(messages).isEmpty(); + assertThat(conversations).isEmpty(); + } + + @Test + void anAlteredBodyFailsTheSignature() throws Exception { + WebhookIngestRequest ok = signed(payload("text.json").toString().getBytes(StandardCharsets.UTF_8), SECRETS.get("INS")); + byte[] altered = payload("text.json", "BODY", "other").toString().getBytes(StandardCharsets.UTF_8); + + assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(Base64.getEncoder().encodeToString(altered), ok.signature()))) + .isInstanceOf(ResponseStatusException.class); + assertThat(messages).isEmpty(); + } + + @Test + void anInsPayloadSignedWithCvSecretDropsTheInsNumber() throws Exception { + IngestResult r = ingest(payload("text.json"), "CV"); + + assertThat(r.dropped()).isEqualTo(1); + assertThat(messages).isEmpty(); + } } -- 2.54.1 From 627e0134e26932e778398d99aa6a816c394b20fa Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 02:27:53 +0800 Subject: [PATCH 10/23] docs: tick WhatsApp wave 3 tasks Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-whatsapp-inbox/tasks.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openspec/changes/add-whatsapp-inbox/tasks.md b/openspec/changes/add-whatsapp-inbox/tasks.md index 5c203c7..424acde 100644 --- a/openspec/changes/add-whatsapp-inbox/tasks.md +++ b/openspec/changes/add-whatsapp-inbox/tasks.md @@ -38,11 +38,11 @@ Verify commands: ## Wave 3 (parallel: 3.1 and 3.2) -- [ ] 3.1 mobile-api webhook: the GET handshake, the POST raw-body HMAC against each company secret, forwarding to ingest, the per-IP limit, the public-route exemptions, and `LogRedactor` masking for the webhook query. +- [x] 3.1 mobile-api webhook: the GET handshake, the POST raw-body HMAC against each company secret, forwarding to ingest, the per-IP limit, the public-route exemptions, and `LogRedactor` masking for the webhook query. - Depends on: 2.1 - Scope: `solvway-mobile-api/src/main/java/**/whatsapp/**`, `solvway-mobile-api/src/main/java/**/controller/PublicWhatsApp*`, `solvway-mobile-api/src/test/**/whatsapp/**`, `solvway-api-gateway/src/main/java/**/LogRedactor.java`, `solvway-api-gateway/src/test/**/LogRedactorTest.java`, and the public-path exemption config (security code: also read the whole diff in the controller check) - Verify: `mvn -T 0.5C -q -pl solvway-mobile-api,solvway-api-gateway verify` -- [ ] 3.2 Service ownership: `OwnershipService.recompute`, the user access check, the `leadChanged` and `userChanged` endpoints, manual assign and automatic return, and the nightly job. +- [x] 3.2 Service ownership: `OwnershipService.recompute`, the user access check, the `leadChanged` and `userChanged` endpoints, manual assign and automatic return, and the nightly job. - Depends on: 2.1, 2.2 - Scope: `solvway-services-whatsapp/src/main/java/**/ownership/**`, `solvway-services-whatsapp/src/main/java/**/job/**`, `solvway-services-whatsapp/src/test/**/ownership/**` - Verify: `mvn -T 0.5C -q -pl solvway-services-whatsapp verify` -- 2.54.1 From e6c3a488cfbd5c8866d7efc3deea8570b4c2041e Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 02:47:39 +0800 Subject: [PATCH 11/23] feat: WhatsApp inbox reads: list tabs, thread, read markers, unread, start chat The service lists a user's conversations by tab (mine, unassigned, all) with per-user unread counts in one query, pages threads backwards, keeps read markers monotonic, counts unread conversations for the badge, and starts or claims a chat from a lead or event lead. A staff call without a company fails closed. The read-marker key is a class, not a record, because Hibernate 6.4 cannot bind a record as an @IdClass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../counter/controller/LeadController.java | 7 + .../services/counter/dto/WhatsappTarget.java | 4 + .../services/counter/service/LeadService.java | 26 +- .../counter/service/WhatsappTargetTest.java | 102 +++ .../whatsapp/constants/CounterApi.java | 3 + .../whatsapp/inbox/InboxController.java | 59 ++ .../services/whatsapp/inbox/InboxService.java | 269 ++++++++ .../whatsapp/inbox/WhatsappTarget.java | 4 + .../services/whatsapp/model/WaReadId.java | 24 +- .../whatsapp/ownership/OwnershipService.java | 3 +- .../repository/WaConversationRepository.java | 15 + .../repository/WaMessageRepository.java | 25 + .../whatsapp/repository/WaReadRepository.java | 14 +- .../whatsapp/service/CompanyDirectory.java | 8 + .../services/whatsapp/inbox/InboxTest.java | 591 ++++++++++++++++++ 15 files changed, 1148 insertions(+), 6 deletions(-) create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/dto/WhatsappTarget.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappTargetTest.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxController.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/WhatsappTarget.java create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/InboxTest.java diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java index 6fc11a9..25ca60d 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java @@ -29,6 +29,13 @@ public class LeadController { return leadService.whatsappContact(companyId, mobileE164); } + @GetMapping("/lead/whatsappTarget") + public WhatsappTarget whatsappTarget(@RequestParam(value = "companyId", required = false) Long companyId, + @RequestParam(value = "leadUuid", required = false) Long leadUuid, + @RequestParam(value = "eventLeadUuid", required = false) Long eventLeadUuid) { + return leadService.whatsappTarget(companyId, leadUuid, eventLeadUuid); + } + @PostMapping("/lead/update") public LeadDetail update(@RequestBody LeadUpdateRequest req) { return leadService.update(req); } } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/WhatsappTarget.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/WhatsappTarget.java new file mode 100644 index 0000000..4759bc9 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/WhatsappTarget.java @@ -0,0 +1,4 @@ +package com.solvway.services.counter.dto; + +/** Counter GET /counter/lead/whatsappTarget response; the lead's own company id lets a super admin start without one. */ +public record WhatsappTarget(Long leadUuid, String name, String mobileE164, Long companyId) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java index 89ac5e0..80f33bc 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java @@ -7,6 +7,7 @@ import com.solvway.services.counter.dto.LeadSummary; import com.solvway.services.counter.dto.LeadUpdateRequest; import com.solvway.services.counter.dto.SharedContact; import com.solvway.services.counter.dto.WhatsappContact; +import com.solvway.services.counter.dto.WhatsappTarget; import com.solvway.services.counter.model.Event; import com.solvway.services.counter.model.EventLead; import com.solvway.services.counter.model.Lead; @@ -47,9 +48,7 @@ public class LeadService { /** A null company looks the lead up across all companies; the detail reports the lead's own company. */ public LeadDetail detail(Long companyId, long leadUuid) { - return detail(companyId == null - ? leadRepository.findByUuid(leadUuid).orElseThrow(LeadService::notFound) - : find(companyId, leadUuid)); + return detail(anyCompanyLead(companyId, leadUuid)); } /** The newest lead of the company with this mobile and its latest salesperson; 404 when there is none. */ @@ -59,6 +58,27 @@ public class LeadService { return new WhatsappContact(l.getUuid(), l.getName(), leadRepository.latestSalespersonUserId(companyId, l.getUuid())); } + /** The lead (or the event lead's lead) to start a WhatsApp chat with; a null company is any company. 404 when none or no mobile. */ + public WhatsappTarget whatsappTarget(Long companyId, Long leadUuid, Long eventLeadUuid) { + Long uuid = leadUuid; + if (uuid == null && eventLeadUuid != null) { + uuid = (companyId == null ? eventLeadRepository.findByUuid(eventLeadUuid) + : eventLeadRepository.findByUuidAndCompanyId(eventLeadUuid, companyId)).map(EventLead::getLeadUuid).orElse(null); + } + if (uuid == null) { + throw notFound(); + } + Lead l = anyCompanyLead(companyId, uuid); + if (l.getMobileE164() == null || l.getMobileE164().isBlank()) { + throw notFound(); + } + return new WhatsappTarget(l.getUuid(), l.getName(), l.getMobileE164(), l.getCompanyId()); + } + + private Lead anyCompanyLead(Long companyId, long leadUuid) { + return companyId == null ? leadRepository.findByUuid(leadUuid).orElseThrow(LeadService::notFound) : find(companyId, leadUuid); + } + @Transactional public LeadDetail update(LeadUpdateRequest req) { if (req.companyId() == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappTargetTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappTargetTest.java new file mode 100644 index 0000000..c21f299 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappTargetTest.java @@ -0,0 +1,102 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.controller.LeadController; +import com.solvway.services.counter.dto.WhatsappTarget; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.LeadRepository; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.server.ResponseStatusException; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** GET /counter/lead/whatsappTarget: the mobile and company of a lead (or of an event lead's lead) to start a chat with. */ +class WhatsappTargetTest { + private static final long COMPANY = 42L; + + private final LeadRepository leads = mock(LeadRepository.class); + private final EventLeadRepository eventLeads = mock(EventLeadRepository.class); + private final LeadService service = new LeadService(leads, eventLeads); + + private static Lead lead(long company, String mobile) { + Lead l = new Lead(); + l.setCompanyId(company); + l.setName("Aisyah"); + l.setMobileE164(mobile); + return l; + } + + private static void assertNotFound(Runnable call) { + assertThatThrownBy(call::run).isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + @Test + void leadOfTheCompanyYieldsNameMobileAndCompany() { + Lead l = lead(COMPANY, "+60111222333"); + when(leads.findByUuidAndCompanyId(l.getUuid(), COMPANY)).thenReturn(Optional.of(l)); + + assertThat(service.whatsappTarget(COMPANY, l.getUuid(), null)) + .isEqualTo(new WhatsappTarget(l.getUuid(), "Aisyah", "+60111222333", COMPANY)); + } + + @Test + void nullCompanyLooksTheLeadUpAcrossCompaniesAndReportsItsOwn() { + Lead l = lead(7L, "+60111222333"); + when(leads.findByUuid(l.getUuid())).thenReturn(Optional.of(l)); + + assertThat(service.whatsappTarget(null, l.getUuid(), null).companyId()).isEqualTo(7L); + } + + @Test + void eventLeadResolvesToItsLead() { + Lead l = lead(COMPANY, "+60111222333"); + EventLead e = new EventLead(); + e.setCompanyId(COMPANY); + e.setLeadUuid(l.getUuid()); + when(eventLeads.findByUuidAndCompanyId(e.getUuid(), COMPANY)).thenReturn(Optional.of(e)); + when(leads.findByUuidAndCompanyId(l.getUuid(), COMPANY)).thenReturn(Optional.of(l)); + + assertThat(service.whatsappTarget(COMPANY, null, e.getUuid()).leadUuid()).isEqualTo(l.getUuid()); + } + + @Test + void unknownLeadOtherCompanyOrNoMobileIs404() { + Lead noMobile = lead(COMPANY, null); + when(leads.findByUuidAndCompanyId(noMobile.getUuid(), COMPANY)).thenReturn(Optional.of(noMobile)); + Lead blank = lead(COMPANY, " "); + when(leads.findByUuidAndCompanyId(blank.getUuid(), COMPANY)).thenReturn(Optional.of(blank)); + + assertNotFound(() -> service.whatsappTarget(COMPANY, noMobile.getUuid(), null)); + assertNotFound(() -> service.whatsappTarget(COMPANY, blank.getUuid(), null)); + assertNotFound(() -> service.whatsappTarget(COMPANY, 1L, null)); + assertNotFound(() -> service.whatsappTarget(COMPANY, null, 2L)); + assertNotFound(() -> service.whatsappTarget(COMPANY, null, null)); + } + + @Test + void httpMapsFoundAndNotFound() throws Exception { + LeadService svc = mock(LeadService.class); + when(svc.whatsappTarget(COMPANY, 9L, null)).thenReturn(new WhatsappTarget(9L, "A", "+60111222333", COMPANY)); + when(svc.whatsappTarget(COMPANY, 1L, null)).thenThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new LeadController(svc)).build(); + + mvc.perform(get("/counter/lead/whatsappTarget").param("companyId", "42").param("leadUuid", "9")) + .andExpect(status().isOk()).andExpect(jsonPath("$.mobileE164").value("+60111222333")) + .andExpect(jsonPath("$.companyId").value(42)); + mvc.perform(get("/counter/lead/whatsappTarget").param("companyId", "42").param("leadUuid", "1")) + .andExpect(status().isNotFound()); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/constants/CounterApi.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/constants/CounterApi.java index b21063a..1a2979e 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/constants/CounterApi.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/constants/CounterApi.java @@ -6,4 +6,7 @@ public final class CounterApi { /** GET, query params companyId and mobileE164; returns WhatsappContact. */ public static final String WHATSAPP_CONTACT = "/counter/lead/whatsappContact"; + + /** GET, query params companyId (optional) and leadUuid or eventLeadUuid; returns the lead's name, mobileE164 and companyId, 404 when none. */ + public static final String WHATSAPP_TARGET = "/counter/lead/whatsappTarget"; } diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxController.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxController.java new file mode 100644 index 0000000..2b92973 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxController.java @@ -0,0 +1,59 @@ +package com.solvway.services.whatsapp.inbox; + +import com.solvway.services.whatsapp.dto.ConversationPage; +import com.solvway.services.whatsapp.dto.ConversationView; +import com.solvway.services.whatsapp.dto.StartChatRequest; +import com.solvway.services.whatsapp.dto.ThreadView; +import com.solvway.services.whatsapp.dto.UnreadCount; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +/** Caller context (companyId, userId, admin) arrives as trusted query params from mobile-api; the service enforces access. */ +@RestController +@RequestMapping("/whatsapp") +public class InboxController { + + private final InboxService service; + + public InboxController(InboxService service) { + this.service = service; + } + + @GetMapping("/conversations") + public ConversationPage list(@RequestParam(required = false) Long companyId, @RequestParam Long userId, @RequestParam boolean admin, + @RequestParam(defaultValue = "mine") String tab, @RequestParam(required = false) String q, + @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "30") int size) { + return service.list(companyId, userId, admin, tab, q, page, size); + } + + @GetMapping("/conversations/{uuid}") + public ThreadView thread(@PathVariable String uuid, @RequestParam(required = false) Long companyId, @RequestParam Long userId, + @RequestParam boolean admin, @RequestParam(required = false) String before) { + return service.thread(uuid, companyId, userId, admin, before); + } + + @PostMapping("/conversations/{uuid}/read") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void read(@PathVariable String uuid, @RequestParam(required = false) Long companyId, @RequestParam Long userId, + @RequestParam boolean admin) { + service.markRead(uuid, companyId, userId, admin); + } + + @GetMapping("/unreadCount") + public UnreadCount unreadCount(@RequestParam(required = false) Long companyId, @RequestParam Long userId, @RequestParam boolean admin) { + return service.unreadCount(companyId, userId, admin); + } + + @PostMapping("/conversations/start") + public ConversationView start(@RequestParam(required = false) Long companyId, @RequestParam Long userId, @RequestParam boolean admin, + @RequestBody StartChatRequest request) { + return service.start(companyId, userId, admin, request); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java new file mode 100644 index 0000000..163e967 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java @@ -0,0 +1,269 @@ +package com.solvway.services.whatsapp.inbox; + +import com.solvway.services.whatsapp.constants.CounterApi; +import com.solvway.services.whatsapp.dto.ConversationPage; +import com.solvway.services.whatsapp.dto.ConversationView; +import com.solvway.services.whatsapp.dto.MessageView; +import com.solvway.services.whatsapp.dto.StartChatRequest; +import com.solvway.services.whatsapp.dto.ThreadView; +import com.solvway.services.whatsapp.dto.UnreadCount; +import com.solvway.services.whatsapp.dto.WhatsappContact; +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.model.WaMessage; +import com.solvway.services.whatsapp.model.WaRead; +import com.solvway.services.whatsapp.ownership.OwnershipService; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import com.solvway.services.whatsapp.repository.WaMessageRepository; +import com.solvway.services.whatsapp.repository.WaReadRepository; +import com.solvway.services.whatsapp.service.CompanyDirectory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.server.ResponseStatusException; + +import java.net.URI; +import java.time.Clock; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * Inbox reads. Access is enforced here from the trusted caller context: another company's chat is always 404, and with + * admin=false so is a chat the user does not own. Never logs numbers, names or message text. + */ +@Service +public class InboxService { + + private static final int DEFAULT_PAGE = 30; + private static final int MAX_PAGE = 100; + private static final int THREAD_PAGE = 50; + private static final Sort LIST_ORDER = Sort.by(Sort.Order.desc("lastMessageAt"), Sort.Order.desc("id")); + + private final WaConversationRepository conversations; + private final WaMessageRepository messages; + private final WaReadRepository reads; + private final OwnershipService ownership; + private final CompanyDirectory companies; + private final RestTemplate rest; + private final Clock clock; + + @Autowired + public InboxService(WaConversationRepository conversations, WaMessageRepository messages, WaReadRepository reads, + OwnershipService ownership, CompanyDirectory companies, RestTemplateBuilder builder) { + this(conversations, messages, reads, ownership, companies, + builder.setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(10)).build(), Clock.systemDefaultZone()); + } + + InboxService(WaConversationRepository conversations, WaMessageRepository messages, WaReadRepository reads, + OwnershipService ownership, CompanyDirectory companies, RestTemplate rest, Clock clock) { + this.conversations = conversations; + this.messages = messages; + this.reads = reads; + this.ownership = ownership; + this.companies = companies; + this.rest = rest; + this.clock = clock; + } + + /** + * mine = owned by the user; unassigned = nobody owns it (admin only, staff get an empty page, not an error); + * all = everything in scope for an admin, only own for staff. + * ponytail: q matches contact name and number only (the lead name is not stored); list rows carry no leadName + * (one counter call per row is not acceptable), the thread and start views do. + */ + public ConversationPage list(Long companyId, Long userId, boolean admin, String tab, String q, int page, int size) { + int pageNo = Math.max(page, 0); + int pageSize = size < 1 ? DEFAULT_PAGE : Math.min(size, MAX_PAGE); + if (failClosed(companyId, admin)) { + return new ConversationPage(List.of(), 0, pageNo, pageSize); + } + Long owner = userId; + boolean unassigned = false; + switch (tab == null ? "mine" : tab) { + case "mine" -> { } + case "all" -> owner = admin ? null : userId; + case "unassigned" -> { + if (!admin) { + return new ConversationPage(List.of(), 0, pageNo, pageSize); + } + owner = null; + unassigned = true; + } + default -> throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); + } + String text = q == null ? "" : q.trim(); + String digits = text.replaceAll("\\D", ""); + // ponytail: LIKE wildcards are stripped from q instead of escaped. + String name = text.isEmpty() ? null : "%" + text.toLowerCase().replaceAll("[%_\\\\]", "") + "%"; + Page found = conversations.list(companyId, owner, unassigned, name, digits.isEmpty() || text.isEmpty() ? null : "%" + digits + "%", + PageRequest.of(pageNo, pageSize, LIST_ORDER)); + Map unread = unread(found.getContent().stream().map(c -> c.id).toList(), userId); + List items = found.getContent().stream().map(c -> view(c, null, unread.getOrDefault(c.id, 0L))).toList(); + return new ConversationPage(items, found.getTotalElements(), pageNo, pageSize); + } + + public ThreadView thread(String uuid, Long companyId, Long userId, boolean admin, String before) { + WaConversation c = visible(uuid, companyId, userId, admin); + Pageable page = PageRequest.of(0, THREAD_PAGE + 1); + List rows; + if (before == null) { + rows = messages.findByConversationIdOrderByIdDesc(c.id, page); + } else { + WaMessage cursor = messages.findByUuid(before).filter(m -> c.id.equals(m.conversationId)).orElseThrow(InboxService::notFound); + rows = messages.findByConversationIdAndIdLessThanOrderByIdDesc(c.id, cursor.id, page); + } + boolean hasOlder = rows.size() > THREAD_PAGE; + List newestFirst = new ArrayList<>(rows.subList(0, Math.min(rows.size(), THREAD_PAGE))); + Collections.reverse(newestFirst); + return new ThreadView(view(c, leadName(c), unread(List.of(c.id), userId).getOrDefault(c.id, 0L)), + newestFirst.stream().map(InboxService::message).toList(), hasOlder); + } + + /** Monotonic upsert (GREATEST in SQL): concurrent reads never move the marker back and first reads cannot collide. */ + public void markRead(String uuid, Long companyId, Long userId, boolean admin) { + WaConversation c = visible(uuid, companyId, userId, admin); + messages.findFirstByConversationIdOrderByIdDesc(c.id).ifPresent(last -> reads.markRead(c.id, userId, last.id)); + } + + /** ponytail: an admin counts every conversation of the company, so the badge can be large. */ + public UnreadCount unreadCount(Long companyId, Long userId, boolean admin) { + if (failClosed(companyId, admin)) { + return new UnreadCount(0); + } + return new UnreadCount(messages.unreadConversations(companyId, admin ? null : userId, userId)); + } + + /** Opens (or creates) the chat with a lead's number. An unowned chat becomes the starter's manual chat. */ + public ConversationView start(Long companyId, Long userId, boolean admin, StartChatRequest request) { + if (failClosed(companyId, admin)) { + throw notFound(); + } + if (request == null || (request.leadUuid() == null && request.eventLeadUuid() == null)) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); + } + WhatsappTarget target = target(companyId, request); + String digits = target.mobileE164() == null ? "" : target.mobileE164().replaceAll("\\D", ""); + if (digits.isEmpty() || target.companyId() == null || (companyId != null && !companyId.equals(target.companyId()))) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND"); + } + Long company = target.companyId(); + String phoneNumberId = companies.phoneNumberIdOf(company) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED")); + WaConversation c = conversations.findByCompanyIdAndContactWaId(company, digits) + .orElseGet(() -> create(company, digits, phoneNumberId, target.name())); + if (c.ownerUserId == null) { + if (conversations.claimIfUnowned(c.id, userId, target.leadUuid()) == 1) { + c.ownerUserId = userId; + c.ownerManual = true; + c.leadUuid = target.leadUuid(); + } else { // lost the race: someone owns it now + c = conversations.findById(c.id).orElse(c); + } + } + if (!admin && !userId.equals(c.ownerUserId)) { // owner fields only: no preview, no unread + return view(c, target.name(), 0, false); + } + return view(c, target.name(), unread(List.of(c.id), userId).getOrDefault(c.id, 0L), true); + } + + private WhatsappTarget target(Long companyId, StartChatRequest request) { + String query = (companyId == null ? "?" : "?companyId=" + companyId + "&") + + (request.leadUuid() != null ? "leadUuid=" + request.leadUuid() : "eventLeadUuid=" + request.eventLeadUuid()); + try { + WhatsappTarget target = rest.getForObject(URI.create("http://service-counter" + CounterApi.WHATSAPP_TARGET + query), WhatsappTarget.class); + if (target == null) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND"); + } + return target; + } catch (HttpClientErrorException.NotFound e) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND"); + } catch (ResponseStatusException e) { + throw e; + } catch (RuntimeException e) { + throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "COUNTER_UNAVAILABLE"); + } + } + + private WaConversation create(Long company, String digits, String phoneNumberId, String leadName) { + WaConversation c = new WaConversation(); + c.uuid = UUID.randomUUID().toString(); + c.companyId = company; + c.contactWaId = digits; + c.contactName = leadName == null || leadName.length() <= 255 ? leadName : leadName.substring(0, 255); + c.phoneNumberId = phoneNumberId; + c.createdAt = LocalDateTime.now(clock); + try { + return conversations.save(c); + } catch (DataIntegrityViolationException e) { // a concurrent first message or start created it + return conversations.findByCompanyIdAndContactWaId(company, digits).orElseThrow(() -> e); + } + } + + /** Only a super admin may span companies; a non-admin without a company must never mean "all". */ + private static boolean failClosed(Long companyId, boolean admin) { + return companyId == null && !admin; + } + + private WaConversation visible(String uuid, Long companyId, Long userId, boolean admin) { + if (failClosed(companyId, admin)) { + throw notFound(); + } + return conversations.findByUuid(uuid) + .filter(c -> companyId == null || companyId.equals(c.companyId)) + .filter(c -> admin || userId.equals(c.ownerUserId)) + .orElseThrow(InboxService::notFound); + } + + /** Unread inbound messages per conversation for the user, in one grouped query. */ + private Map unread(List ids, Long userId) { + Map counts = new HashMap<>(); + if (!ids.isEmpty()) { + messages.unreadByConversation(ids, userId).forEach(r -> counts.put((Long) r[0], ((Number) r[1]).longValue())); + } + return counts; + } + + private String leadName(WaConversation c) { + if (c.leadUuid == null) { + return null; + } + try { + WhatsappContact contact = ownership.lookup(c); + return contact == null ? null : contact.name(); + } catch (RuntimeException e) { // the name is decoration; an unreachable counter must not fail the thread + return null; + } + } + + private ConversationView view(WaConversation c, String leadName, long unread) { + return view(c, leadName, unread, true); + } + + private ConversationView view(WaConversation c, String leadName, long unread, boolean withPreview) { + boolean open = c.lastInboundAt != null && c.lastInboundAt.isAfter(LocalDateTime.now(clock).minusHours(24)); + return new ConversationView(c.uuid, c.companyId, c.contactWaId, c.contactName, c.leadUuid, leadName, c.ownerUserId, null, + c.ownerManual, c.lastInboundAt, c.lastMessageAt, withPreview ? c.lastMessagePreview : null, open, unread); + } + + private static MessageView message(WaMessage m) { + return new MessageView(m.uuid, m.direction, m.type, m.body, m.templateName, m.mediaMime, m.mediaFilename, m.locationLat, + m.locationLng, m.locationName, m.status, m.errorCode, m.errorTitle, m.sentByUserId, m.createdAt, m.statusAt); + } + + private static ResponseStatusException notFound() { + return new ResponseStatusException(HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND"); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/WhatsappTarget.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/WhatsappTarget.java new file mode 100644 index 0000000..b85cc13 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/WhatsappTarget.java @@ -0,0 +1,4 @@ +package com.solvway.services.whatsapp.inbox; + +/** Counter GET /counter/lead/whatsappTarget response: who to start a chat with, and the lead's company. */ +public record WhatsappTarget(Long leadUuid, String name, String mobileE164, Long companyId) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaReadId.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaReadId.java index e66bb7f..473912c 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaReadId.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaReadId.java @@ -1,5 +1,27 @@ package com.solvway.services.whatsapp.model; import java.io.Serializable; +import java.util.Objects; -public record WaReadId(Long conversationId, Long userId) implements Serializable {} +/** Composite key of wa_read. A class, not a record: Hibernate 6.4 cannot bind a record as an @IdClass (startup fails). */ +public class WaReadId implements Serializable { + public Long conversationId; + public Long userId; + + public WaReadId() {} + + public WaReadId(Long conversationId, Long userId) { + this.conversationId = conversationId; + this.userId = userId; + } + + @Override + public boolean equals(Object o) { + return o instanceof WaReadId k && Objects.equals(conversationId, k.conversationId) && Objects.equals(userId, k.userId); + } + + @Override + public int hashCode() { + return Objects.hash(conversationId, userId); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipService.java index 8806f66..2fd49fc 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipService.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipService.java @@ -148,7 +148,8 @@ public class OwnershipService { c.lastInboundAt != null && c.lastInboundAt.isAfter(LocalDateTime.now().minusHours(24)), 0); } - private WhatsappContact lookup(WaConversation c) { + /** The newest lead for the conversation's number; null when there is none. Throws when the counter is unreachable. */ + public WhatsappContact lookup(WaConversation c) { String mobile = URLEncoder.encode("+" + c.contactWaId, StandardCharsets.UTF_8); try { return rest.getForObject(URI.create("http://service-counter" + CounterApi.WHATSAPP_CONTACT diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java index c66ac11..3283aac 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java @@ -1,6 +1,7 @@ package com.solvway.services.whatsapp.repository; import com.solvway.services.whatsapp.model.WaConversation; +import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; @@ -32,6 +33,13 @@ public interface WaConversationRepository extends JpaRepository findByUuid(String uuid); + /** Inbox list: null companyId = all companies, null owner = any owner; q and digits are ready-made LIKE patterns. */ + @Query("select c from WaConversation c where (:companyId is null or c.companyId = :companyId) " + + "and (:owner is null or c.ownerUserId = :owner) and (:unassigned = false or c.ownerUserId is null) " + + "and (:q is null or lower(c.contactName) like :q or c.contactWaId like :digits)") + Page list(@Param("companyId") Long companyId, @Param("owner") Long owner, @Param("unassigned") boolean unassigned, + @Param("q") String q, @Param("digits") String digits, Pageable page); + List findByOwnerUserId(Long ownerUserId); /** Keyset paging (stable while rows are updated underneath), used by the nightly job. */ @@ -53,4 +61,11 @@ public interface WaConversationRepository extends JpaRepository :prevOwner", nativeQuery = true) int casOwnership(@Param("id") Long id, @Param("owner") Long owner, @Param("lead") Long lead, @Param("prevManual") boolean prevManual, @Param("prevOwner") Long prevOwner); + + /** Manual claim of an unowned chat: loses (0 rows) if someone owned it first. */ + @Transactional + @Modifying + @Query(value = "UPDATE wa_conversation SET owner_user_id = :owner, owner_manual = true, lead_uuid = :lead " + + "WHERE id = :id AND owner_user_id IS NULL", nativeQuery = true) + int claimIfUnowned(@Param("id") Long id, @Param("owner") Long owner, @Param("lead") Long lead); } diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaMessageRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaMessageRepository.java index e888ca1..f90db1f 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaMessageRepository.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaMessageRepository.java @@ -1,12 +1,37 @@ package com.solvway.services.whatsapp.repository; import com.solvway.services.whatsapp.model.WaMessage; +import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import java.util.List; import java.util.Optional; public interface WaMessageRepository extends JpaRepository { boolean existsByWamid(String wamid); + Optional findByUuid(String uuid); + + List findByConversationIdOrderByIdDesc(Long conversationId, Pageable page); + + List findByConversationIdAndIdLessThanOrderByIdDesc(Long conversationId, Long beforeId, Pageable page); + + Optional findFirstByConversationIdOrderByIdDesc(Long conversationId); + + /** Rows are [conversationId, unread inbound count] for the user (messages newer than their read marker); none for zero. */ + @Query("select m.conversationId, count(m) from WaMessage m where m.conversationId in :ids and m.direction = 'IN' " + + "and m.id > coalesce((select r.lastReadMessageId from WaRead r where r.conversationId = m.conversationId and r.userId = :userId), 0) " + + "group by m.conversationId") + List unreadByConversation(@Param("ids") List ids, @Param("userId") Long userId); + + /** Conversations (null companyId = all, null owner = any) with an inbound message newer than the user's read marker. */ + @Query("select count(distinct m.conversationId) from WaMessage m, WaConversation c where c.id = m.conversationId " + + "and (:companyId is null or c.companyId = :companyId) and (:owner is null or c.ownerUserId = :owner) " + + "and m.direction = 'IN' " + + "and m.id > coalesce((select r.lastReadMessageId from WaRead r where r.conversationId = m.conversationId and r.userId = :userId), 0)") + long unreadConversations(@Param("companyId") Long companyId, @Param("owner") Long owner, @Param("userId") Long userId); + Optional findByWamidAndDirection(String wamid, String direction); } diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaReadRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaReadRepository.java index 4346e82..614a0c3 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaReadRepository.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaReadRepository.java @@ -3,5 +3,17 @@ package com.solvway.services.whatsapp.repository; import com.solvway.services.whatsapp.model.WaRead; import com.solvway.services.whatsapp.model.WaReadId; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; -public interface WaReadRepository extends JpaRepository {} +public interface WaReadRepository extends JpaRepository { + + /** Upsert that only moves the marker forward. */ + @Transactional + @Modifying + @Query(value = "INSERT INTO wa_read (conversation_id, user_id, last_read_message_id) VALUES (:conversation, :user, :message) " + + "ON DUPLICATE KEY UPDATE last_read_message_id = GREATEST(last_read_message_id, VALUES(last_read_message_id))", nativeQuery = true) + int markRead(@Param("conversation") Long conversation, @Param("user") Long user, @Param("message") Long message); +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java index ab029cd..6d2630f 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java @@ -64,6 +64,14 @@ public class CompanyDirectory { return Optional.ofNullable(byPhoneNumberId.get(phoneNumberId)); } + /** The configured phone number id of the company; empty when WhatsApp is not configured for it (or not resolved yet). */ + public Optional phoneNumberIdOf(long companyId) { + if (!unresolved.isEmpty() && !coolingDown()) { + resolve(); + } + return byPhoneNumberId.entrySet().stream().filter(e -> e.getValue().id() == companyId).map(Map.Entry::getKey).findFirst(); + } + private boolean coolingDown() { Instant failed = lastFailure; return failed != null && clock.instant().isBefore(failed.plus(RETRY_COOLDOWN)); diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/InboxTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/InboxTest.java new file mode 100644 index 0000000..088879c --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/InboxTest.java @@ -0,0 +1,591 @@ +package com.solvway.services.whatsapp.inbox; + +import com.solvway.services.whatsapp.controller.ErrorHandler; +import com.solvway.services.whatsapp.dto.ConversationPage; +import com.solvway.services.whatsapp.dto.ConversationView; +import com.solvway.services.whatsapp.dto.StartChatRequest; +import com.solvway.services.whatsapp.dto.ThreadView; +import com.solvway.services.whatsapp.dto.WhatsappContact; +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.model.WaMessage; +import com.solvway.services.whatsapp.model.WaRead; +import com.solvway.services.whatsapp.ownership.OwnershipService; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import com.solvway.services.whatsapp.repository.WaMessageRepository; +import com.solvway.services.whatsapp.repository.WaReadRepository; +import com.solvway.services.whatsapp.service.CompanyDirectory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.http.HttpStatus; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.server.ResponseStatusException; + +import java.net.URI; +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class InboxTest { + + private static final LocalDateTime NOW = LocalDateTime.of(2026, 12, 2, 12, 0); + private static final long STAFF = 10L; + + private WaConversationRepository conversations; + private WaMessageRepository messages; + private WaReadRepository reads; + private OwnershipService ownership; + private CompanyDirectory directory; + private RestTemplate rest; + private InboxService service; + private MockMvc mvc; + private WhatsappTarget target; // null = counter answers 404 + private boolean counterDown; + + @BeforeEach + void setUp() { + conversations = mock(WaConversationRepository.class); + messages = mock(WaMessageRepository.class); + reads = mock(WaReadRepository.class); + ownership = mock(OwnershipService.class); + directory = mock(CompanyDirectory.class); + rest = mock(RestTemplate.class); + when(rest.getForObject(any(URI.class), eq(WhatsappTarget.class))).thenAnswer(i -> { + if (counterDown) { + throw new ResourceAccessException("down"); + } + if (target == null) { + throw HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null); + } + return target; + }); + when(conversations.claimIfUnowned(anyLong(), any(), any())).thenReturn(1); + when(directory.phoneNumberIdOf(1L)).thenReturn(Optional.of("111")); + when(conversations.save(any(WaConversation.class))).thenAnswer(i -> { + WaConversation c = i.getArgument(0); + c.id = 99L; + return c; + }); + Clock clock = Clock.fixed(NOW.toInstant(ZoneOffset.UTC), ZoneOffset.UTC); + service = new InboxService(conversations, messages, reads, ownership, directory, rest, clock); + mvc = MockMvcBuilders.standaloneSetup(new InboxController(service)).setControllerAdvice(new ErrorHandler()).build(); + } + + private static WaConversation conv(long id, Long company, Long owner) { + WaConversation c = new WaConversation(); + c.id = id; + c.uuid = "u-" + id; + c.companyId = company; + c.contactWaId = "6011122" + id; + c.contactName = "Name" + id; + c.ownerUserId = owner; + c.lastInboundAt = NOW.minusHours(1); + c.lastMessageAt = NOW.minusHours(1); + return c; + } + + private void given(WaConversation c) { + when(conversations.findByUuid(c.uuid)).thenReturn(Optional.of(c)); + } + + private static WaMessage msg(long id) { + WaMessage m = new WaMessage(); + m.id = id; + m.uuid = "m-" + id; + m.direction = "IN"; + m.type = "text"; + m.body = "hi" + id; + return m; + } + + private static void assertNotFound(Runnable call) { + assertThatThrownBy(call::run).isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(e.getReason()).isEqualTo("CONVERSATION_NOT_FOUND"); + }); + } + + // ---- inbox access + + @Test + void staffOpeningSomeoneElsesChatGets404OnThreadAndRead() { + given(conv(5, 1L, 11L)); + + assertNotFound(() -> service.thread("u-5", 1L, STAFF, false, null)); + assertNotFound(() -> service.markRead("u-5", 1L, STAFF, false)); + verify(reads, never()).save(any()); + } + + @Test + void conversationOfAnotherCompanyIs404EvenForAnAdmin() { + given(conv(5, 2L, STAFF)); + + assertNotFound(() -> service.thread("u-5", 1L, STAFF, true, null)); + assertNotFound(() -> service.markRead("u-5", 1L, STAFF, true)); + } + + @Test + void superAdminWithoutCompanyOpensAnyCompany() { + given(conv(5, 2L, null)); + + assertThat(service.thread("u-5", null, STAFF, true, null).conversation().uuid()).isEqualTo("u-5"); + } + + @Test + void unknownConversationIs404() { + when(conversations.findByUuid("zz")).thenReturn(Optional.empty()); + + assertNotFound(() -> service.thread("zz", 1L, STAFF, true, null)); + } + + @Test + void adminUnassignedTabListsOnlyTheirCompany() { + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of())); + + service.list(1L, STAFF, true, "unassigned", null, 0, 30); + + verify(conversations).list(eq(1L), isNull(), eq(true), isNull(), isNull(), any(Pageable.class)); + } + + @Test + void staffUnassignedTabIsEmptyAndNeverQueries() { + ConversationPage page = service.list(1L, STAFF, false, "unassigned", null, 0, 30); + + assertThat(page.items()).isEmpty(); + assertThat(page.total()).isZero(); + verify(conversations, never()).list(any(), any(), anyBoolean(), any(), any(), any()); + } + + @Test + void allTabIsEverythingForAdminAndOnlyOwnForStaff() { + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of())); + + service.list(1L, STAFF, true, "all", null, 0, 30); + service.list(1L, STAFF, false, "all", null, 0, 30); + service.list(1L, STAFF, false, "mine", null, 0, 30); + + verify(conversations).list(eq(1L), isNull(), eq(false), isNull(), isNull(), any()); + verify(conversations, times(2)).list(eq(1L), eq(STAFF), eq(false), isNull(), isNull(), any()); + } + + @Test + void superAdminListIsNotCompanyScoped() { + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of())); + + service.list(null, STAFF, true, "all", null, 0, 30); + + verify(conversations).list(isNull(), isNull(), eq(false), isNull(), isNull(), any()); + } + + @Test + void unknownTabIs400() { + assertThatThrownBy(() -> service.list(1L, STAFF, true, "bogus", null, 0, 30)) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST)); + } + + // ---- list: ordering, paging, filter, flags + + @Test + void listOrdersByLastMessageThenIdAndClampsThePageSize() { + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of())); + ArgumentCaptor page = ArgumentCaptor.forClass(Pageable.class); + + service.list(1L, STAFF, true, "all", null, 2, 0); + service.list(1L, STAFF, true, "all", null, -1, 500); + + verify(conversations, times(2)).list(any(), any(), anyBoolean(), any(), any(), page.capture()); + Pageable first = page.getAllValues().get(0); + Pageable second = page.getAllValues().get(1); + assertThat(first.getPageSize()).isEqualTo(30); + assertThat(first.getPageNumber()).isEqualTo(2); + assertThat(second.getPageSize()).isEqualTo(100); + assertThat(second.getPageNumber()).isZero(); + assertThat(first.getSort()).isEqualTo(Sort.by(Sort.Order.desc("lastMessageAt"), Sort.Order.desc("id"))); + } + + @Test + void qMatchesNameCaseInsensitivelyAndNumberByDigitsOnly() { + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of())); + + service.list(1L, STAFF, true, "all", " Ais_% ", 0, 30); + service.list(1L, STAFF, true, "all", "+60 11-22", 0, 30); + service.list(1L, STAFF, true, "all", " ", 0, 30); + + verify(conversations).list(any(), any(), anyBoolean(), eq("%ais%"), isNull(), any()); + verify(conversations).list(any(), any(), anyBoolean(), eq("%+60 11-22%"), eq("%601122%"), any()); + verify(conversations).list(any(), any(), anyBoolean(), isNull(), isNull(), any()); + } + + @Test + void listItemsCarryWindowFlagAndUnreadFromOneGroupedQuery() { + WaConversation a = conv(1, 1L, STAFF); + WaConversation b = conv(2, 1L, STAFF); + b.lastInboundAt = NOW.minusHours(30); + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of(a, b))); + when(messages.unreadByConversation(anyList(), eq(STAFF))).thenReturn(Collections.singletonList(new Object[] {1L, 3L})); + + ConversationPage page = service.list(1L, STAFF, false, "mine", null, 0, 30); + + verify(messages, times(1)).unreadByConversation(eq(List.of(1L, 2L)), eq(STAFF)); + assertThat(page.items()).extracting(ConversationView::uuid).containsExactly("u-1", "u-2"); + assertThat(page.items()).extracting(ConversationView::unreadCount).containsExactly(3L, 0L); + assertThat(page.items()).extracting(ConversationView::windowOpen).containsExactly(true, false); + assertThat(page.items()).extracting(ConversationView::leadName).containsOnlyNulls(); + assertThat(page.items().get(0).ownerName()).isNull(); + assertThat(page.total()).isEqualTo(2); + assertThat(page.size()).isEqualTo(30); + } + + @Test + void windowIsOpenAt23h59AndClosedAt24h() { + WaConversation open = conv(1, 1L, STAFF); + open.lastInboundAt = NOW.minusHours(23).minusMinutes(59); + WaConversation closed = conv(2, 1L, STAFF); + closed.lastInboundAt = NOW.minusHours(24); + WaConversation never = conv(3, 1L, STAFF); + never.lastInboundAt = null; + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of(open, closed, never))); + + ConversationPage page = service.list(1L, STAFF, false, "mine", null, 0, 30); + + assertThat(page.items()).extracting(ConversationView::windowOpen).containsExactly(true, false, false); + } + + // ---- thread + + @Test + void threadReturnsNewestLastAndHasOlderWhenMoreThanAPageExists() { + given(conv(5, 1L, STAFF)); + List newestFirst = new ArrayList<>(); + for (long id = 60; id >= 10; id--) { // 51 rows + newestFirst.add(msg(id)); + } + when(messages.findByConversationIdOrderByIdDesc(eq(5L), any(Pageable.class))).thenReturn(newestFirst); + + ThreadView view = service.thread("u-5", 1L, STAFF, false, null); + + assertThat(view.hasOlder()).isTrue(); + assertThat(view.messages()).hasSize(50); + assertThat(view.messages().get(0).uuid()).isEqualTo("m-11"); + assertThat(view.messages().get(49).uuid()).isEqualTo("m-60"); + ArgumentCaptor page = ArgumentCaptor.forClass(Pageable.class); + verify(messages).findByConversationIdOrderByIdDesc(eq(5L), page.capture()); + assertThat(page.getValue().getPageSize()).isEqualTo(51); + } + + @Test + void threadWithBeforeContinuesFromThatMessageAndSaysWhenItIsTheStart() { + given(conv(5, 1L, STAFF)); + WaMessage cursor = msg(11); + cursor.conversationId = 5L; + when(messages.findByUuid("m-11")).thenReturn(Optional.of(cursor)); + when(messages.findByConversationIdAndIdLessThanOrderByIdDesc(eq(5L), eq(11L), any(Pageable.class))) + .thenReturn(List.of(msg(10), msg(9))); + + ThreadView view = service.thread("u-5", 1L, STAFF, false, "m-11"); + + assertThat(view.hasOlder()).isFalse(); + assertThat(view.messages()).extracting(m -> m.uuid()).containsExactly("m-9", "m-10"); + } + + @Test + void threadBeforeAMessageOfAnotherConversationIs404() { + given(conv(5, 1L, STAFF)); + WaMessage foreign = msg(11); + foreign.conversationId = 6L; + when(messages.findByUuid("m-11")).thenReturn(Optional.of(foreign)); + + assertNotFound(() -> service.thread("u-5", 1L, STAFF, false, "m-11")); + when(messages.findByUuid("nope")).thenReturn(Optional.empty()); + assertNotFound(() -> service.thread("u-5", 1L, STAFF, false, "nope")); + } + + @Test + void threadLooksUpTheLeadNameOnceAndToleratesFailure() { + WaConversation c = conv(5, 1L, STAFF); + c.leadUuid = 77L; + given(c); + when(ownership.lookup(c)).thenReturn(new WhatsappContact(77L, "Aisyah", 10L)); + + assertThat(service.thread("u-5", 1L, STAFF, false, null).conversation().leadName()).isEqualTo("Aisyah"); + + when(ownership.lookup(c)).thenThrow(new ResourceAccessException("down")); + assertThat(service.thread("u-5", 1L, STAFF, false, null).conversation().leadName()).isNull(); + + WaConversation noLead = conv(6, 1L, STAFF); + given(noLead); + service.thread("u-6", 1L, STAFF, false, null); + verify(ownership, never()).lookup(noLead); + } + + // ---- read markers and unread counts + + @Test + void readingMarksTheLastMessageAndAnEmptyChatIsANoOp() { + given(conv(5, 1L, STAFF)); + when(messages.findFirstByConversationIdOrderByIdDesc(5L)).thenReturn(Optional.of(msg(42))); + + service.markRead("u-5", 1L, STAFF, false); + + // monotonic upsert (GREATEST in SQL), not read-modify-write + verify(reads).markRead(5L, STAFF, 42L); + verify(reads, never()).save(any()); + + given(conv(6, 1L, STAFF)); + when(messages.findFirstByConversationIdOrderByIdDesc(6L)).thenReturn(Optional.empty()); + service.markRead("u-6", 1L, STAFF, false); + verify(reads, times(1)).markRead(anyLong(), anyLong(), anyLong()); + } + + @Test + void unreadCountIsPerUserMineForStaffAndWholeCompanyForAdmin() { + when(messages.unreadConversations(anyLong(), any(), anyLong())).thenReturn(4L); + when(messages.unreadConversations(isNull(), any(), anyLong())).thenReturn(9L); + + assertThat(service.unreadCount(1L, STAFF, false).count()).isEqualTo(4L); + verify(messages).unreadConversations(1L, STAFF, STAFF); + assertThat(service.unreadCount(1L, STAFF, true).count()).isEqualTo(4L); + verify(messages).unreadConversations(1L, null, STAFF); + assertThat(service.unreadCount(null, STAFF, true).count()).isEqualTo(9L); + } + + // ---- start a chat + + private void leadOf(long company, String mobile) { + target = new WhatsappTarget(77L, "Aisyah", mobile, company); + } + + @Test + void startOnAnUnownedChatMakesItTheStartersManualChat() { + leadOf(1L, "+60111222333"); + WaConversation c = conv(5, 1L, null); + c.contactWaId = "60111222333"; + when(conversations.findByCompanyIdAndContactWaId(1L, "60111222333")).thenReturn(Optional.of(c)); + + ConversationView view = service.start(1L, STAFF, false, new StartChatRequest(77L, null)); + + verify(conversations).claimIfUnowned(5L, STAFF, 77L); + assertThat(view.ownerUserId()).isEqualTo(STAFF); + assertThat(view.ownerManual()).isTrue(); + assertThat(view.leadName()).isEqualTo("Aisyah"); + assertThat(view.leadUuid()).isEqualTo(77L); + } + + @Test + void startCreatesTheConversationWithThePhoneNumberOfTheCompany() { + leadOf(1L, "+60111222333"); + when(conversations.findByCompanyIdAndContactWaId(1L, "60111222333")).thenReturn(Optional.empty()); + + ConversationView view = service.start(1L, STAFF, false, new StartChatRequest(null, 500L)); + + ArgumentCaptor saved = ArgumentCaptor.forClass(WaConversation.class); + verify(conversations).save(saved.capture()); + assertThat(saved.getValue().companyId).isEqualTo(1L); + assertThat(saved.getValue().contactWaId).isEqualTo("60111222333"); + assertThat(saved.getValue().phoneNumberId).isEqualTo("111"); + assertThat(saved.getValue().uuid).isNotBlank(); + verify(conversations).claimIfUnowned(99L, STAFF, 77L); + assertThat(view.ownerUserId()).isEqualTo(STAFF); + assertThat(view.windowOpen()).isFalse(); + } + + @Test + void startOnSomeoneElsesChatShowsTheOwnerAndChangesNothing() { + leadOf(1L, "+60111222333"); + WaConversation c = conv(5, 1L, 11L); + c.ownerManual = true; + c.contactWaId = "60111222333"; + when(conversations.findByCompanyIdAndContactWaId(1L, "60111222333")).thenReturn(Optional.of(c)); + + ConversationView view = service.start(1L, STAFF, false, new StartChatRequest(77L, null)); + + verify(conversations, never()).claimIfUnowned(anyLong(), any(), any()); + assertThat(view.ownerUserId()).isEqualTo(11L); + assertThat(view.ownerManual()).isTrue(); + verify(messages, never()).findByConversationIdOrderByIdDesc(anyLong(), any()); + assertThat(view.lastMessagePreview()).isNull(); + assertThat(view.unreadCount()).isZero(); + assertThat(view.contactName()).isEqualTo("Name5"); + assertThat(view.leadName()).isEqualTo("Aisyah"); + verify(messages, never()).unreadByConversation(anyList(), anyLong()); + } + + @Test + void startLosingTheClaimRaceShowsTheWinnerAsOwnerFieldsOnly() { + leadOf(1L, "+60111222333"); + WaConversation c = conv(5, 1L, null); + c.contactWaId = "60111222333"; + c.lastMessagePreview = "secret"; + WaConversation winner = conv(5, 1L, 11L); + winner.ownerManual = true; + winner.lastMessagePreview = "secret"; + when(conversations.findByCompanyIdAndContactWaId(1L, "60111222333")).thenReturn(Optional.of(c)); + when(conversations.claimIfUnowned(5L, STAFF, 77L)).thenReturn(0); + when(conversations.findById(5L)).thenReturn(Optional.of(winner)); + + ConversationView view = service.start(1L, STAFF, false, new StartChatRequest(77L, null)); + + assertThat(view.ownerUserId()).isEqualTo(11L); + assertThat(view.lastMessagePreview()).isNull(); + assertThat(view.unreadCount()).isZero(); + } + + // ---- fail closed: no company and not a super admin must never mean "all companies" + + @Test + void nonAdminWithoutCompanyIsDeniedEverywhere() { + leadOf(1L, "+60111222333"); + WaConversation c = conv(5, 1L, STAFF); + given(c); + + assertThat(service.list(null, STAFF, false, "all", null, 0, 30).items()).isEmpty(); + assertThat(service.list(null, STAFF, false, "mine", null, 0, 30).items()).isEmpty(); + assertThat(service.unreadCount(null, STAFF, false).count()).isZero(); + assertNotFound(() -> service.thread("u-5", null, STAFF, false, null)); + assertNotFound(() -> service.markRead("u-5", null, STAFF, false)); + assertNotFound(() -> service.start(null, STAFF, false, new StartChatRequest(77L, null))); + + verify(conversations, never()).list(any(), any(), anyBoolean(), any(), any(), any()); + verify(messages, never()).unreadConversations(any(), any(), anyLong()); + verify(reads, never()).markRead(anyLong(), anyLong(), anyLong()); + verifyNoInteractions(rest); + verify(conversations, never()).save(any()); + verify(conversations, never()).claimIfUnowned(anyLong(), any(), any()); + } + + @Test + void httpNonAdminWithoutCompanyIsDenied() throws Exception { + mvc.perform(get("/whatsapp/conversations").param("userId", "10").param("admin", "false")) + .andExpect(status().isOk()).andExpect(jsonPath("$.items").isEmpty()); + mvc.perform(get("/whatsapp/unreadCount").param("userId", "10").param("admin", "false")) + .andExpect(status().isOk()).andExpect(jsonPath("$.count").value(0)); + mvc.perform(post("/whatsapp/conversations/start").param("userId", "10").param("admin", "false") + .contentType("application/json").content("{\"leadUuid\":77}")) + .andExpect(status().isNotFound()); + } + + @Test + void startForALeadWithoutMobileOrWithoutLeadIs404() { + target = null; + assertThatThrownBy(() -> service.start(1L, STAFF, false, new StartChatRequest(77L, null))) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + verify(conversations, never()).save(any()); + } + + @Test + void startForALeadOfAnotherCompanyIs404() { + leadOf(2L, "+60111222333"); + + assertThatThrownBy(() -> service.start(1L, STAFF, false, new StartChatRequest(77L, null))) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + verify(conversations, never()).save(any()); + } + + @Test + void superAdminStartUsesTheCompanyOfTheLead() { + leadOf(2L, "+60111222333"); + when(directory.phoneNumberIdOf(2L)).thenReturn(Optional.of("222")); + when(conversations.findByCompanyIdAndContactWaId(2L, "60111222333")).thenReturn(Optional.empty()); + + ConversationView view = service.start(null, STAFF, true, new StartChatRequest(77L, null)); + + assertThat(view.companyId()).isEqualTo(2L); + verify(rest).getForObject(eq(URI.create("http://service-counter/counter/lead/whatsappTarget?leadUuid=77")), eq(WhatsappTarget.class)); + } + + @Test + void startWithoutConfiguredWhatsAppForTheCompanyIs409() { + leadOf(1L, "+60111222333"); + when(directory.phoneNumberIdOf(1L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.start(1L, STAFF, false, new StartChatRequest(77L, null))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getReason()).isEqualTo("WHATSAPP_NOT_CONFIGURED"); + }); + verify(conversations, never()).save(any()); + } + + @Test + void startAsksTheCounterByLeadOrEventLeadAndScopesToTheCompany() { + leadOf(1L, "+60111222333"); + when(conversations.findByCompanyIdAndContactWaId(any(), any())).thenReturn(Optional.empty()); + + service.start(1L, STAFF, false, new StartChatRequest(77L, null)); + service.start(1L, STAFF, false, new StartChatRequest(null, 500L)); + + verify(rest).getForObject(eq(URI.create("http://service-counter/counter/lead/whatsappTarget?companyId=1&leadUuid=77")), eq(WhatsappTarget.class)); + verify(rest).getForObject(eq(URI.create("http://service-counter/counter/lead/whatsappTarget?companyId=1&eventLeadUuid=500")), eq(WhatsappTarget.class)); + } + + @Test + void startWithCounterDownIs503AndEmptyBodyIs400() { + counterDown = true; + assertThatThrownBy(() -> service.start(1L, STAFF, false, new StartChatRequest(77L, null))) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE)); + assertThatThrownBy(() -> service.start(1L, STAFF, false, new StartChatRequest(null, null))) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST)); + } + + // ---- HTTP + + @Test + void httpListReadAndStart() throws Exception { + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of(conv(1, 1L, STAFF)))); + mvc.perform(get("/whatsapp/conversations").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isOk()).andExpect(jsonPath("$.items[0].uuid").value("u-1")).andExpect(jsonPath("$.size").value(30)); + + given(conv(5, 1L, STAFF)); + mvc.perform(post("/whatsapp/conversations/u-5/read").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isNoContent()); + given(conv(6, 1L, 11L)); + mvc.perform(post("/whatsapp/conversations/u-6/read").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isNotFound()).andExpect(jsonPath("$.detail").value("CONVERSATION_NOT_FOUND")); + + when(messages.unreadConversations(any(), any(), anyLong())).thenReturn(2L); + mvc.perform(get("/whatsapp/unreadCount").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isOk()).andExpect(jsonPath("$.count").value(2)); + + leadOf(1L, "+60111222333"); + when(directory.phoneNumberIdOf(1L)).thenReturn(Optional.empty()); + mvc.perform(post("/whatsapp/conversations/start").param("companyId", "1").param("userId", "10").param("admin", "false") + .contentType("application/json").content("{\"leadUuid\":77}")) + .andExpect(status().isConflict()).andExpect(jsonPath("$.detail").value("WHATSAPP_NOT_CONFIGURED")); + } +} -- 2.54.1 From 9f1b8de04da2f2155cd1e8a02ac988c2b65577ce Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 09:19:55 +0800 Subject: [PATCH 12/23] feat: whatsapp send, templates and media proxy - MetaClient: text and template sends, approved templates with bounded paging, streamed media with a 100 MB cap. - Send endpoint: 24-hour window, template params and supported checks before Meta; pending then sent or failed with Meta's code and title. - Template sync per company and nightly at 03:30 KL; a failed fetch keeps existing rows. - Media proxy: 404 without access, 410 when Meta no longer holds the file. - Mock: Graph send, templates, media and bearer checks; /simulate/inbound and /simulate/status sign with the company secret. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- local/docker-compose.yml | 11 + local/whatsapp-mock/server.js | 128 +++++++- .../services/whatsapp/inbox/InboxService.java | 4 +- .../whatsapp/inbox/OutboundController.java | 68 ++++ .../whatsapp/inbox/OutboundService.java | 185 +++++++++++ .../whatsapp/inbox/TemplateService.java | 187 +++++++++++ .../services/whatsapp/meta/MetaClient.java | 210 ++++++++++++ .../repository/WaConversationRepository.java | 8 + .../repository/WaTemplateRepository.java | 17 +- .../whatsapp/service/CompanyDirectory.java | 15 + .../services/whatsapp/inbox/OutboundTest.java | 310 ++++++++++++++++++ .../whatsapp/inbox/TemplateServiceTest.java | 175 ++++++++++ .../whatsapp/meta/MetaClientTest.java | 263 +++++++++++++++ 13 files changed, 1570 insertions(+), 11 deletions(-) create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundController.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundService.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/TemplateService.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/meta/MetaClient.java create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/OutboundTest.java create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/TemplateServiceTest.java create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/meta/MetaClientTest.java diff --git a/local/docker-compose.yml b/local/docker-compose.yml index 276e4f3..1afc8ac 100644 --- a/local/docker-compose.yml +++ b/local/docker-compose.yml @@ -121,5 +121,16 @@ services: mysql: {condition: service_healthy} whatsapp-mock: build: ./whatsapp-mock + environment: + WEBHOOK_URL: http://mobile-api/api/public/whatsapp/webhook + WHATSAPP_COMPANIES: ${WHATSAPP_COMPANIES} + WHATSAPP_INS_PHONE_NUMBER_ID: ${WHATSAPP_INS_PHONE_NUMBER_ID} + WHATSAPP_INS_WABA_ID: ${WHATSAPP_INS_WABA_ID} + WHATSAPP_INS_ACCESS_TOKEN: ${WHATSAPP_INS_ACCESS_TOKEN} + WHATSAPP_INS_APP_SECRET: ${WHATSAPP_INS_APP_SECRET} + WHATSAPP_CV_PHONE_NUMBER_ID: ${WHATSAPP_CV_PHONE_NUMBER_ID} + WHATSAPP_CV_WABA_ID: ${WHATSAPP_CV_WABA_ID} + WHATSAPP_CV_ACCESS_TOKEN: ${WHATSAPP_CV_ACCESS_TOKEN} + WHATSAPP_CV_APP_SECRET: ${WHATSAPP_CV_APP_SECRET} volumes: mysql-data: diff --git a/local/whatsapp-mock/server.js b/local/whatsapp-mock/server.js index fa93adf..3ccf27e 100644 --- a/local/whatsapp-mock/server.js +++ b/local/whatsapp-mock/server.js @@ -1,11 +1,123 @@ -// Local stand-in for the WhatsApp Cloud (Graph) API. Later tasks add Graph endpoints and signed webhooks. +// Local stand-in for the WhatsApp Cloud (Graph) API and for Meta's signed webhook. Never part of release packaging. +// Env: PORT (8080), WEBHOOK_URL, WHATSAPP_COMPANIES=INS,CV and per company WHATSAPP__PHONE_NUMBER_ID / _WABA_ID / _ACCESS_TOKEN / _APP_SECRET. const http = require('node:http'); +const crypto = require('node:crypto'); -http.createServer((req, res) => { - if (req.method === 'GET' && req.url === '/health') { - res.writeHead(200, { 'Content-Type': 'application/json' }); - return res.end('{"status":"UP"}'); +const env = process.env; +const companies = (env.WHATSAPP_COMPANIES || '').split(',').map((s) => s.trim()).filter(Boolean).map((code) => ({ + code, + phoneNumberId: env[`WHATSAPP_${code}_PHONE_NUMBER_ID`], + wabaId: env[`WHATSAPP_${code}_WABA_ID`], + token: env[`WHATSAPP_${code}_ACCESS_TOKEN`], + secret: env[`WHATSAPP_${code}_APP_SECRET`], +})); +const tokens = new Set(companies.map((c) => c.token).filter(Boolean)); + +const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64'); +const PDF = Buffer.from('%PDF-1.1\n1 0 obj<>endobj\n2 0 obj<>endobj\n' + + '3 0 obj<>endobj\ntrailer<>\n%%EOF\n'); + +let counter = 0; + +function send(res, status, body, type = 'application/json') { + res.writeHead(status, { 'Content-Type': type }); + res.end(Buffer.isBuffer(body) || typeof body === 'string' ? body : JSON.stringify(body)); +} + +function readBody(req) { + return new Promise((resolve) => { + const chunks = []; + req.on('data', (c) => chunks.push(c)); + req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); + }); +} + +function templates(wabaId, host, page) { + const expo = { name: 'expo_followup', language: 'en', category: 'MARKETING', status: 'APPROVED', + components: [{ type: 'BODY', text: 'Hi {{1}}, thanks for visiting us at {{2}}.' }] }; + const promo = { name: 'promo_header', language: 'en', category: 'MARKETING', status: 'APPROVED', + components: [{ type: 'HEADER', format: 'IMAGE' }, { type: 'BODY', text: 'Big sale this weekend.' }] }; + return page === 'p2' + ? { data: [promo], paging: {} } + : { data: [expo], paging: { next: `http://${host}/${wabaId}/message_templates?status=APPROVED&limit=200&after=p2` } }; +} + +// Delivers a signed webhook the way Meta does: HMAC-SHA256 over the exact bytes, header "sha256=". +async function deliver(company, payload) { + const body = JSON.stringify(payload); + const signature = 'sha256=' + crypto.createHmac('sha256', company.secret).update(body).digest('hex'); + const r = await fetch(env.WEBHOOK_URL, { method: 'POST', body, headers: { 'Content-Type': 'application/json', 'X-Hub-Signature-256': signature } }); + return r.status; +} + +function envelope(company, value) { + return { object: 'whatsapp_business_account', entry: [{ id: company.wabaId, changes: [{ field: 'messages', + value: { messaging_product: 'whatsapp', metadata: { display_phone_number: '15550000000', phone_number_id: company.phoneNumberId }, ...value } }] }] }; +} + +async function simulate(path, req, res) { + let input; + try { + input = JSON.parse(await readBody(req)); + } catch (e) { + return send(res, 400, { error: 'invalid json' }); } - res.writeHead(404, { 'Content-Type': 'application/json' }); - res.end('{"error":"not found"}'); -}).listen(8080); + const company = companies.find((c) => c.code === input.companyCode); + if (!company || !env.WEBHOOK_URL) return send(res, 400, { error: 'unknown companyCode or WEBHOOK_URL not set' }); + const now = Math.floor(Date.now() / 1000); + let payload; + if (path === '/simulate/status') { + payload = envelope(company, { statuses: [{ id: input.wamid, status: input.status, timestamp: String(now), recipient_id: input.from || '60100000000' }] }); + } else { + const type = input.type || 'text'; + const message = { from: input.from, id: `wamid.MOCKIN${++counter}`, timestamp: String(now), type }; + if (type === 'text') message.text = { body: input.text || 'hello' }; + else if (type === 'location') message.location = { latitude: 3.139, longitude: 101.6869, name: 'Mock Location' }; + else if (type === 'document') message.document = { id: input.mediaId, mime_type: 'application/pdf', filename: 'quote.pdf' }; + else message[type] = { id: input.mediaId, mime_type: 'image/png' }; + payload = envelope(company, { contacts: [{ profile: { name: 'Mock Contact' }, wa_id: input.from }], messages: [message] }); + } + try { + send(res, await deliver(company, payload), { delivered: true }); + } catch (e) { + send(res, 502, { error: 'webhook unreachable' }); + } +} + +http.createServer(async (req, res) => { + const url = new URL(req.url, 'http://mock'); + const path = url.pathname.replace(/^\/v\d+\.\d+/, ''); // the client may add a Graph version prefix + if (req.method === 'GET' && path === '/health') return send(res, 200, { status: 'UP' }); + if (req.method === 'POST' && (path === '/simulate/inbound' || path === '/simulate/status')) return simulate(path, req, res); + + const auth = /^Bearer (.+)$/.exec(req.headers.authorization || ''); + if (!auth || !tokens.has(auth[1])) return send(res, 401, { error: { code: 190, title: 'Invalid OAuth access token' } }); + + // media bytes: Meta wants the bearer token on the download too + const bytes = path.match(/^\/media-bytes\/([^/]+)$/); + if (req.method === 'GET' && bytes) { + const id = bytes[1]; + if (id.startsWith('expired')) return send(res, 404, { error: { code: 100, title: 'Media expired' } }); + return id.startsWith('doc') ? send(res, 200, PDF, 'application/pdf') : send(res, 200, PNG, 'image/png'); + } + + const parts = path.split('/').filter(Boolean); + if (req.method === 'POST' && parts.length === 2 && parts[1] === 'messages') { + let input; + try { + input = JSON.parse(await readBody(req)); + } catch (e) { + return send(res, 400, { error: { code: 100, title: 'Invalid parameter' } }); + } + if (String(input.to || '').endsWith('0000')) return send(res, 400, { error: { code: 131026, title: 'Message undeliverable' } }); + return send(res, 200, { messaging_product: 'whatsapp', messages: [{ id: `wamid.MOCK${++counter}` }] }); + } + if (req.method === 'GET' && parts.length === 2 && parts[1] === 'message_templates') { + return send(res, 200, templates(parts[0], req.headers.host, url.searchParams.get('after'))); + } + if (req.method === 'GET' && parts.length === 1) { // media lookup + const id = parts[0]; + return send(res, 200, { id, url: `http://whatsapp-mock:8080/media-bytes/${id}`, mime_type: id.startsWith('doc') ? 'application/pdf' : 'image/png' }); + } + send(res, 404, { error: { code: 100, title: 'Unknown path' } }); +}).listen(Number(env.PORT || 8080)); diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java index 163e967..31a64ba 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java @@ -217,7 +217,7 @@ public class InboxService { return companyId == null && !admin; } - private WaConversation visible(String uuid, Long companyId, Long userId, boolean admin) { + WaConversation visible(String uuid, Long companyId, Long userId, boolean admin) { if (failClosed(companyId, admin)) { throw notFound(); } @@ -258,7 +258,7 @@ public class InboxService { c.ownerManual, c.lastInboundAt, c.lastMessageAt, withPreview ? c.lastMessagePreview : null, open, unread); } - private static MessageView message(WaMessage m) { + static MessageView message(WaMessage m) { return new MessageView(m.uuid, m.direction, m.type, m.body, m.templateName, m.mediaMime, m.mediaFilename, m.locationLat, m.locationLng, m.locationName, m.status, m.errorCode, m.errorTitle, m.sentByUserId, m.createdAt, m.statusAt); } diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundController.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundController.java new file mode 100644 index 0000000..1f746e7 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundController.java @@ -0,0 +1,68 @@ +package com.solvway.services.whatsapp.inbox; + +import com.solvway.services.whatsapp.dto.MessageView; +import com.solvway.services.whatsapp.dto.SendMessageRequest; +import com.solvway.services.whatsapp.dto.TemplateView; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** Sending, templates and media. Caller context arrives as trusted query params from mobile-api, like {@link InboxController}. */ +@RestController +@RequestMapping("/whatsapp") +public class OutboundController { + + private final OutboundService service; + private final TemplateService templates; + + public OutboundController(OutboundService service, TemplateService templates) { + this.service = service; + this.templates = templates; + } + + @PostMapping("/conversations/{uuid}/messages") + public MessageView send(@PathVariable String uuid, @RequestParam(required = false) Long companyId, @RequestParam Long userId, + @RequestParam boolean admin, @RequestBody SendMessageRequest request) { + return service.send(uuid, companyId, userId, admin, request); + } + + @GetMapping("/templates") + public List templates(@RequestParam(required = false) Long companyId) { + return templates.list(companyId); + } + + @PostMapping("/templates/sync") + public List sync(@RequestParam(required = false) Long companyId, @RequestParam boolean admin) { + return templates.sync(companyId, admin); + } + + /** Streams straight from Meta into the response; errors are decided before the first byte so they still get a ProblemDetail. */ + @GetMapping("/media/{messageUuid}") + public void media(@PathVariable String messageUuid, @RequestParam(required = false) Long companyId, @RequestParam Long userId, + @RequestParam boolean admin, HttpServletResponse response) { + service.media(messageUuid, companyId, userId, admin, (mime, disposition, length) -> { + MediaType type; + try { + type = mime == null ? MediaType.APPLICATION_OCTET_STREAM : MediaType.parseMediaType(mime); + } catch (IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM; + } + response.setContentType(type.toString()); + response.setHeader(HttpHeaders.CONTENT_DISPOSITION, disposition); + response.setHeader("X-Content-Type-Options", "nosniff"); + if (length >= 0) { + response.setContentLengthLong(length); + } + return response.getOutputStream(); + }); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundService.java new file mode 100644 index 0000000..e45ef99 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundService.java @@ -0,0 +1,185 @@ +package com.solvway.services.whatsapp.inbox; + +import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig; +import com.solvway.services.whatsapp.dto.MessageView; +import com.solvway.services.whatsapp.dto.SendMessageRequest; +import com.solvway.services.whatsapp.meta.MetaClient; +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.model.WaMessage; +import com.solvway.services.whatsapp.model.WaTemplate; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import com.solvway.services.whatsapp.repository.WaMessageRepository; +import com.solvway.services.whatsapp.repository.WaTemplateRepository; +import com.solvway.services.whatsapp.service.CompanyDirectory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +import java.time.Clock; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Sends text (inside the 24-hour window) and templates, and proxies media. The Meta call runs outside any transaction. + * Never logs numbers, message text or tokens. + * ponytail: a delivery webhook that arrives before the wamid is saved is ignored (rare); the message then stays "sent". + */ +@Service +public class OutboundService { + + private static final int TEXT_MAX = 4096; + private static final int PREVIEW_MAX = 80; + private static final Pattern PARAM = Pattern.compile("\\{\\{(\\d+)}}"); + private static final Set MEDIA_TYPES = Set.of("image", "sticker", "document", "audio", "video"); + private static final Set INLINE_MIMES = Set.of("image/jpeg", "image/png", "image/webp", "image/gif"); + + /** Where the proxied bytes go: called once with the final headers, before any byte is written. */ + @FunctionalInterface + public interface MediaOutput { + java.io.OutputStream open(String mime, String disposition, long length) throws java.io.IOException; + } + + private final InboxService inbox; + private final WaConversationRepository conversations; + private final WaMessageRepository messages; + private final WaTemplateRepository templates; + private final CompanyDirectory companies; + private final MetaClient meta; + private final Clock clock; + + @Autowired + public OutboundService(InboxService inbox, WaConversationRepository conversations, WaMessageRepository messages, + WaTemplateRepository templates, CompanyDirectory companies, MetaClient meta) { + this(inbox, conversations, messages, templates, companies, meta, Clock.systemDefaultZone()); + } + + OutboundService(InboxService inbox, WaConversationRepository conversations, WaMessageRepository messages, + WaTemplateRepository templates, CompanyDirectory companies, MetaClient meta, Clock clock) { + this.inbox = inbox; + this.conversations = conversations; + this.messages = messages; + this.templates = templates; + this.companies = companies; + this.meta = meta; + this.clock = clock; + } + + public MessageView send(String uuid, Long companyId, Long userId, boolean admin, SendMessageRequest request) { + WaConversation c = inbox.visible(uuid, companyId, userId, admin); + boolean isText = request != null && request.text() != null; + boolean isTemplate = request != null && request.template() != null; + if (isText == isTemplate || (isText && (request.text().isBlank() || request.text().length() > TEXT_MAX)) + || (isTemplate && (request.template().isBlank() || request.language() == null || request.language().isBlank()))) { + throw bad("INVALID_PAYLOAD"); + } + CompanyConfig cfg = companies.configOf(c.companyId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED")); + LocalDateTime now = LocalDateTime.now(clock); + + String type; + String body; + String templateName = null; + List params = null; + if (isText) { + if (c.lastInboundAt == null || !c.lastInboundAt.isAfter(now.minusHours(24))) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "WINDOW_CLOSED"); + } + type = "text"; + body = request.text(); + } else { + WaTemplate t = templates.findByCompanyIdAndNameAndLanguage(c.companyId, request.template(), request.language()) + .filter(x -> TemplateService.APPROVED.equals(x.status)).orElseThrow(() -> bad("TEMPLATE_PARAMS")); + params = request.params() == null ? List.of() : request.params(); + if (params.size() != t.paramCount || params.stream().anyMatch(p -> p == null || p.isBlank())) { + throw bad("TEMPLATE_PARAMS"); + } + type = "template"; + templateName = t.name; + body = fill(t.bodyText, params); + } + + WaMessage m = new WaMessage(); + m.uuid = UUID.randomUUID().toString(); + m.conversationId = c.id; + m.direction = "OUT"; + m.type = type; + m.body = body; + m.templateName = templateName; + m.status = "pending"; + m.sentByUserId = userId; + m.createdAt = now; + m = messages.save(m); + + MetaClient.SendResult r = isText ? meta.sendText(cfg, c.contactWaId, body) + : meta.sendTemplate(cfg, c.contactWaId, templateName, request.language(), params); + m.statusAt = LocalDateTime.now(clock); + if (r.failed()) { + m.status = "failed"; + m.errorCode = r.errorCode(); + m.errorTitle = r.errorTitle(); + } else { + m.status = "sent"; + m.wamid = r.wamid(); + } + m = messages.save(m); + conversations.recordOutbound(c.id, m.createdAt, preview(body)); + return InboxService.message(m); + } + + /** + * Streams a media message's bytes from Meta (404 when not visible or not media, 410 when Meta no longer has it). + * ponytail: Meta keeps media about 30 days and every view re-fetches it; upgrade by copying to object storage on receipt. + */ + public void media(String messageUuid, Long companyId, Long userId, boolean admin, MediaOutput output) { + WaMessage m = messages.findByUuid(messageUuid).orElseThrow(OutboundService::mediaNotFound); + WaConversation c = conversations.findById(m.conversationId).orElseThrow(OutboundService::mediaNotFound); + inbox.visible(c.uuid, companyId, userId, admin); + if (m.mediaId == null || !MEDIA_TYPES.contains(m.type)) { + throw mediaNotFound(); + } + CompanyConfig cfg = companies.configOf(c.companyId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED")); + try { + meta.media(cfg, m.mediaId, (upstreamMime, length) -> { + String mime = m.mediaMime != null ? m.mediaMime : upstreamMime; + // Only plain raster images render inline; anything else (SVG, HTML, PDF...) downloads, so media can never run script here. + boolean inline = ("image".equals(m.type) || "sticker".equals(m.type)) && mime != null && INLINE_MIMES.contains(mime.toLowerCase()); + String disposition = inline ? "inline" + : m.mediaFilename == null ? "attachment" : ContentDisposition.attachment().filename(m.mediaFilename).build().toString(); + return output.open(mime, disposition, length); + }); + } catch (MetaClient.MediaExpiredException e) { + throw new ResponseStatusException(HttpStatus.GONE, "MEDIA_EXPIRED"); + } catch (MetaClient.MetaException e) { + throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "META_UNAVAILABLE"); + } + } + + private static String fill(String template, List params) { + Matcher m = PARAM.matcher(template == null ? "" : template); + StringBuilder out = new StringBuilder(); + while (m.find()) { // one pass over the template, so a parameter that contains {{2}} is not substituted again + int i = Integer.parseInt(m.group(1)); + m.appendReplacement(out, Matcher.quoteReplacement(i >= 1 && i <= params.size() ? params.get(i - 1) : m.group())); + } + return m.appendTail(out).toString(); + } + + private static String preview(String text) { + return text.codePointCount(0, text.length()) <= PREVIEW_MAX ? text : text.substring(0, text.offsetByCodePoints(0, PREVIEW_MAX)); + } + + private static ResponseStatusException bad(String reason) { + return new ResponseStatusException(HttpStatus.BAD_REQUEST, reason); + } + + private static ResponseStatusException mediaNotFound() { + return new ResponseStatusException(HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND"); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/TemplateService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/TemplateService.java new file mode 100644 index 0000000..6eb2360 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/TemplateService.java @@ -0,0 +1,187 @@ +package com.solvway.services.whatsapp.inbox; + +import com.fasterxml.jackson.databind.JsonNode; +import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig; +import com.solvway.services.whatsapp.dto.TemplateView; +import com.solvway.services.whatsapp.meta.MetaClient; +import com.solvway.services.whatsapp.model.WaTemplate; +import com.solvway.services.whatsapp.repository.WaTemplateRepository; +import com.solvway.services.whatsapp.service.CompanyDirectory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.server.ResponseStatusException; + +import java.time.Clock; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Template list and sync from Meta. A template this app cannot fill in (media or parameterised header, parameterised or + * copy-code buttons, named parameters) is stored with status UNSUPPORTED so it shows but cannot be sent; supported ones + * keep status APPROVED (the sync only asks Meta for approved templates). + */ +@Service +public class TemplateService { + + private static final Logger log = LoggerFactory.getLogger(TemplateService.class); + private static final Pattern PARAM = Pattern.compile("\\{\\{(\\d+)}}"); + private static final Set BUTTONS_OK = Set.of("QUICK_REPLY", "PHONE_NUMBER", "URL"); + + static final String APPROVED = "APPROVED"; + static final String UNSUPPORTED = "UNSUPPORTED"; + + private final WaTemplateRepository templates; + private final CompanyDirectory companies; + private final MetaClient meta; + private final TransactionTemplate tx; + private final Clock clock; + + @Autowired + public TemplateService(WaTemplateRepository templates, CompanyDirectory companies, MetaClient meta, TransactionTemplate tx) { + this(templates, companies, meta, tx, Clock.systemDefaultZone()); + } + + TemplateService(WaTemplateRepository templates, CompanyDirectory companies, MetaClient meta, TransactionTemplate tx, Clock clock) { + this.templates = templates; + this.companies = companies; + this.meta = meta; + this.tx = tx; + this.clock = clock; + } + + /** ponytail: no company means no list (a super admin picks a company); upgrade to a merged list if needed. */ + public List list(Long companyId) { + if (companyId == null) { + return List.of(); + } + return templates.findByCompanyIdOrderByNameAsc(companyId).stream().map(TemplateService::view).toList(); + } + + /** Admin only (404 otherwise). A super admin without a company syncs every configured company; one failure does not stop the rest. */ + public List sync(Long companyId, boolean admin) { + if (!admin) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "NOT_FOUND"); + } + if (companyId == null) { + syncAll(); + return List.of(); + } + CompanyConfig cfg = companies.configOf(companyId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED")); + return syncOne(companyId, cfg).stream().map(TemplateService::view).toList(); + } + + @Scheduled(cron = "${whatsapp.templates.cron:0 30 3 * * *}", zone = "Asia/Kuala_Lumpur") + public void nightly() { + syncAll(); + } + + private void syncAll() { + for (Map.Entry e : companies.configured().entrySet()) { + try { + syncOne(e.getKey(), e.getValue()); + } catch (RuntimeException ex) { // per company: log the id and exception type only + log.warn("WhatsApp template sync failed for company {}: {}", e.getKey(), ex.getClass().getSimpleName()); + } + } + } + + /** Fetch first, so a Meta failure leaves the existing rows alone; then replace them atomically. */ + private List syncOne(long companyId, CompanyConfig cfg) { + List fetched; + try { + fetched = meta.templates(cfg); + } catch (MetaClient.MetaException e) { + throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "META_UNAVAILABLE"); + } + LocalDateTime now = LocalDateTime.now(clock); + List rows = new ArrayList<>(); + Set seen = new HashSet<>(); + for (JsonNode t : fetched) { + String name = t.path("name").asText(""); + String language = t.path("language").asText(""); + if (name.isEmpty() || language.isEmpty() || !seen.add(name + "\0" + language)) { + continue; + } + String body = bodyText(t); + WaTemplate row = new WaTemplate(); + row.companyId = companyId; + row.name = name; + row.language = language; + row.category = t.path("category").asText(null); + row.status = supported(t) ? APPROVED : UNSUPPORTED; + row.bodyText = body; + row.paramCount = paramCount(body); + row.syncedAt = now; + rows.add(row); + } + tx.executeWithoutResult(s -> { + templates.deleteByCompanyId(companyId); + templates.saveAll(rows); + }); + return rows; + } + + /** The one place that decides whether this app can fill a template in: body-only parameters, plain header and buttons. */ + static boolean supported(JsonNode template) { + if ("NAMED".equals(template.path("parameter_format").asText())) { + return false; + } + for (JsonNode c : template.path("components")) { + switch (c.path("type").asText()) { + case "BODY", "FOOTER" -> { } + case "HEADER" -> { + if (!"TEXT".equals(c.path("format").asText()) || c.path("text").asText("").contains("{{")) { + return false; + } + } + case "BUTTONS" -> { + for (JsonNode b : c.path("buttons")) { + if (!BUTTONS_OK.contains(b.path("type").asText()) || b.path("url").asText("").contains("{{")) { + return false; + } + } + } + default -> { + return false; + } + } + } + return true; + } + + private static String bodyText(JsonNode template) { + for (JsonNode c : template.path("components")) { + if ("BODY".equals(c.path("type").asText())) { + return c.path("text").asText(null); + } + } + return null; + } + + static int paramCount(String body) { + Set distinct = new HashSet<>(); + if (body != null) { + Matcher m = PARAM.matcher(body); + while (m.find()) { + distinct.add(m.group(1)); + } + } + return distinct.size(); + } + + private static TemplateView view(WaTemplate t) { + return new TemplateView(t.name, t.language, t.category, t.bodyText, t.paramCount, APPROVED.equals(t.status)); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/meta/MetaClient.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/meta/MetaClient.java new file mode 100644 index 0000000..26b880e --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/meta/MetaClient.java @@ -0,0 +1,210 @@ +package com.solvway.services.whatsapp.meta; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.solvway.services.whatsapp.config.WhatsAppSettings; +import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +/** + * Meta WhatsApp Cloud (Graph) API client. Never logs tokens, URLs, message text or numbers; failures surface as codes only. + * ponytail: the media and paging URLs Meta returns get the bearer token as returned; no host allow-list. + */ +@Component +public class MetaClient { + + /** wamid on success; otherwise Meta's error code and title (code NETWORK when Meta was not reached). */ + public record SendResult(String wamid, String errorCode, String errorTitle) { + public boolean failed() { + return wamid == null; + } + } + + /** Receives the upstream's mime type and length (-1 unknown) once, before the first byte, and returns where to write. */ + @FunctionalInterface + public interface MediaSink { + OutputStream open(String mime, long length) throws IOException; + } + + public static class MediaExpiredException extends RuntimeException { + public MediaExpiredException() { + super("MEDIA_EXPIRED"); + } + } + + /** A Graph call that failed; the message is only the error code, never a body. */ + public static class MetaException extends RuntimeException { + public MetaException(String code) { + super(code); + } + } + + private static final JsonNodeFactory JSON = JsonNodeFactory.instance; + private static final int MAX_PAGES = 50; + /** ponytail: fixed 100 MB ceiling on one proxied media file (WhatsApp's own limit is 100 MB for documents); make it a setting if that changes. */ + static final long MAX_MEDIA_BYTES = 100L * 1024 * 1024; + + long maxMediaBytes = MAX_MEDIA_BYTES; // not final so a test can use a small cap + + private final WhatsAppSettings settings; + private final RestTemplate rest; + + @Autowired + public MetaClient(WhatsAppSettings settings, RestTemplateBuilder builder) { + this(settings, builder.setConnectTimeout(Duration.ofSeconds(10)).setReadTimeout(Duration.ofSeconds(10)).build()); + } + + MetaClient(WhatsAppSettings settings, RestTemplate rest) { + this.settings = settings; + this.rest = rest; + } + + public SendResult sendText(CompanyConfig cfg, String to, String body) { + ObjectNode payload = payload(to, "text"); + payload.putObject("text").put("body", body); + return send(cfg, payload); + } + + public SendResult sendTemplate(CompanyConfig cfg, String to, String name, String language, List params) { + ObjectNode payload = payload(to, "template"); + ObjectNode template = payload.putObject("template"); + template.put("name", name); + template.putObject("language").put("code", language); + if (!params.isEmpty()) { + ArrayNode parameters = template.putArray("components").addObject().put("type", "body").putArray("parameters"); + params.forEach(p -> parameters.addObject().put("type", "text").put("text", p)); + } + return send(cfg, payload); + } + + /** Every approved template of the business account, following paging.next. Throws MetaException. */ + public List templates(CompanyConfig cfg) { + List all = new ArrayList<>(); + URI next = URI.create(settings.graphBaseUrl() + "/" + cfg.wabaId() + "/message_templates?status=APPROVED&limit=200"); + for (int pages = 0; next != null; pages++) { + if (pages == MAX_PAGES) { // fail rather than return a truncated list: sync would delete the missing templates + throw new MetaException("PAGING"); + } + JsonNode page = get(cfg, next, JsonNode.class); + JsonNode data = page.path("data"); + data.forEach(all::add); + String link = page.path("paging").path("next").asText(""); + // a repeated link or an empty page means Meta is not advancing: stop instead of looping + next = link.isEmpty() || data.isEmpty() || link.equals(next.toString()) ? null : URI.create(link); + } + return all; + } + + /** + * Short-lived URL lookup, then streams the bytes into the sink (never held whole in memory). The sink opens only after + * Meta answered with success and a length within the cap, so 404/410 and refusals happen before anything is written. + * Throws MediaExpiredException (Meta 404/410) or MetaException. + */ + public void media(CompanyConfig cfg, String mediaId, MediaSink sink) { + try { + JsonNode info = rest.exchange(settings.graphBaseUrl() + "/{id}", HttpMethod.GET, auth(cfg), JsonNode.class, mediaId).getBody(); + if (info == null || !info.hasNonNull("url")) { + throw new MetaException("NO_URL"); + } + String mime = info.path("mime_type").asText(null); + rest.execute(URI.create(info.get("url").asText()), HttpMethod.GET, request -> request.getHeaders().setBearerAuth(cfg.accessToken()), response -> { + long length = response.getHeaders().getContentLength(); + if (length > maxMediaBytes) { + throw new MetaException("TOO_LARGE"); + } + try (InputStream in = response.getBody(); OutputStream out = sink.open(mime, length)) { + byte[] buffer = new byte[8192]; + long total = 0; + for (int n; (n = in.read(buffer)) != -1; ) { + total += n; + if (total > maxMediaBytes) { + throw new MetaException("TOO_LARGE"); + } + out.write(buffer, 0, n); + } + } + return null; + }); + } catch (HttpStatusCodeException e) { + HttpStatusCode code = e.getStatusCode(); + if (code.isSameCodeAs(HttpStatus.NOT_FOUND) || code.isSameCodeAs(HttpStatus.GONE)) { + throw new MediaExpiredException(); + } + throw new MetaException(String.valueOf(code.value())); + } catch (RestClientException e) { + throw new MetaException("NETWORK"); + } + } + + private SendResult send(CompanyConfig cfg, ObjectNode payload) { + HttpHeaders headers = new HttpHeaders(); + headers.setBearerAuth(cfg.accessToken()); + try { + JsonNode r = rest.exchange(settings.graphBaseUrl() + "/{id}/messages", HttpMethod.POST, new HttpEntity<>(payload, headers), + JsonNode.class, cfg.phoneNumberId()).getBody(); + String wamid = r == null ? "" : r.path("messages").path(0).path("id").asText(""); + return wamid.isEmpty() ? new SendResult(null, "NO_WAMID", null) : new SendResult(wamid, null, null); + } catch (HttpStatusCodeException e) { + JsonNode error = parse(e); + String title = error.path("title").asText(error.path("message").asText("")); + return new SendResult(null, cut(error.path("code").asText(String.valueOf(e.getStatusCode().value())), 32), + title.isEmpty() ? null : cut(title, 255)); + } catch (RestClientException e) { + return new SendResult(null, "NETWORK", null); + } + } + + private T get(CompanyConfig cfg, URI uri, Class type) { + try { + return rest.exchange(uri, HttpMethod.GET, auth(cfg), type).getBody(); + } catch (HttpStatusCodeException e) { + throw new MetaException(cut(parse(e).path("code").asText(String.valueOf(e.getStatusCode().value())), 32)); + } catch (RestClientException e) { + throw new MetaException("NETWORK"); + } + } + + private static JsonNode parse(HttpStatusCodeException e) { + try { + return new com.fasterxml.jackson.databind.ObjectMapper().readTree(e.getResponseBodyAsString()).path("error"); + } catch (Exception ignored) { // not JSON: fall back to the HTTP status + return JSON.missingNode(); + } + } + + private static ObjectNode payload(String to, String type) { + ObjectNode payload = JSON.objectNode(); + payload.put("messaging_product", "whatsapp").put("to", to).put("type", type); + return payload; + } + + private static HttpEntity auth(CompanyConfig cfg) { + HttpHeaders headers = new HttpHeaders(); + headers.setBearerAuth(cfg.accessToken()); + return new HttpEntity<>(headers); + } + + private static String cut(String s, int max) { + return s.length() <= max ? s : s.substring(0, max); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java index 3283aac..fc728f0 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java @@ -31,6 +31,14 @@ public interface WaConversationRepository extends JpaRepository= last_message_at THEN :preview ELSE last_message_preview END, " + + "last_message_at = GREATEST(COALESCE(last_message_at, :at), :at) WHERE id = :id", nativeQuery = true) + int recordOutbound(@Param("id") Long id, @Param("at") LocalDateTime at, @Param("preview") String preview); + Optional findByUuid(String uuid); /** Inbox list: null companyId = all companies, null owner = any owner; q and digits are ready-made LIKE patterns. */ diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaTemplateRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaTemplateRepository.java index 090b3f4..61977d3 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaTemplateRepository.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaTemplateRepository.java @@ -2,5 +2,20 @@ package com.solvway.services.whatsapp.repository; import com.solvway.services.whatsapp.model.WaTemplate; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; -public interface WaTemplateRepository extends JpaRepository {} +import java.util.List; +import java.util.Optional; + +public interface WaTemplateRepository extends JpaRepository { + List findByCompanyIdOrderByNameAsc(Long companyId); + + Optional findByCompanyIdAndNameAndLanguage(Long companyId, String name, String language); + + /** Bulk delete (runs at once, so re-inserting the same name+language in the same transaction does not collide). */ + @Modifying + @Query("delete from WaTemplate t where t.companyId = :companyId") + void deleteByCompanyId(@Param("companyId") Long companyId); +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java index 6d2630f..443cd67 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java @@ -14,6 +14,7 @@ import org.springframework.web.client.RestTemplate; import java.time.Clock; import java.time.Duration; import java.time.Instant; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -72,6 +73,20 @@ public class CompanyDirectory { return byPhoneNumberId.entrySet().stream().filter(e -> e.getValue().id() == companyId).map(Map.Entry::getKey).findFirst(); } + /** The company's WhatsApp settings; empty when WhatsApp is not configured for it. */ + public Optional configOf(long companyId) { + return phoneNumberIdOf(companyId).flatMap(settings::findByPhoneNumberId); + } + + /** Every configured and resolved company id with its settings. */ + public Map configured() { + Map all = new LinkedHashMap<>(); + for (WhatsAppSettings.CompanyConfig c : settings.companies()) { + byPhoneNumberId(c.phoneNumberId()).ifPresent(company -> all.put(company.id(), c)); + } + return all; + } + private boolean coolingDown() { Instant failed = lastFailure; return failed != null && clock.instant().isBefore(failed.plus(RETRY_COOLDOWN)); diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/OutboundTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/OutboundTest.java new file mode 100644 index 0000000..2e1fa20 --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/OutboundTest.java @@ -0,0 +1,310 @@ +package com.solvway.services.whatsapp.inbox; + +import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig; +import com.solvway.services.whatsapp.controller.ErrorHandler; +import com.solvway.services.whatsapp.dto.MessageView; +import com.solvway.services.whatsapp.dto.SendMessageRequest; +import com.solvway.services.whatsapp.meta.MetaClient; +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.model.WaMessage; +import com.solvway.services.whatsapp.model.WaTemplate; +import com.solvway.services.whatsapp.ownership.OwnershipService; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import com.solvway.services.whatsapp.repository.WaMessageRepository; +import com.solvway.services.whatsapp.repository.WaReadRepository; +import com.solvway.services.whatsapp.repository.WaTemplateRepository; +import com.solvway.services.whatsapp.service.CompanyDirectory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.server.ResponseStatusException; + +import java.time.Clock; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class OutboundTest { + + private static final LocalDateTime NOW = LocalDateTime.of(2026, 12, 2, 12, 0); + private static final long STAFF = 10L; + private static final CompanyConfig CFG = new CompanyConfig("INS", "111", "222", "t", "s"); + + private WaConversationRepository conversations; + private WaMessageRepository messages; + private WaTemplateRepository templates; + private CompanyDirectory directory; + private MetaClient meta; + private OutboundService service; + private MockMvc mvc; + private final List statuses = new ArrayList<>(); + private WaConversation conv; + + @BeforeEach + void setUp() { + conversations = mock(WaConversationRepository.class); + messages = mock(WaMessageRepository.class); + templates = mock(WaTemplateRepository.class); + directory = mock(CompanyDirectory.class); + meta = mock(MetaClient.class); + Clock clock = Clock.fixed(NOW.toInstant(ZoneOffset.UTC), ZoneOffset.UTC); + InboxService inbox = new InboxService(conversations, messages, mock(WaReadRepository.class), mock(OwnershipService.class), directory, + mock(RestTemplate.class), clock); + service = new OutboundService(inbox, conversations, messages, templates, directory, meta, clock); + mvc = MockMvcBuilders.standaloneSetup(new OutboundController(service, mock(TemplateService.class))).setControllerAdvice(new ErrorHandler()).build(); + conv = new WaConversation(); + conv.id = 5L; + conv.uuid = "c-5"; + conv.companyId = 1L; + conv.contactWaId = "60123"; + conv.ownerUserId = STAFF; + conv.lastInboundAt = NOW.minusHours(1); + when(conversations.findByUuid("c-5")).thenReturn(Optional.of(conv)); + when(conversations.findById(5L)).thenReturn(Optional.of(conv)); + when(directory.configOf(1L)).thenReturn(Optional.of(CFG)); + when(messages.save(any(WaMessage.class))).thenAnswer(i -> { + WaMessage m = i.getArgument(0); + if (m.id == null) { + m.id = 77L; + } + statuses.add(m.status); + return m; + }); + } + + private void template(String status, int params) { + WaTemplate t = new WaTemplate(); + t.companyId = 1L; + t.name = "expo_followup"; + t.language = "en"; + t.status = status; + t.paramCount = params; + t.bodyText = "Hi {{1}}, thanks for visiting us at {{2}}."; + when(templates.findByCompanyIdAndNameAndLanguage(1L, "expo_followup", "en")).thenReturn(Optional.of(t)); + } + + private static void assertStatus(Runnable call, HttpStatus status, String reason) { + assertThatThrownBy(call::run).isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getReason()).isEqualTo(reason); + }); + } + + private MessageView sendText(String text) { + return service.send("c-5", 1L, STAFF, false, new SendMessageRequest(text, null, null, null)); + } + + private MessageView sendTemplate(String... params) { + return service.send("c-5", 1L, STAFF, false, new SendMessageRequest(null, "expo_followup", "en", List.of(params))); + } + + // ---- sending + + @Test + void windowClosedRefusesTextAndSendsNothing() { + conv.lastInboundAt = NOW.minusHours(25); + assertStatus(() -> sendText("hi"), HttpStatus.CONFLICT, "WINDOW_CLOSED"); + conv.lastInboundAt = NOW.minusHours(24); + assertStatus(() -> sendText("hi"), HttpStatus.CONFLICT, "WINDOW_CLOSED"); + conv.lastInboundAt = null; + assertStatus(() -> sendText("hi"), HttpStatus.CONFLICT, "WINDOW_CLOSED"); + verifyNoInteractions(meta); + verify(messages, never()).save(any()); + } + + @Test + void openWindowTextIsPendingThenSentWithWamid() { + when(meta.sendText(CFG, "60123", "hi")).thenReturn(new MetaClient.SendResult("wamid.A", null, null)); + + MessageView view = sendText("hi"); + + assertThat(statuses).containsExactly("pending", "sent"); + assertThat(view.status()).isEqualTo("sent"); + assertThat(view.direction()).isEqualTo("OUT"); + assertThat(view.type()).isEqualTo("text"); + assertThat(view.body()).isEqualTo("hi"); + assertThat(view.sentByUserId()).isEqualTo(STAFF); + assertThat(view.statusAt()).isEqualTo(NOW); + verify(messages, never()).findByWamidAndDirection(anyString(), anyString()); + verify(conversations).recordOutbound(5L, NOW, "hi"); + verify(conversations, never()).updateOwnership(any(), any(), any(Boolean.class), any()); + } + + @Test + void metaErrorStoresFailedWithCodeAndTitle() { + when(meta.sendText(CFG, "60123", "hi")).thenReturn(new MetaClient.SendResult(null, "131026", "Message undeliverable")); + + MessageView view = sendText("hi"); + + assertThat(statuses).containsExactly("pending", "failed"); + assertThat(view.status()).isEqualTo("failed"); + assertThat(view.errorCode()).isEqualTo("131026"); + assertThat(view.errorTitle()).isEqualTo("Message undeliverable"); + } + + @Test + void templateSendSubstitutesBodyAndWorksOutsideWindow() { + conv.lastInboundAt = null; + template("APPROVED", 2); + when(meta.sendTemplate(CFG, "60123", "expo_followup", "en", List.of("Ann", "Expo"))) + .thenReturn(new MetaClient.SendResult("wamid.T", null, null)); + + MessageView view = sendTemplate("Ann", "Expo"); + + assertThat(view.type()).isEqualTo("template"); + assertThat(view.templateName()).isEqualTo("expo_followup"); + assertThat(view.body()).isEqualTo("Hi Ann, thanks for visiting us at Expo."); + assertThat(view.status()).isEqualTo("sent"); + } + + @Test + void templateParamProblemsAreRefusedBeforeMeta() { + template("APPROVED", 2); + assertStatus(() -> sendTemplate("Ann", " "), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS"); + assertStatus(() -> sendTemplate("Ann"), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS"); + assertStatus(() -> sendTemplate("a", "b", "c"), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS"); + assertStatus(() -> service.send("c-5", 1L, STAFF, false, new SendMessageRequest(null, "expo_followup", "en", null)), + HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS"); + verifyNoInteractions(meta); + verify(messages, never()).save(any()); + } + + @Test + void unknownOrUnsupportedTemplateIsRefused() { + assertStatus(() -> sendTemplate("a", "b"), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS"); + template("UNSUPPORTED", 0); + assertStatus(() -> sendTemplate(), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS"); + verifyNoInteractions(meta); + } + + @Test + void notConfiguredIs409() { + when(directory.configOf(1L)).thenReturn(Optional.empty()); + assertStatus(() -> sendText("hi"), HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED"); + verifyNoInteractions(meta); + } + + @Test + void staffOnAnotherUsersChatOrCompanyGets404() { + conv.ownerUserId = 99L; + assertStatus(() -> sendText("hi"), HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND"); + conv.ownerUserId = STAFF; + assertStatus(() -> service.send("c-5", 2L, STAFF, false, new SendMessageRequest("hi", null, null, null)), + HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND"); + assertStatus(() -> service.send("c-5", null, STAFF, false, new SendMessageRequest("hi", null, null, null)), + HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND"); + verifyNoInteractions(meta); + } + + @Test + void emptyOrBothBodiesAreInvalid() { + assertStatus(() -> sendText(" "), HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); + assertStatus(() -> service.send("c-5", 1L, STAFF, false, new SendMessageRequest("x", "expo_followup", "en", List.of())), + HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); + verifyNoInteractions(meta); + } + + // ---- media + + private WaMessage media(String type, String mime, String filename) { + WaMessage m = new WaMessage(); + m.id = 3L; + m.uuid = "m-3"; + m.conversationId = 5L; + m.direction = "IN"; + m.type = type; + m.mediaId = "media-1"; + m.mediaMime = mime; + m.mediaFilename = filename; + when(messages.findByUuid("m-3")).thenReturn(Optional.of(m)); + return m; + } + + /** Meta stand-in: announces the mime to the sink, then writes the bytes. */ + private void streams(String mime, byte[] bytes) throws Exception { + doAnswer(inv -> { + try (java.io.OutputStream out = inv.getArgument(2).open(mime, bytes.length)) { + out.write(bytes); + } + return null; + }).when(meta).media(eq(CFG), eq("media-1"), any()); + } + + @Test + void mediaImageIsInlineWithMime() throws Exception { + media("image", "image/jpeg", null); + streams("image/jpeg", new byte[] {1, 2}); + + mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isOk()).andExpect(header().string("Content-Type", "image/jpeg")) + .andExpect(header().string("Content-Disposition", "inline")).andExpect(content().bytes(new byte[] {1, 2})); + } + + @Test + void mediaDocumentIsAttachmentWithFilename() throws Exception { + media("document", "application/pdf", "Quote 1.pdf"); + streams("application/pdf", new byte[] {1}); + + mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isOk()).andExpect(header().string("Content-Type", "application/pdf")) + .andExpect(header().string("Content-Disposition", org.hamcrest.Matchers.startsWith("attachment; filename=\"Quote 1.pdf\""))); + } + + @Test + void mediaActiveContentIsNeverInline() throws Exception { + media("image", "image/svg+xml", null); + streams("image/svg+xml", new byte[] {1}); + + mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(header().string("Content-Disposition", org.hamcrest.Matchers.startsWith("attachment"))) + .andExpect(header().string("X-Content-Type-Options", "nosniff")); + } + + @Test + void mediaExpiredIs410() throws Exception { + media("image", "image/jpeg", null); + doThrow(new MetaClient.MediaExpiredException()).when(meta).media(eq(CFG), eq("media-1"), any()); + + mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isGone()).andExpect(jsonPath("$.detail").value("MEDIA_EXPIRED")); + } + + @Test + void mediaNotVisibleOrNotMediaIs404() throws Exception { + WaMessage m = media("image", "image/jpeg", null); + conv.ownerUserId = 99L; + mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isNotFound()).andExpect(jsonPath("$.detail").value("CONVERSATION_NOT_FOUND")); + conv.ownerUserId = STAFF; + m.mediaId = null; + m.type = "text"; + mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isNotFound()); + mvc.perform(get("/whatsapp/media/nope").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isNotFound()).andExpect(jsonPath("$.detail").value("CONVERSATION_NOT_FOUND")); + verifyNoInteractions(meta); + } +} diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/TemplateServiceTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/TemplateServiceTest.java new file mode 100644 index 0000000..ee1542f --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/TemplateServiceTest.java @@ -0,0 +1,175 @@ +package com.solvway.services.whatsapp.inbox; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig; +import com.solvway.services.whatsapp.dto.TemplateView; +import com.solvway.services.whatsapp.meta.MetaClient; +import com.solvway.services.whatsapp.model.WaTemplate; +import com.solvway.services.whatsapp.repository.WaTemplateRepository; +import com.solvway.services.whatsapp.service.CompanyDirectory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.http.HttpStatus; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.server.ResponseStatusException; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class TemplateServiceTest { + + private static final ObjectMapper JSON = new ObjectMapper(); + private static final CompanyConfig INS = new CompanyConfig("INS", "111", "222", "t", "s"); + private static final CompanyConfig CV = new CompanyConfig("CV", "112", "223", "t", "s"); + + private WaTemplateRepository repo; + private CompanyDirectory directory; + private MetaClient meta; + private TemplateService service; + + @BeforeEach + void setUp() { + repo = mock(WaTemplateRepository.class); + directory = mock(CompanyDirectory.class); + meta = mock(MetaClient.class); + when(directory.configOf(1L)).thenReturn(Optional.of(INS)); + when(directory.configOf(2L)).thenReturn(Optional.of(CV)); + service = new TemplateService(repo, directory, meta, new TransactionTemplate(mock(PlatformTransactionManager.class)), + Clock.fixed(Instant.parse("2026-12-02T04:00:00Z"), ZoneOffset.UTC)); + } + + private static JsonNode json(String s) { + try { + return JSON.readTree(s); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static final String EXPO = "{\"name\":\"expo_followup\",\"language\":\"en\",\"category\":\"MARKETING\",\"status\":\"APPROVED\"," + + "\"components\":[{\"type\":\"BODY\",\"text\":\"Hi {{1}}, thanks for visiting us at {{2}}. {{1}} again.\"}]}"; + private static final String PROMO = "{\"name\":\"promo_header\",\"language\":\"en\",\"category\":\"MARKETING\",\"status\":\"APPROVED\"," + + "\"components\":[{\"type\":\"HEADER\",\"format\":\"IMAGE\"},{\"type\":\"BODY\",\"text\":\"Big sale\"}]}"; + + @SuppressWarnings("unchecked") + private List savedRows() { + ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); + verify(repo).saveAll(captor.capture()); + return captor.getValue(); + } + + @Test + void syncReplacesRowsWithBodyTextParamCountAndUnsupported() { + when(meta.templates(INS)).thenReturn(List.of(json(EXPO), json(PROMO))); + + service.sync(1L, true); + + verify(repo).deleteByCompanyId(1L); + List rows = savedRows(); + assertThat(rows).hasSize(2); + WaTemplate expo = rows.get(0); + assertThat(expo.companyId).isEqualTo(1L); + assertThat(expo.name).isEqualTo("expo_followup"); + assertThat(expo.language).isEqualTo("en"); + assertThat(expo.category).isEqualTo("MARKETING"); + assertThat(expo.status).isEqualTo("APPROVED"); + assertThat(expo.paramCount).isEqualTo(2); // {{1}} twice counts once + assertThat(expo.bodyText).startsWith("Hi {{1}}"); + assertThat(rows.get(1).status).isEqualTo("UNSUPPORTED"); + } + + @Test + void metaFailureKeepsExistingRows() { + when(meta.templates(INS)).thenThrow(new MetaClient.MetaException("NETWORK")); + + assertThatThrownBy(() -> service.sync(1L, true)).isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_GATEWAY)); + verify(repo, never()).deleteByCompanyId(any(Long.class)); + } + + @Test + void staffCannotSyncAndUnconfiguredCompanyIs409() { + assertThatThrownBy(() -> service.sync(1L, false)).isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + assertThatThrownBy(() -> service.sync(9L, true)).isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getReason()).isEqualTo("WHATSAPP_NOT_CONFIGURED"); + }); + verify(meta, never()).templates(any()); + } + + @Test + void superAdminWithoutCompanySyncsEveryConfiguredCompanyAndSurvivesOneFailure() { + LinkedHashMap all = new LinkedHashMap<>(); + all.put(1L, INS); + all.put(2L, CV); + when(directory.configured()).thenReturn(all); + when(meta.templates(INS)).thenThrow(new MetaClient.MetaException("190")); + when(meta.templates(CV)).thenReturn(List.of(json(EXPO))); + + service.sync(null, true); + + verify(repo).deleteByCompanyId(2L); + verify(repo, never()).deleteByCompanyId(1L); + } + + @Test + void nightlySyncsEveryCompany() { + LinkedHashMap all = new LinkedHashMap<>(); + all.put(1L, INS); + when(directory.configured()).thenReturn(all); + when(meta.templates(INS)).thenReturn(List.of(json(EXPO))); + + service.nightly(); + + verify(repo).deleteByCompanyId(1L); + } + + @Test + void listShowsSupportedFlagFromStatus() { + WaTemplate ok = row("a", "APPROVED"); + WaTemplate bad = row("b", "UNSUPPORTED"); + when(repo.findByCompanyIdOrderByNameAsc(1L)).thenReturn(List.of(ok, bad)); + + List views = service.list(1L); + + assertThat(views).extracting(TemplateView::name).containsExactly("a", "b"); + assertThat(views).extracting(TemplateView::supported).containsExactly(true, false); + assertThat(service.list(null)).isEmpty(); + } + + private static WaTemplate row(String name, String status) { + WaTemplate t = new WaTemplate(); + t.name = name; + t.language = "en"; + t.status = status; + return t; + } + + @Test + void supportedRule() { + assertThat(TemplateService.supported(json(EXPO))).isTrue(); + assertThat(TemplateService.supported(json(PROMO))).isFalse(); + assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"HEADER\",\"format\":\"TEXT\",\"text\":\"Hello\"},{\"type\":\"BODY\",\"text\":\"x\"}]}"))).isTrue(); + assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"HEADER\",\"format\":\"TEXT\",\"text\":\"Hello {{1}}\"}]}"))).isFalse(); + assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"BODY\",\"text\":\"x\"},{\"type\":\"BUTTONS\",\"buttons\":[{\"type\":\"QUICK_REPLY\"},{\"type\":\"URL\",\"url\":\"https://a.com\"}]}]}"))).isTrue(); + assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"BODY\",\"text\":\"x\"},{\"type\":\"BUTTONS\",\"buttons\":[{\"type\":\"URL\",\"url\":\"https://a.com/{{1}}\"}]}]}"))).isFalse(); + assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"BODY\",\"text\":\"x\"},{\"type\":\"BUTTONS\",\"buttons\":[{\"type\":\"COPY_CODE\"}]}]}"))).isFalse(); + assertThat(TemplateService.supported(json("{\"parameter_format\":\"NAMED\",\"components\":[{\"type\":\"BODY\",\"text\":\"Hi {{name}}\"}]}"))).isFalse(); + } +} diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/meta/MetaClientTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/meta/MetaClientTest.java new file mode 100644 index 0000000..331ee10 --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/meta/MetaClientTest.java @@ -0,0 +1,263 @@ +package com.solvway.services.whatsapp.meta; + +import com.fasterxml.jackson.databind.JsonNode; +import com.solvway.services.whatsapp.config.WhatsAppSettings; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.test.web.client.ExpectedCount; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.header; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withException; + +class MetaClientTest { + + private WhatsAppSettings.CompanyConfig cfg; + private MockRestServiceServer server; + private MetaClient client; + + @BeforeEach + void setUp() { + MockEnvironment env = new MockEnvironment().withProperty("WHATSAPP_COMPANIES", "INS") + .withProperty("WHATSAPP_INS_PHONE_NUMBER_ID", "111").withProperty("WHATSAPP_INS_WABA_ID", "222") + .withProperty("WHATSAPP_INS_ACCESS_TOKEN", "tok").withProperty("WHATSAPP_INS_APP_SECRET", "s") + .withProperty("WHATSAPP_GRAPH_BASE_URL", "http://graph.test/v1"); + WhatsAppSettings settings = new WhatsAppSettings(env); + cfg = settings.companies().get(0); + RestTemplate rest = new RestTemplate(); + server = MockRestServiceServer.bindTo(rest).build(); + client = new MetaClient(settings, rest); + } + + @Test + void sendsTextWithBearerAndReturnsWamid() { + server.expect(requestTo("http://graph.test/v1/111/messages")).andExpect(method(HttpMethod.POST)) + .andExpect(header("Authorization", "Bearer tok")) + .andExpect(jsonPath("$.messaging_product").value("whatsapp")).andExpect(jsonPath("$.to").value("60123")) + .andExpect(jsonPath("$.type").value("text")).andExpect(jsonPath("$.text.body").value("hello")) + .andRespond(withSuccess("{\"messages\":[{\"id\":\"wamid.X\"}]}", MediaType.APPLICATION_JSON)); + + MetaClient.SendResult r = client.sendText(cfg, "60123", "hello"); + + assertThat(r.wamid()).isEqualTo("wamid.X"); + assertThat(r.failed()).isFalse(); + server.verify(); + } + + @Test + void sendsTemplateWithBodyParametersAndOmitsComponentsWithoutParams() { + server.expect(requestTo("http://graph.test/v1/111/messages")).andExpect(jsonPath("$.type").value("template")) + .andExpect(jsonPath("$.template.name").value("expo_followup")).andExpect(jsonPath("$.template.language.code").value("en")) + .andExpect(jsonPath("$.template.components[0].type").value("body")) + .andExpect(jsonPath("$.template.components[0].parameters[1].text").value("Expo")) + .andRespond(withSuccess("{\"messages\":[{\"id\":\"wamid.T\"}]}", MediaType.APPLICATION_JSON)); + server.expect(requestTo("http://graph.test/v1/111/messages")).andExpect(jsonPath("$.template.components").doesNotExist()) + .andRespond(withSuccess("{\"messages\":[{\"id\":\"wamid.U\"}]}", MediaType.APPLICATION_JSON)); + + assertThat(client.sendTemplate(cfg, "60123", "expo_followup", "en", List.of("Ann", "Expo")).wamid()).isEqualTo("wamid.T"); + assertThat(client.sendTemplate(cfg, "60123", "plain", "en", List.of()).wamid()).isEqualTo("wamid.U"); + } + + @Test + void metaErrorGivesCodeAndTitleOrMessage() { + server.expect(requestTo("http://graph.test/v1/111/messages")).andRespond(withStatus(HttpStatus.BAD_REQUEST) + .contentType(MediaType.APPLICATION_JSON).body("{\"error\":{\"code\":131026,\"title\":\"Message undeliverable\",\"message\":\"m\"}}")); + server.expect(requestTo("http://graph.test/v1/111/messages")).andRespond(withStatus(HttpStatus.UNAUTHORIZED) + .contentType(MediaType.APPLICATION_JSON).body("{\"error\":{\"code\":190,\"message\":\"Invalid token\"}}")); + + MetaClient.SendResult first = client.sendText(cfg, "60123", "x"); + MetaClient.SendResult second = client.sendText(cfg, "60123", "x"); + + assertThat(first.failed()).isTrue(); + assertThat(first.errorCode()).isEqualTo("131026"); + assertThat(first.errorTitle()).isEqualTo("Message undeliverable"); + assertThat(second.errorCode()).isEqualTo("190"); + assertThat(second.errorTitle()).isEqualTo("Invalid token"); + } + + @Test + void networkErrorGivesNetworkCode() { + server.expect(requestTo("http://graph.test/v1/111/messages")).andRespond(withException(new IOException("down"))); + + MetaClient.SendResult r = client.sendText(cfg, "60123", "x"); + + assertThat(r.failed()).isTrue(); + assertThat(r.errorCode()).isEqualTo("NETWORK"); + } + + @Test + void templatesFollowPagingNext() { + server.expect(requestTo("http://graph.test/v1/222/message_templates?status=APPROVED&limit=200")) + .andExpect(header("Authorization", "Bearer tok")) + .andRespond(withSuccess("{\"data\":[{\"name\":\"a\"}],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=X\"}}", + MediaType.APPLICATION_JSON)); + server.expect(requestTo("http://graph.test/v1/222/message_templates?after=X")) + .andExpect(header("Authorization", "Bearer tok")) + .andRespond(withSuccess("{\"data\":[{\"name\":\"b\"}],\"paging\":{}}", MediaType.APPLICATION_JSON)); + + List all = client.templates(cfg); + + assertThat(all).extracting(n -> n.get("name").asText()).containsExactly("a", "b"); + server.verify(); + } + + @Test + void templatePagingStopsWhenNextRepeatsTheRequestedUrl() { + server.expect(requestTo("http://graph.test/v1/222/message_templates?status=APPROVED&limit=200")) + .andRespond(withSuccess("{\"data\":[{\"name\":\"a\"}],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=X\"}}", + MediaType.APPLICATION_JSON)); + server.expect(requestTo("http://graph.test/v1/222/message_templates?after=X")) + .andRespond(withSuccess("{\"data\":[{\"name\":\"b\"}],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=X\"}}", + MediaType.APPLICATION_JSON)); + + assertThat(client.templates(cfg)).hasSize(2); + server.verify(); + } + + @Test + void templatePagingStopsOnAnEmptyPage() { + server.expect(requestTo("http://graph.test/v1/222/message_templates?status=APPROVED&limit=200")) + .andRespond(withSuccess("{\"data\":[],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=Y\"}}", + MediaType.APPLICATION_JSON)); + + assertThat(client.templates(cfg)).isEmpty(); + server.verify(); + } + + @Test + void templatePagingIsCappedAtFiftyPages() { + int[] n = {0}; + server.expect(ExpectedCount.manyTimes(), requestTo(org.hamcrest.Matchers.startsWith("http://graph.test/v1/222/message_templates"))) + .andRespond(request -> withSuccess("{\"data\":[{\"name\":\"t\"}],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=p" + + (++n[0]) + "\"}}", MediaType.APPLICATION_JSON).createResponse(request)); + + assertThatThrownBy(() -> client.templates(cfg)).isInstanceOf(MetaClient.MetaException.class); + assertThat(n[0]).isEqualTo(50); + } + + /** Sink that records what was announced and written, and how much of the upstream had been read at the first write. */ + private static class Sink implements MetaClient.MediaSink { + String mime; + long length = -2; + boolean opened; + final java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); + long upstreamReadAtFirstWrite = -1; + java.util.function.LongSupplier upstreamRead = () -> -1; + + @Override + public java.io.OutputStream open(String mime, long length) { + this.mime = mime; + this.length = length; + opened = true; + return new java.io.OutputStream() { + @Override + public void write(int b) { + write(new byte[] {(byte) b}, 0, 1); + } + + @Override + public void write(byte[] b, int off, int len) { + if (upstreamReadAtFirstWrite < 0) { + upstreamReadAtFirstWrite = upstreamRead.getAsLong(); + } + out.write(b, off, len); + } + }; + } + } + + private void expectMediaLookup(String url) { + server.expect(requestTo("http://graph.test/v1/m1")).andExpect(header("Authorization", "Bearer tok")) + .andRespond(withSuccess("{\"url\":\"" + url + "\",\"mime_type\":\"image/png\"}", MediaType.APPLICATION_JSON)); + } + + @Test + void mediaFetchesUrlThenStreamsBytes() { + expectMediaLookup("http://cdn.test/file"); + server.expect(requestTo("http://cdn.test/file")).andExpect(header("Authorization", "Bearer tok")) + .andRespond(withSuccess(new byte[] {1, 2, 3}, MediaType.APPLICATION_OCTET_STREAM)); + Sink sink = new Sink(); + + client.media(cfg, "m1", sink); + + assertThat(sink.out.toByteArray()).containsExactly(1, 2, 3); + assertThat(sink.mime).isEqualTo("image/png"); + } + + @Test + void mediaIsPassedThroughNotBufferedWhole() { + expectMediaLookup("http://cdn.test/big"); + byte[] data = new byte[64 * 1024]; + long[] read = {0}; + java.io.InputStream upstream = new java.io.ByteArrayInputStream(data) { + @Override + public synchronized int read(byte[] b, int off, int len) { + int n = super.read(b, off, len); + if (n > 0) { + read[0] += n; + } + return n; + } + }; + server.expect(requestTo("http://cdn.test/big")).andRespond(request -> + new org.springframework.mock.http.client.MockClientHttpResponse(upstream, HttpStatus.OK)); + Sink sink = new Sink(); + sink.upstreamRead = () -> read[0]; + + client.media(cfg, "m1", sink); + + assertThat(sink.out.size()).isEqualTo(data.length); + assertThat(sink.upstreamReadAtFirstWrite).isGreaterThan(0).isLessThan(data.length); + } + + @Test + void mediaOverTheCapIsRefusedByContentLengthBeforeAnyByte() { + expectMediaLookup("http://cdn.test/huge"); + server.expect(requestTo("http://cdn.test/huge")).andRespond(withSuccess(new byte[] {1}, MediaType.APPLICATION_OCTET_STREAM) + .header("Content-Length", String.valueOf(MetaClient.MAX_MEDIA_BYTES + 1))); + Sink sink = new Sink(); + + assertThatThrownBy(() -> client.media(cfg, "m1", sink)).isInstanceOf(MetaClient.MetaException.class); + assertThat(sink.opened).isFalse(); + } + + @Test + void mediaCopyStopsAtTheCapWhenLengthIsUnknown() { + expectMediaLookup("http://cdn.test/chunked"); + server.expect(requestTo("http://cdn.test/chunked")).andRespond(withSuccess(new byte[100], MediaType.APPLICATION_OCTET_STREAM)); + client.maxMediaBytes = 10; + Sink sink = new Sink(); + + assertThatThrownBy(() -> client.media(cfg, "m1", sink)).isInstanceOf(MetaClient.MetaException.class); + assertThat(sink.out.size()).isLessThanOrEqualTo(10); + } + + @Test + void mediaGoneIsExpiredAndNothingIsOpened() { + server.expect(requestTo("http://graph.test/v1/m1")).andRespond(withStatus(HttpStatus.NOT_FOUND)); + server.expect(requestTo("http://graph.test/v1/m2")) + .andRespond(withSuccess("{\"url\":\"http://cdn.test/f\",\"mime_type\":\"image/png\"}", MediaType.APPLICATION_JSON)); + server.expect(requestTo("http://cdn.test/f")).andRespond(withStatus(HttpStatus.GONE)); + Sink sink = new Sink(); + + assertThatThrownBy(() -> client.media(cfg, "m1", sink)).isInstanceOf(MetaClient.MediaExpiredException.class); + assertThatThrownBy(() -> client.media(cfg, "m2", sink)).isInstanceOf(MetaClient.MediaExpiredException.class); + assertThat(sink.opened).isFalse(); + } +} -- 2.54.1 From 0d5c3f351a7880cdf9c449a41038252a82ff84e0 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 09:20:45 +0800 Subject: [PATCH 13/23] chore: tick whatsapp task 4.1 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-whatsapp-inbox/tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openspec/changes/add-whatsapp-inbox/tasks.md b/openspec/changes/add-whatsapp-inbox/tasks.md index 424acde..dc0b06d 100644 --- a/openspec/changes/add-whatsapp-inbox/tasks.md +++ b/openspec/changes/add-whatsapp-inbox/tasks.md @@ -49,7 +49,7 @@ Verify commands: ## Wave 4 (serial) -- [ ] 4.1 Meta client and sending: text inside the window, templates with parameter validation, template sync per company, the media proxy, error mapping to failed, and "not configured". The mock gains the Graph endpoints and `/simulate/inbound`. +- [x] 4.1 Meta client and sending: text inside the window, templates with parameter validation, template sync per company, the media proxy, error mapping to failed, and "not configured". The mock gains the Graph endpoints and `/simulate/inbound`. - Depends on: 3.2 - Scope: `solvway-services-whatsapp/**`, `local/whatsapp-mock/**` - Verify: `mvn -T 1C -q -pl solvway-services-whatsapp verify` -- 2.54.1 From 13b692748c6447aca8ed64e6125a3d9bb8fd8eab Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 09:51:13 +0800 Subject: [PATCH 14/23] feat: whatsapp admin api in mobile-api - /api/admin/whatsapp: conversations, thread, send, read, assign, start, templates and sync, media, unread count, assignees. - Caller context from the token: company through AdminCompanyScope (fail closed), admin for BO_WHATSAPP_ADMIN or super admin. - Exactly-one validation for send, assign and start; path ids must look like uuids before they reach the service. - Service reason codes come back with their status and a message; an unreachable service is 502. - Owner and assignee names filled from the system service. - Audit: send (conversation and template name, never text), assign (owner before and after), start, sync; read markers skipped. - Media streams with nosniff and a sandbox CSP; anything but image, audio or video downloads. - Disabling a user or changing their roles tells the service to free their chats (best effort). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-whatsapp-inbox/tasks.md | 2 +- .../api/RestApiSystemServiceConstants.java | 1 + .../admin/AdminWhatsAppController.java | 131 ++++++++ .../mobile/api/service/AdminUserService.java | 4 + .../api/service/AdminWhatsAppService.java | 308 ++++++++++++++++++ .../admin/AdminWhatsAppControllerTest.java | 155 +++++++++ .../service/AdminUserServiceWhatsAppTest.java | 138 ++++++++ .../api/service/AdminWhatsAppServiceTest.java | 292 +++++++++++++++++ 8 files changed, 1030 insertions(+), 1 deletion(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminWhatsAppController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminWhatsAppService.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminWhatsAppControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceWhatsAppTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminWhatsAppServiceTest.java diff --git a/openspec/changes/add-whatsapp-inbox/tasks.md b/openspec/changes/add-whatsapp-inbox/tasks.md index dc0b06d..cc5d4ee 100644 --- a/openspec/changes/add-whatsapp-inbox/tasks.md +++ b/openspec/changes/add-whatsapp-inbox/tasks.md @@ -53,7 +53,7 @@ Verify commands: - Depends on: 3.2 - Scope: `solvway-services-whatsapp/**`, `local/whatsapp-mock/**` - Verify: `mvn -T 1C -q -pl solvway-services-whatsapp verify` -- [ ] 4.2 mobile-api admin API: every endpoint in design decision 9, module checks, company scoping (fail closed), audit, and the `userChanged` call from the user save path. +- [x] 4.2 mobile-api admin API: every endpoint in design decision 9, module checks, company scoping (fail closed), audit, and the `userChanged` call from the user save path. - Depends on: 4.1 - Scope: `solvway-mobile-api/**` (security code: also read the whole diff in the controller check) - Verify: `mvn -T 1C -q -pl solvway-mobile-api verify` diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java index ab15e24..79956e9 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java @@ -7,6 +7,7 @@ public class RestApiSystemServiceConstants { public static final String API_REST_SYSTEM_USER_FIND_BY_USERNAME = "/user/findByUsername/{username}"; public static final String API_REST_SYSTEM_USER_FIND_BY_ID = "/user/findById/{id}"; public static final String API_REST_SYSTEM_USER_ACTIVE_ADMIN_OF = "/user/{id}/activeAdminOf/{companyId}"; + public static final String API_REST_SYSTEM_USER_ACTIVE_WITH_MODULE = "/user/activeWithModule?companyId={companyId}&module={module}"; public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL = "/user/findByEmail/{email}"; public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_ID_NOT = "/user/findByEmailAndIdNot/{email}/{id}"; public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_COMPANY = "/user/findByEmailAndCompanyId/{email}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminWhatsAppController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminWhatsAppController.java new file mode 100644 index 0000000..db5b9d1 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminWhatsAppController.java @@ -0,0 +1,131 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.whatsapp.AssignRequest; +import com.solvway.mobile.api.dto.whatsapp.ConversationPage; +import com.solvway.mobile.api.dto.whatsapp.ConversationView; +import com.solvway.mobile.api.dto.whatsapp.MessageView; +import com.solvway.mobile.api.dto.whatsapp.SendMessageRequest; +import com.solvway.mobile.api.dto.whatsapp.StartChatRequest; +import com.solvway.mobile.api.dto.whatsapp.TemplateView; +import com.solvway.mobile.api.dto.whatsapp.ThreadView; +import com.solvway.mobile.api.dto.whatsapp.UnreadCount; +import com.solvway.mobile.api.service.AdminWhatsAppService; +import com.solvway.mobile.api.useraccess.AdminModule; +import com.solvway.mobile.api.useraccess.Audited; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +/** + * The WhatsApp inbox (design decision 9). Staff with BO_WHATSAPP see their own chats; BO_WHATSAPP_ADMIN sees the + * company's. companyId is honoured for a super admin only (AdminCompanyScope). Must stay under {@code controller..}. + */ +@RestController +@RequestMapping("/api/admin/whatsapp") +@RequiredArgsConstructor +@AdminModule({AdminWhatsAppService.MODULE, AdminWhatsAppService.MODULE_ADMIN}) +public class AdminWhatsAppController { + private final AdminWhatsAppService whatsapp; + + @AppAuth + @GetMapping("/conversations") + public ResponseEntity list(@RequestParam(defaultValue = "mine") String tab, @RequestParam(required = false) String q, + @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "30") int size, + @RequestParam(required = false) Long companyId) { + return ResponseEntity.ok(whatsapp.list(companyId, tab, q, page, size)); + } + + @AppAuth + @GetMapping("/conversations/{uuid}") + public ResponseEntity thread(@PathVariable String uuid, @RequestParam(required = false) String before, + @RequestParam(required = false) Long companyId) { + return ResponseEntity.ok(whatsapp.thread(uuid, companyId, before)); + } + + @AppAuth + @Audited(action = "WHATSAPP_SEND") + @PostMapping("/conversations/{uuid}/messages") + public ResponseEntity send(@PathVariable String uuid, @RequestBody SendMessageRequest request, + @RequestParam(required = false) Long companyId) { + return ResponseEntity.ok(whatsapp.send(uuid, companyId, request)); + } + + @AppAuth + @Audited(skip = true) + @PostMapping("/conversations/{uuid}/read") + public ResponseEntity read(@PathVariable String uuid, @RequestParam(required = false) Long companyId) { + whatsapp.read(uuid, companyId); + return ResponseEntity.noContent().build(); + } + + @AppAuth + @AdminModule(AdminWhatsAppService.MODULE_ADMIN) + @Audited(action = "WHATSAPP_ASSIGN") + @PostMapping("/conversations/{uuid}/assign") + public ResponseEntity assign(@PathVariable String uuid, @RequestBody AssignRequest request, + @RequestParam(required = false) Long companyId) { + return ResponseEntity.ok(whatsapp.assign(uuid, companyId, request)); + } + + @AppAuth + @Audited(action = "WHATSAPP_START") + @PostMapping("/start") + public ResponseEntity start(@RequestBody StartChatRequest request, @RequestParam(required = false) Long companyId) { + return ResponseEntity.ok(whatsapp.start(companyId, request)); + } + + @AppAuth + @GetMapping("/templates") + public ResponseEntity> templates(@RequestParam(required = false) Long companyId) { + return ResponseEntity.ok(whatsapp.templates(companyId)); + } + + @AppAuth + @AdminModule(AdminWhatsAppService.MODULE_ADMIN) + @Audited(action = "WHATSAPP_TEMPLATE_SYNC") + @PostMapping("/templates/sync") + public ResponseEntity> syncTemplates(@RequestParam(required = false) Long companyId) { + return ResponseEntity.ok(whatsapp.syncTemplates(companyId)); + } + + @AppAuth + @GetMapping("/media/{messageUuid}") + public void media(@PathVariable String messageUuid, @RequestParam(required = false) Long companyId, HttpServletResponse response) { + whatsapp.media(messageUuid, companyId, (type, length) -> { + response.setContentType(type); + if (length >= 0) response.setContentLengthLong(length); + response.setHeader("Cache-Control", "private, no-store"); + // The type is whatever the sender declared: never let it run as a page on this origin. + response.setHeader("X-Content-Type-Options", "nosniff"); + response.setHeader("Content-Security-Policy", "sandbox"); + if (!type.startsWith("image/") && !type.startsWith("audio/") && !type.startsWith("video/")) { + response.setHeader("Content-Disposition", "attachment"); + } + return response.getOutputStream(); + }); + } + + @AppAuth + @GetMapping("/unread-count") + public ResponseEntity unreadCount(@RequestParam(required = false) Long companyId) { + return ResponseEntity.ok(whatsapp.unreadCount(companyId)); + } + + @AppAuth + @AdminModule(AdminWhatsAppService.MODULE_ADMIN) + @GetMapping("/assignees") + public ResponseEntity>> assignees(@RequestParam(required = false) Long companyId) { + return ResponseEntity.ok(whatsapp.assignees(companyId)); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java index fbbc9cd..ba2566e 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java @@ -178,6 +178,10 @@ public class AdminUserService { List rolesAfter = sortedRoleNames(user.get("roles")); if (r.roles() != null && !rolesBefore.equals(rolesAfter)) AuditChanges.put("roles", rolesBefore, rolesAfter); if (r.enabled() != null && !r.enabled().equals(enabledBefore)) AuditChanges.put("enabled", enabledBefore, r.enabled()); + if (Boolean.FALSE.equals(r.enabled()) && !Boolean.FALSE.equals(enabledBefore) + || r.roles() != null && !rolesBefore.equals(rolesAfter)) { + AdminWhatsAppService.userChanged(restTemplateUtil, id); // they may have lost WhatsApp: free their chats + } return present(clean(saved)); } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminWhatsAppService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminWhatsAppService.java new file mode 100644 index 0000000..1d11229 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminWhatsAppService.java @@ -0,0 +1,308 @@ +package com.solvway.mobile.api.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.constant.api.RestApiWhatsappServiceConstants; +import com.solvway.mobile.api.dto.whatsapp.AssignRequest; +import com.solvway.mobile.api.dto.whatsapp.ConversationPage; +import com.solvway.mobile.api.dto.whatsapp.ConversationView; +import com.solvway.mobile.api.dto.whatsapp.MessageView; +import com.solvway.mobile.api.dto.whatsapp.SendMessageRequest; +import com.solvway.mobile.api.dto.whatsapp.StartChatRequest; +import com.solvway.mobile.api.dto.whatsapp.TemplateView; +import com.solvway.mobile.api.dto.whatsapp.ThreadView; +import com.solvway.mobile.api.dto.whatsapp.UnreadCount; +import com.solvway.mobile.api.dto.whatsapp.UserChangedRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.useraccess.AdminModuleAccess; +import com.solvway.mobile.api.useraccess.AuditChanges; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +/** + * The WhatsApp inbox for the admin portal. Resolves the caller's context (company, user, admin) from the token and + * passes it to the WhatsApp service, which enforces who may see what (RestApiWhatsappServiceConstants). + */ +@Slf4j +@Service +public class AdminWhatsAppService { + public static final String MODULE = "BO_WHATSAPP"; + public static final String MODULE_ADMIN = "BO_WHATSAPP_ADMIN"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final java.util.regex.Pattern UUID_LIKE = java.util.regex.Pattern.compile("[A-Za-z0-9-]{1,64}"); + private static final ParameterizedTypeReference> IDS = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference> TEMPLATES = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + /** Messages the portal shows for the service's reason codes; anything else keeps the code. */ + private static final Map MESSAGES = Map.of( + "WINDOW_CLOSED", "The 24-hour window has closed. Send a template.", + "TEMPLATE_PARAMS", "Fill in every template parameter.", + "MEDIA_EXPIRED", "Media expired", + "WHATSAPP_NOT_CONFIGURED", "WhatsApp is not configured", + "ASSIGNEE_NOT_ALLOWED", "This user cannot take WhatsApp chats.", + "LEAD_NOT_FOUND", "This lead has no mobile number.", + "USERS_UNAVAILABLE", "Users could not be loaded. Try again."); + + private final RestTemplateCustomUtil rest; + private final RestTemplate restTemplate; + private final AdminAuthenticationService adminAuthenticationService; + // a field initializer: the scope holds no state + private final AdminCompanyScope scope = new AdminCompanyScope(); + + public AdminWhatsAppService(RestTemplateCustomUtil rest, RestTemplate restTemplate, + AdminAuthenticationService adminAuthenticationService) { + this.rest = rest; + this.restTemplate = restTemplate; + this.adminAuthenticationService = adminAuthenticationService; + } + + /** Who is asking: the company they may see (null = super admin, all companies), their id, and admin rights. */ + record Context(Long companyId, long userId, boolean admin) {} + + Context context(Long requestedCompanyId) { + User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (caller == null || caller.getId() == null) throw coded(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED"); + Long company = scope.scope(caller, requestedCompanyId); // staff without a company: 403, fail closed + boolean admin = AdminCompanyScope.isSuper(caller) || AdminModuleAccess.holds(rest, caller, MODULE_ADMIN); + return new Context(company, caller.getId(), admin); + } + + public ConversationPage list(Long companyId, String tab, String q, int page, int size) { + Context c = context(companyId); + ConversationPage p = call(() -> rest.getForEntity( + url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATIONS, null, c) + + "&tab={tab}&q={q}&page={page}&size={size}", + ConversationPage.class, tab, q == null ? "" : q.trim(), page, size).getBody()); + Function names = names(); + return new ConversationPage(p.items().stream().map(v -> named(v, names)).toList(), p.total(), p.page(), p.size()); + } + + public ThreadView thread(String uuid, Long companyId, String before) { + Context c = context(companyId); + String u = url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION, uuid, c); + ThreadView t = call(() -> before == null + ? rest.getForEntity(u, ThreadView.class).getBody() + : rest.getForEntity(u + "&before={before}", ThreadView.class, before).getBody()); + return new ThreadView(named(t.conversation(), names()), t.messages(), t.hasOlder()); + } + + public MessageView send(String uuid, Long companyId, SendMessageRequest r) { + boolean text = r != null && StringUtils.hasText(r.text()); + boolean template = r != null && StringUtils.hasText(r.template()); + if (text == template) throw coded(HttpStatus.BAD_REQUEST, "Send a text or a template.", "INVALID_PAYLOAD"); + Context c = context(companyId); + // the template name only: never the message text or the filled-in parameters + AuditChanges.put("conversation", null, uuid); + if (template) AuditChanges.put("template", null, r.template()); + return call(() -> rest.postForEntity(url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION_SEND, uuid, c), + MessageView.class, r).getBody()); + } + + public void read(String uuid, Long companyId) { + Context c = context(companyId); + call(() -> rest.postForEntity(url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION_READ, uuid, c), + Void.class, null)); + } + + public ConversationView assign(String uuid, Long companyId, AssignRequest r) { + boolean manual = r != null && r.userId() != null; + boolean automatic = r != null && Boolean.TRUE.equals(r.automatic()); + if (manual == automatic) throw coded(HttpStatus.BAD_REQUEST, "Choose a user or automatic.", "INVALID_PAYLOAD"); + Context c = context(companyId); + if (!c.admin()) throw coded(HttpStatus.FORBIDDEN, "WhatsApp Admin only", "FORBIDDEN"); + // ponytail: reads the thread for the owner before the change (audit); a light conversation GET if it shows up in latency. + ConversationView before = call(() -> rest.getForEntity( + url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION, uuid, c), ThreadView.class).getBody()).conversation(); + ConversationView after = call(() -> rest.postForEntity( + url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION_ASSIGN, uuid, c), + ConversationView.class, r).getBody()); + AuditChanges.put("ownerUserId", before.ownerUserId(), after.ownerUserId()); + AuditChanges.put("ownerManual", before.ownerManual(), after.ownerManual()); + return named(after, names()); + } + + public ConversationView start(Long companyId, StartChatRequest r) { + if (r == null || (r.leadUuid() == null) == (r.eventLeadUuid() == null)) { + throw coded(HttpStatus.BAD_REQUEST, "Choose a lead or an event lead.", "INVALID_PAYLOAD"); + } + Context c = context(companyId); + ConversationView v = call(() -> rest.postForEntity( + url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION_START, null, c), ConversationView.class, r).getBody()); + AuditChanges.put("conversation", null, v.uuid()); + return named(v, names()); + } + + public List templates(Long companyId) { + Context c = context(companyId); + List t = call(() -> rest.getForEntity( + rest.getURLforApiService(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_TEMPLATES) + "?companyId={companyId}", + TEMPLATES, c.companyId() == null ? "" : c.companyId()).getBody()); + return t == null ? List.of() : t; + } + + public List syncTemplates(Long companyId) { + Context c = context(companyId); + if (!c.admin()) throw coded(HttpStatus.FORBIDDEN, "WhatsApp Admin only", "FORBIDDEN"); + AuditChanges.put("companyId", null, c.companyId()); + List t = call(() -> rest.postForEntity( + rest.getURLforApiService(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_TEMPLATES_SYNC) + + "?companyId=" + (c.companyId() == null ? "" : c.companyId()) + "&admin=true", + TEMPLATES, null).getBody()); + return t == null ? List.of() : t; + } + + public UnreadCount unreadCount(Long companyId) { + Context c = context(companyId); + return call(() -> rest.getForEntity(url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_UNREAD_COUNT, null, c), + UnreadCount.class).getBody()); + } + + /** Active users of the company who hold BO_WHATSAPP: the people a WhatsApp Admin may assign a chat to. */ + public List> assignees(Long companyId) { + Context c = context(companyId); + if (!c.admin()) throw coded(HttpStatus.FORBIDDEN, "WhatsApp Admin only", "FORBIDDEN"); + if (c.companyId() == null) throw coded(HttpStatus.BAD_REQUEST, "Choose a company.", "COMPANY_REQUIRED"); + List ids = call(() -> rest.getForEntity(rest.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_ACTIVE_WITH_MODULE), + IDS, c.companyId(), MODULE).getBody()); + Function names = names(); + List> out = new ArrayList<>(); + for (Long id : ids == null ? List.of() : ids) { + Map row = new LinkedHashMap<>(); + row.put("id", id); + row.put("name", names.apply(id)); + out.add(row); + } + return out; + } + + /** Where the media bytes go: called once with the type and length, before any byte is written. */ + public interface MediaOutput { + OutputStream open(String contentType, long contentLength) throws IOException; + } + + /** Streams an incoming image or document through; 404 without access, 410 when Meta no longer holds it. */ + public void media(String messageUuid, Long companyId, MediaOutput out) { + Context c = context(companyId); + String url = url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_MEDIA, messageUuid, c); + call(() -> restTemplate.execute(url, HttpMethod.GET, + req -> req.getHeaders().addAll(rest.getCommonHeaders()), + resp -> { + HttpHeaders h = resp.getHeaders(); + String type = h.getContentType() == null ? "application/octet-stream" : h.getContentType().toString(); + try (InputStream in = resp.getBody(); OutputStream o = out.open(type, h.getContentLength())) { + in.transferTo(o); + } + return null; + })); + } + + /** Best effort after a user is disabled or their roles change: the service unassigns chats they may no longer own. */ + public static void userChanged(RestTemplateCustomUtil rest, Long userId) { + try { + rest.postForEntity(rest.getURLforApiService(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_OWNERSHIP_USER_CHANGED), + Void.class, new UserChangedRequest(userId)); + } catch (RuntimeException e) { // the nightly job repairs a missed call + log.warn("WhatsApp ownership update for user {} failed: {}", userId, e.getClass().getSimpleName()); + } + } + + /** The service URL with the path id filled in and the caller context as query params. Ids are uuids only, so nothing else reaches the path. */ + private String url(String api, String id, Context c) { + String path = api; + if (id != null) { + if (!UUID_LIKE.matcher(id).matches()) throw coded(HttpStatus.NOT_FOUND, "Not found", "CONVERSATION_NOT_FOUND"); + path = api.replaceFirst("\\{[^}]+}", id); + } + return rest.getURLforApiService(path) + "?companyId=" + (c.companyId() == null ? "" : c.companyId()) + + "&userId=" + c.userId() + "&admin=" + c.admin(); + } + + /** User names by id, one lookup per distinct id per request. */ + // ponytail: N lookups for N distinct owners on a page (usually a handful); add a system findByIds if pages grow. + private Function names() { + Map cache = new HashMap<>(); + return id -> id == null ? null : cache.computeIfAbsent(id, k -> { + try { + ResponseEntity> found = rest.getForEntity( + rest.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, k); + Map u = found == null ? null : found.getBody(); + if (u == null) return null; + String name = (String.valueOf(u.getOrDefault("name", "")) + " " + + (u.get("surname") == null ? "" : u.get("surname"))).trim(); + return name.isEmpty() ? String.valueOf(u.get("username")) : name; + } catch (RestClientException e) { + return null; + } + }); + } + + private static ConversationView named(ConversationView v, Function names) { + if (v == null) return null; + return new ConversationView(v.uuid(), v.companyId(), v.contactWaId(), v.contactName(), v.leadUuid(), v.leadName(), + v.ownerUserId(), names.apply(v.ownerUserId()), v.ownerManual(), v.lastInboundAt(), v.lastMessageAt(), + v.lastMessagePreview(), v.windowOpen(), v.unreadCount()); + } + + /** Runs a service call; a 4xx from the service becomes the same status with its reason code and a message. */ + private static T call(java.util.function.Supplier s) { + try { + return s.get(); + } catch (HttpStatusCodeException e) { + HttpStatusCode status = e.getStatusCode(); + if (!status.is4xxClientError()) throw coded(HttpStatus.BAD_GATEWAY, "WhatsApp is unavailable. Try again.", "WHATSAPP_UNAVAILABLE"); + String code = detail(e); + return throwCoded(status, MESSAGES.getOrDefault(code, code), code); + } catch (RestClientException | UncheckedIOException e) { + throw coded(HttpStatus.BAD_GATEWAY, "WhatsApp is unavailable. Try again.", "WHATSAPP_UNAVAILABLE"); + } + } + + private static T throwCoded(HttpStatusCode status, String message, String code) { + CodedResponseStatusException ex = new CodedResponseStatusException(status, message, code); + ex.getBody().setProperty("message", message); + throw ex; + } + + private static String detail(HttpStatusCodeException e) { + try { + JsonNode body = JSON.readTree(e.getResponseBodyAsString()); + String d = body == null ? "" : body.path("detail").asText(""); + return d.isEmpty() ? "NOT_FOUND" : d; + } catch (IOException ex) { + return "NOT_FOUND"; + } + } + + private static CodedResponseStatusException coded(HttpStatusCode status, String message, String code) { + CodedResponseStatusException ex = new CodedResponseStatusException(status, message, code); + ex.getBody().setProperty("message", message); + return ex; + } + +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminWhatsAppControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminWhatsAppControllerTest.java new file mode 100644 index 0000000..0ceb699 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminWhatsAppControllerTest.java @@ -0,0 +1,155 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.whatsapp.AssignRequest; +import com.solvway.mobile.api.dto.whatsapp.SendMessageRequest; +import com.solvway.mobile.api.dto.whatsapp.UnreadCount; +import com.solvway.mobile.api.service.AdminWhatsAppService; +import com.solvway.mobile.api.useraccess.AdminModule; +import com.solvway.mobile.api.useraccess.Audited; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminWhatsAppControllerTest { + + @Mock private AdminWhatsAppService whatsapp; + @InjectMocks private AdminWhatsAppController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + private static List modules(Method m) { + AdminModule a = m.getAnnotation(AdminModule.class); + if (a == null) a = AdminWhatsAppController.class.getAnnotation(AdminModule.class); + return Arrays.asList(a.value()); + } + + @Test + void everyHandlerIsAuthenticatedAndGuardedByTheWhatsappModules() { + List handlers = Arrays.stream(AdminWhatsAppController.class.getDeclaredMethods()) + .filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList(); + assertThat(handlers).hasSize(11); + for (Method m : handlers) { + assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue(); + if (List.of("assign", "syncTemplates", "assignees").contains(m.getName())) { + assertThat(modules(m)).as(m.getName()).containsExactly("BO_WHATSAPP_ADMIN"); + } else { + assertThat(modules(m)).as(m.getName()).containsExactlyInAnyOrder("BO_WHATSAPP", "BO_WHATSAPP_ADMIN"); + } + } + } + + @Test + void readMarkersAreNotAuditedAndWritesNameTheirAction() throws Exception { + assertThat(AdminWhatsAppController.class.getMethod("read", String.class, Long.class).getAnnotation(Audited.class).skip()).isTrue(); + assertThat(AdminWhatsAppController.class.getMethod("send", String.class, SendMessageRequest.class, Long.class) + .getAnnotation(Audited.class).action()).isEqualTo("WHATSAPP_SEND"); + assertThat(AdminWhatsAppController.class.getMethod("assign", String.class, AssignRequest.class, Long.class) + .getAnnotation(Audited.class).action()).isEqualTo("WHATSAPP_ASSIGN"); + assertThat(AdminWhatsAppController.class.getMethod("syncTemplates", Long.class) + .getAnnotation(Audited.class).action()).isEqualTo("WHATSAPP_TEMPLATE_SYNC"); + } + + @Test + void sendBindsTheBodyAndPath() throws Exception { + mvc.perform(post("/api/admin/whatsapp/conversations/c1/messages").contentType(MediaType.APPLICATION_JSON) + .content("{\"template\":\"expo_followup\",\"language\":\"en\",\"params\":[\"A\",\"B\"]}")) + .andExpect(status().isOk()); + verify(whatsapp).send("c1", null, new SendMessageRequest(null, "expo_followup", "en", List.of("A", "B"))); + } + + @Test + void readAnswers204() throws Exception { + mvc.perform(post("/api/admin/whatsapp/conversations/c1/read")).andExpect(status().isNoContent()); + verify(whatsapp).read("c1", null); + } + + @Test + void unreadCountAndListPassTheirParameters() throws Exception { + when(whatsapp.unreadCount(null)).thenReturn(new UnreadCount(3)); + mvc.perform(get("/api/admin/whatsapp/unread-count")).andExpect(status().isOk()).andExpect(content().json("{\"count\":3}")); + mvc.perform(get("/api/admin/whatsapp/conversations").param("tab", "unassigned").param("q", "ais").param("companyId", "2")) + .andExpect(status().isOk()); + verify(whatsapp).list(2L, "unassigned", "ais", 0, 30); + } + + @Test + void mediaStreamsWithTheTypeAndNoCaching() throws Exception { + doAnswer(i -> { + AdminWhatsAppService.MediaOutput out = i.getArgument(2); + out.open("image/jpeg", 3).write(new byte[]{1, 2, 3}); + return null; + }).when(whatsapp).media(eq("m1"), isNull(), any()); + + mvc.perform(get("/api/admin/whatsapp/media/m1")) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", "image/jpeg")) + .andExpect(header().string("Cache-Control", "private, no-store")) + .andExpect(content().bytes(new byte[]{1, 2, 3})); + } + + @Test + void mediaASenderTypedAsHtmlIsADownloadThatCannotRun() throws Exception { + doAnswer(i -> { + AdminWhatsAppService.MediaOutput out = i.getArgument(2); + out.open("text/html", 1).write(new byte[]{1}); + return null; + }).when(whatsapp).media(eq("m2"), isNull(), any()); + + mvc.perform(get("/api/admin/whatsapp/media/m2")) + .andExpect(status().isOk()) + .andExpect(header().string("X-Content-Type-Options", "nosniff")) + .andExpect(header().string("Content-Security-Policy", "sandbox")) + .andExpect(header().string("Content-Disposition", "attachment")); + } + + @Test + void mediaImagesStayInline() throws Exception { + doAnswer(i -> { + AdminWhatsAppService.MediaOutput out = i.getArgument(2); + out.open("image/png", 1).write(new byte[]{1}); + return null; + }).when(whatsapp).media(eq("m3"), isNull(), any()); + + mvc.perform(get("/api/admin/whatsapp/media/m3")) + .andExpect(header().doesNotExist("Content-Disposition")) + .andExpect(header().string("X-Content-Type-Options", "nosniff")); + } + + @Test + void assigneesComeFromTheService() throws Exception { + when(whatsapp.assignees(null)).thenReturn(List.of(Map.of("id", 21, "name", "Siti"))); + mvc.perform(get("/api/admin/whatsapp/assignees")).andExpect(status().isOk()) + .andExpect(content().json("[{\"id\":21,\"name\":\"Siti\"}]", true)); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceWhatsAppTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceWhatsAppTest.java new file mode 100644 index 0000000..e1af4b9 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceWhatsAppTest.java @@ -0,0 +1,138 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.LocationHierarchy; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminRoleRef; +import com.solvway.mobile.api.dto.admin.AdminUserRequest; +import com.solvway.mobile.api.useraccess.AuditChanges; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.ResponseEntity; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.verify; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminUserServiceWhatsAppTest { + + private RestTemplateCustomUtil rest; + private AdminUserService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + AuditChanges.clear(); + rest = mock(RestTemplateCustomUtil.class); + AdminAuthenticationService auth = mock(AdminAuthenticationService.class); + service = new AdminUserService(rest, auth); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + User caller = new User(); + caller.setId(1L); + caller.setUsername("boss"); + caller.setCompanyId(7L); + LocationHierarchy branch = new LocationHierarchy(); + branch.setId(3L); + caller.setBranch(branch); + when(auth.loadUserByToken("tok")).thenReturn(caller); + when(auth.passesAdminPasswordRules(anyString())).thenReturn(true); + when(auth.setAdminPassword(any(), anyString())).thenReturn(1); + when(rest.getForEntity(eq("/company/findById/{id}"), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> ResponseEntity.ok(Map.of("id", (Object) i.getArgument(2), "code", "ins"))); + when(rest.getForEntity(eq("/role/findAll"), any(ParameterizedTypeReference.class))) + .thenReturn(ResponseEntity.ok(List.of(role(4, "ROLE_SALES"), role(5, "ROLE_OPS"), role(6, "ROLE_ACCOUNTS")))); + when(rest.getForEntity(eq("/user/findByUsername/{username}"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok().build()); + when(rest.getForEntity(eq("/user/findByEmailAndCompanyId/{email}?companyId={companyId}"), any(ParameterizedTypeReference.class), any(Object[].class))).thenReturn(ResponseEntity.ok().build()); + when(rest.getForEntity(eq("/user/findByEmailAndCompanyIdAndIdNot/{email}/{id}?companyId={companyId}"), any(ParameterizedTypeReference.class), any(Object[].class))).thenReturn(ResponseEntity.ok().build()); + when(rest.postForEntity(eq("/user/save"), any(ParameterizedTypeReference.class), any())) + .thenAnswer(i -> { + Map saved = new HashMap<>((Map) i.getArgument(2)); + saved.put("id", 9L); + return ResponseEntity.ok(saved); + }); + } + + @AfterEach + void close() { + http.close(); + AuditChanges.clear(); + } + + private static Map role(long id, String name) { + Map m = new HashMap<>(); + m.put("id", id); + m.put("name", name); + return m; + } + + private void stored(boolean enabled, Map... roles) { + Map u = new HashMap<>(); + u.put("id", 9L); + u.put("name", "Sam"); + u.put("username", "sam"); + u.put("email", "sam@x.com"); + u.put("enabled", enabled); + u.put("type", "A"); + u.put("companyId", 7L); + u.put("roles", List.of(roles)); + when(rest.getForEntity(eq("/user/findById/{id}"), any(ParameterizedTypeReference.class), eq(9L))).thenReturn(ResponseEntity.ok(u)); + } + + private static Map change(Object before, Object after) { + Map m = new HashMap<>(); + m.put("before", before); + m.put("after", after); + return m; + } + + private static final String USER_CHANGED = "/whatsapp/ownership/userChanged"; + + private void verifyUserChanged(int times) { + verify(rest, org.mockito.Mockito.times(times)).postForEntity(eq(USER_CHANGED), eq(Void.class), any()); + } + + @Test + void disablingAUserFreesTheirWhatsappChats() { + stored(true, role(4, "ROLE_SALES")); + service.update(9L, new AdminUserRequest(null, null, null, null, false, null)); + verifyUserChanged(1); + } + + @Test + void changingRolesFreesTheirWhatsappChats() { + stored(true, role(4, "ROLE_SALES")); + service.update(9L, new AdminUserRequest(null, null, null, null, null, List.of(new AdminRoleRef(5L, null)))); + verifyUserChanged(1); + } + + @Test + void otherEditsLeaveWhatsappAlone() { + stored(true, role(4, "ROLE_SALES")); + service.update(9L, new AdminUserRequest("Renamed", null, null, null, true, List.of(new AdminRoleRef(4L, null)))); + verifyUserChanged(0); + } + + @Test + void aWhatsappFailureDoesNotFailTheSave() { + stored(true, role(4, "ROLE_SALES")); + when(rest.postForEntity(eq(USER_CHANGED), eq(Void.class), any())).thenThrow(new org.springframework.web.client.ResourceAccessException("down")); + service.update(9L, new AdminUserRequest(null, null, null, null, false, null)); + verifyUserChanged(1); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminWhatsAppServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminWhatsAppServiceTest.java new file mode 100644 index 0000000..d1e5d4c --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminWhatsAppServiceTest.java @@ -0,0 +1,292 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.whatsapp.AssignRequest; +import com.solvway.mobile.api.dto.whatsapp.ConversationPage; +import com.solvway.mobile.api.dto.whatsapp.ConversationView; +import com.solvway.mobile.api.dto.whatsapp.MessageView; +import com.solvway.mobile.api.dto.whatsapp.SendMessageRequest; +import com.solvway.mobile.api.dto.whatsapp.StartChatRequest; +import com.solvway.mobile.api.dto.whatsapp.ThreadView; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.useraccess.AuditChanges; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminWhatsAppServiceTest { + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private AdminWhatsAppService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + auth = mock(AdminAuthenticationService.class); + service = new AdminWhatsAppService(rest, mock(RestTemplate.class), auth); + when(rest.getURLforApiService(any())).thenAnswer(i -> "http://gw/" + i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + AuditChanges.clear(); + } + + @AfterEach + void close() { + http.close(); + AuditChanges.clear(); + } + + private static User user(long id, Long companyId, long... roleIds) { + User u = new User(); + u.setId(id); + u.setUsername("u" + id); + u.setCompanyId(companyId); + List roles = new ArrayList<>(); + for (long r : roleIds) { + Role role = new Role(); + role.setId(r); + roles.add(role); + } + u.setRoles(roles); + return u; + } + + /** BO module list where role 7 holds BO_WHATSAPP and role 8 holds BO_WHATSAPP_ADMIN. */ + private void modules() { + when(rest.getForEntity(eq("http://gw//module/findAllByArea/{area}"), any(ParameterizedTypeReference.class), eq("BO"))) + .thenReturn(ResponseEntity.ok(List.of( + Map.of("name", "BO_WHATSAPP", "roles", List.of(Map.of("id", 7))), + Map.of("name", "BO_WHATSAPP_ADMIN", "roles", List.of(Map.of("id", 8)))))); + } + + private static ConversationView conv(Long owner, boolean manual) { + return new ConversationView("c1", 5L, "60123", "Aisyah", 9L, "Aisyah", owner, null, manual, null, null, null, true, 0); + } + + private String lastGetUrl() { + ArgumentCaptor url = ArgumentCaptor.forClass(String.class); + verify(rest).getForEntity(url.capture(), eq(ConversationPage.class), any(Object[].class)); + return url.getValue(); + } + + @Test + void staffAreScopedToTheirCompanyAsNonAdmin() { + when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7)); + modules(); + when(rest.getForEntity(anyString(), eq(ConversationPage.class), any(Object[].class))) + .thenReturn(ResponseEntity.ok(new ConversationPage(List.of(), 0, 0, 30))); + + service.list(99L, "mine", null, 0, 30); // a requested company is ignored for staff + + assertThat(lastGetUrl()).contains("companyId=5&userId=11&admin=false"); + } + + @Test + void whatsappAdminsAndSuperAdminsActAsAdmin() { + when(auth.loadUserByToken("tok")).thenReturn(user(12, 5L, 8)); + modules(); + when(rest.getForEntity(anyString(), eq(ConversationPage.class), any(Object[].class))) + .thenReturn(ResponseEntity.ok(new ConversationPage(List.of(), 0, 0, 30))); + service.list(null, "all", null, 0, 30); + assertThat(lastGetUrl()).contains("companyId=5&userId=12&admin=true"); + } + + @Test + void superAdminSeesTheRequestedCompanyOrAll() { + when(auth.loadUserByToken("tok")).thenReturn(user(1, null, 1)); + when(rest.getForEntity(anyString(), eq(ConversationPage.class), any(Object[].class))) + .thenReturn(ResponseEntity.ok(new ConversationPage(List.of(), 0, 0, 30))); + service.list(null, "all", null, 0, 30); + assertThat(lastGetUrl()).contains("companyId=&userId=1&admin=true"); + } + + @Test + void staffWithoutACompanyFailClosed() { + when(auth.loadUserByToken("tok")).thenReturn(user(13, null, 7)); + assertThatThrownBy(() -> service.list(null, "mine", null, 0, 30)) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(403)); + verify(rest, never()).getForEntity(anyString(), eq(ConversationPage.class), any(Object[].class)); + } + + @Test + void listFillsOwnerNamesWithOneLookupPerOwner() { + when(auth.loadUserByToken("tok")).thenReturn(user(1, null, 1)); + when(rest.getForEntity(anyString(), eq(ConversationPage.class), any(Object[].class))) + .thenReturn(ResponseEntity.ok(new ConversationPage(List.of(conv(21L, false), conv(21L, true), conv(null, false)), 3, 0, 30))); + when(rest.getForEntity(eq("http://gw//user/findById/{id}"), any(ParameterizedTypeReference.class), eq(21L))) + .thenReturn(ResponseEntity.ok(Map.of("name", "Siti", "surname", "Rahman", "username", "sales1"))); + + ConversationPage page = service.list(null, "all", null, 0, 30); + + assertThat(page.items()).extracting(ConversationView::ownerName).containsExactly("Siti Rahman", "Siti Rahman", null); + verify(rest, times(1)).getForEntity(eq("http://gw//user/findById/{id}"), any(ParameterizedTypeReference.class), eq(21L)); + } + + @Test + void sendNeedsExactlyOneOfTextOrTemplate() { + when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7)); + for (SendMessageRequest bad : new SendMessageRequest[]{ + new SendMessageRequest("hi", "expo_followup", "en", List.of()), + new SendMessageRequest(" ", null, null, null), null}) { + assertThatThrownBy(() -> service.send("c1", null, bad)) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(400)); + } + verify(rest, never()).postForEntity(anyString(), eq(MessageView.class), any()); + } + + @Test + void templateSendIsAuditedWithTheTemplateNameButNotTheText() { + when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7)); + modules(); + when(rest.postForEntity(anyString(), eq(MessageView.class), any())).thenReturn(ResponseEntity.ok(null)); + + service.send("c1", null, new SendMessageRequest(null, "expo_followup", "en", List.of("Aisyah", "Expo"))); + + verify(rest).postForEntity(eq("http://gw//whatsapp/conversations/c1/messages?companyId=5&userId=11&admin=false"), + eq(MessageView.class), any()); + assertThat(AuditChanges.current()).containsKeys("conversation", "template"); + assertThat(AuditChanges.current().toString()).contains("expo_followup").doesNotContain("Aisyah").doesNotContain("Expo"); + } + + @Test + void textSendAuditsNoText() { + when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7)); + modules(); + when(rest.postForEntity(anyString(), eq(MessageView.class), any())).thenReturn(ResponseEntity.ok(null)); + service.send("c1", null, new SendMessageRequest("my secret text", null, null, null)); + assertThat(AuditChanges.current().toString()).doesNotContain("secret"); + } + + @Test + void aPathIdThatIsNotAUuidNeverReachesTheService() { + when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7)); + modules(); + assertThatThrownBy(() -> service.send("../templates/sync", null, new SendMessageRequest("x", null, null, null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(404)); + verify(rest, never()).postForEntity(anyString(), eq(MessageView.class), any()); + } + + @Test + void serviceReasonsComeBackWithTheirStatusCodeAndMessage() { + when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7)); + modules(); + when(rest.postForEntity(anyString(), eq(MessageView.class), any())).thenThrow(HttpClientErrorException.create( + HttpStatus.CONFLICT, "Conflict", HttpHeaders.EMPTY, + "{\"status\":409,\"detail\":\"WINDOW_CLOSED\"}".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8)); + + assertThatThrownBy(() -> service.send("c1", null, new SendMessageRequest("hi", null, null, null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode().value()).isEqualTo(409); + assertThat(e.getCode()).isEqualTo("WINDOW_CLOSED"); + assertThat(e.getBody().getProperties()).containsEntry("message", "The 24-hour window has closed. Send a template."); + }); + } + + @Test + void anUnreachableServiceIs502() { + when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7)); + modules(); + when(rest.getForEntity(anyString(), eq(ConversationPage.class), any(Object[].class))).thenThrow(new ResourceAccessException("down")); + assertThatThrownBy(() -> service.list(null, "mine", null, 0, 30)) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(502)); + } + + @Test + void assignNeedsExactlyOneOfUserOrAutomaticAndAnAdmin() { + when(auth.loadUserByToken("tok")).thenReturn(user(12, 5L, 8)); + modules(); + for (AssignRequest bad : new AssignRequest[]{new AssignRequest(21L, true), new AssignRequest(null, false), null}) { + assertThatThrownBy(() -> service.assign("c1", null, bad)) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(400)); + } + when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7)); // staff + assertThatThrownBy(() -> service.assign("c1", null, new AssignRequest(21L, null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(403)); + verify(rest, never()).postForEntity(anyString(), eq(ConversationView.class), any()); + } + + @Test + void assignIsAuditedFromAndToOwner() { + when(auth.loadUserByToken("tok")).thenReturn(user(12, 5L, 8)); + modules(); + when(rest.getForEntity(anyString(), eq(ThreadView.class))).thenReturn(ResponseEntity.ok(new ThreadView(conv(21L, false), List.of(), false))); + when(rest.postForEntity(anyString(), eq(ConversationView.class), any())).thenReturn(ResponseEntity.ok(conv(22L, true))); + + service.assign("c1", null, new AssignRequest(22L, null)); + + Map owner = (Map) AuditChanges.current().get("ownerUserId"); + assertThat(owner).containsEntry("before", 21L).containsEntry("after", 22L); + } + + @Test + void startNeedsExactlyOneOfLeadOrEventLead() { + when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7)); + for (StartChatRequest bad : new StartChatRequest[]{new StartChatRequest(1L, 2L), new StartChatRequest(null, null), null}) { + assertThatThrownBy(() -> service.start(null, bad)) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(400)); + } + verifyNoInteractions(rest); + } + + @Test + void syncAndAssigneesAreForAdminsOnly() { + when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7)); + modules(); + assertThatThrownBy(() -> service.syncTemplates(null)) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(403)); + assertThatThrownBy(() -> service.assignees(null)) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(403)); + } + + @Test + void assigneesAreTheCompanysActiveWhatsappUsersWithNames() { + when(auth.loadUserByToken("tok")).thenReturn(user(12, 5L, 8)); + modules(); + when(rest.getForEntity(eq("http://gw//user/activeWithModule?companyId={companyId}&module={module}"), + any(ParameterizedTypeReference.class), eq(5L), eq("BO_WHATSAPP"))).thenReturn(ResponseEntity.ok(List.of(21L))); + when(rest.getForEntity(eq("http://gw//user/findById/{id}"), any(ParameterizedTypeReference.class), eq(21L))) + .thenReturn(ResponseEntity.ok(Map.of("name", "Siti", "username", "sales1"))); + + assertThat(service.assignees(null)).containsExactly(Map.of("id", 21L, "name", "Siti")); + } + + @Test + void userChangedIsBestEffort() { + when(rest.postForEntity(anyString(), eq(Void.class), any())).thenThrow(new ResourceAccessException("down")); + AdminWhatsAppService.userChanged(rest, 21L); // no exception + verify(rest).postForEntity(eq("http://gw//whatsapp/ownership/userChanged"), eq(Void.class), any()); + } +} -- 2.54.1 From 1d5e792e3d8ca2604495df2c2269810a3e1478ff Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 10:15:37 +0800 Subject: [PATCH 15/23] feat: whatsapp portal proxy, client service and polling hook Part of tasks 5.1/5.2 (not ticked): one catch-all proxy at /api/whatsapp (media served with nosniff and a sandbox CSP), typed client calls, and usePolling that pauses while the tab is hidden. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../api/whatsapp/[[...path]]/route.test.ts | 72 +++++++++++ .../app/api/whatsapp/[[...path]]/route.ts | 41 +++++++ .../app/lib/hooks/usePolling.test.ts | 51 ++++++++ .../app/lib/hooks/usePolling.ts | 28 +++++ .../app/lib/services/whatsapp.ts | 113 ++++++++++++++++++ 5 files changed, 305 insertions(+) create mode 100644 solvway-admin-portal/app/api/whatsapp/[[...path]]/route.test.ts create mode 100644 solvway-admin-portal/app/api/whatsapp/[[...path]]/route.ts create mode 100644 solvway-admin-portal/app/lib/hooks/usePolling.test.ts create mode 100644 solvway-admin-portal/app/lib/hooks/usePolling.ts create mode 100644 solvway-admin-portal/app/lib/services/whatsapp.ts diff --git a/solvway-admin-portal/app/api/whatsapp/[[...path]]/route.test.ts b/solvway-admin-portal/app/api/whatsapp/[[...path]]/route.test.ts new file mode 100644 index 0000000..ecaa71e --- /dev/null +++ b/solvway-admin-portal/app/api/whatsapp/[[...path]]/route.test.ts @@ -0,0 +1,72 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), callMobileApiBinary: vi.fn(), getToken: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi, callMobileApiBinary: mocks.callMobileApiBinary })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { GET, POST } from "./route"; + +type Req = Parameters[0]; +const ctx = (...path: string[]) => ({ params: Promise.resolve({ path: path.length ? path : undefined }) }); +const req = (url: string, init?: RequestInit) => new Request(`http://localhost${url}`, init) as unknown as Req; + +beforeEach(() => { + mocks.callMobileApi.mockReset(); + mocks.callMobileApiBinary.mockReset(); + mocks.getToken.mockReset(); + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ok: 1 } }); +}); + +describe("/api/whatsapp/[[...path]]", () => { + it("returns 401 without a session", async () => { + mocks.getToken.mockResolvedValue(null); + expect((await GET(req("/api/whatsapp/conversations"), ctx("conversations"))).status).toBe(401); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("forwards GETs with the query string", async () => { + await GET(req("/api/whatsapp/conversations?tab=mine&q=ais"), ctx("conversations")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/whatsapp/conversations?tab=mine&q=ais", { token: "jwt-abc" }); + }); + + it("forwards POST bodies", async () => { + await POST(req("/api/whatsapp/conversations/c1/messages", { method: "POST", body: JSON.stringify({ text: "hi" }) }), ctx("conversations", "c1", "messages")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/whatsapp/conversations/c1/messages", { method: "POST", body: { text: "hi" }, token: "jwt-abc" }); + }); + + it("answers an empty upstream body as JSON null", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: true, data: undefined }); + const res = await POST(req("/api/whatsapp/conversations/c1/read", { method: "POST" }), ctx("conversations", "c1", "read")); + expect(res.status).toBe(200); + expect(await res.json()).toBeNull(); + }); + + it("rejects dot segments", async () => { + expect((await GET(req("/api/whatsapp/x"), ctx("..", "users"))).status).toBe(400); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("passes upstream errors with their code", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: false, error: "The 24-hour window has closed. Send a template.", status: 409, code: "WINDOW_CLOSED" }); + const res = await POST(req("/api/whatsapp/conversations/c1/messages", { method: "POST", body: "{}" }), ctx("conversations", "c1", "messages")); + expect(res.status).toBe(409); + expect(((await res.json()) as Record).code).toBe("WINDOW_CLOSED"); + }); + + it("serves media as bytes that cannot run as a page", async () => { + mocks.callMobileApiBinary.mockResolvedValue({ ok: true, data: { body: new Uint8Array([1, 2]).buffer, contentType: "text/html", contentDisposition: "attachment" } }); + const res = await GET(req("/api/whatsapp/media/m1"), ctx("media", "m1")); + expect(mocks.callMobileApiBinary).toHaveBeenCalledWith("/api/admin/whatsapp/media/m1", { token: "jwt-abc" }); + expect(res.headers.get("Content-Type")).toBe("text/html"); + expect(res.headers.get("X-Content-Type-Options")).toBe("nosniff"); + expect(res.headers.get("Content-Security-Policy")).toBe("sandbox"); + expect(res.headers.get("Content-Disposition")).toBe("attachment"); + expect(res.headers.get("Cache-Control")).toBe("private, no-store"); + }); + + it("passes a media 410 through", async () => { + mocks.callMobileApiBinary.mockResolvedValue({ ok: false, error: "Media expired", status: 410, code: "MEDIA_EXPIRED" }); + expect((await GET(req("/api/whatsapp/media/m1"), ctx("media", "m1"))).status).toBe(410); + }); +}); diff --git a/solvway-admin-portal/app/api/whatsapp/[[...path]]/route.ts b/solvway-admin-portal/app/api/whatsapp/[[...path]]/route.ts new file mode 100644 index 0000000..25c4985 --- /dev/null +++ b/solvway-admin-portal/app/api/whatsapp/[[...path]]/route.ts @@ -0,0 +1,41 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { callMobileApi, callMobileApiBinary } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; + +// One proxy for every /api/admin/whatsapp endpoint; mobile-api owns validation and the BO_WHATSAPP guards. +type Ctx = { params: Promise<{ path?: string[] }> }; + +async function forward(req: NextRequest, { params }: Ctx, method?: "POST") { + const token = await getToken(); + if (!token) return unauthorized(); + const { path = [] } = await params; + if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path."); + const target = `/api/admin/whatsapp${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`; + + if (!method && path[0] === "media") { + // ponytail: buffers the file (mobile-api caps it at 100 MB); stream the upstream body if large documents become common. + const media = await callMobileApiBinary(target, { token }); + if (!media.ok) return errorResponse(media); + const { body, contentType, contentDisposition } = media.data; + return new NextResponse(body, { + headers: { + "Content-Type": contentType ?? "application/octet-stream", + ...(contentDisposition ? { "Content-Disposition": contentDisposition } : {}), + // The type is whatever the sender declared: never let it run as a page on this origin. + "X-Content-Type-Options": "nosniff", + "Content-Security-Policy": "sandbox", + "Cache-Control": "private, no-store", + }, + }); + } + + const result = method + ? await callMobileApi(target, { method, body: await req.json().catch(() => ({})), token }) + : await callMobileApi(target, { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data ?? null); +} + +export const GET = (req: NextRequest, ctx: Ctx) => forward(req, ctx); +export const POST = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "POST"); diff --git a/solvway-admin-portal/app/lib/hooks/usePolling.test.ts b/solvway-admin-portal/app/lib/hooks/usePolling.test.ts new file mode 100644 index 0000000..2caff74 --- /dev/null +++ b/solvway-admin-portal/app/lib/hooks/usePolling.test.ts @@ -0,0 +1,51 @@ +// @vitest-environment jsdom +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { renderHook } from "@testing-library/react"; +import { act } from "react"; +import { usePolling } from "./usePolling"; + +let hidden = false; +beforeEach(() => { + vi.useFakeTimers(); + hidden = false; + Object.defineProperty(document, "hidden", { configurable: true, get: () => hidden }); +}); +afterEach(() => vi.useRealTimers()); + +describe("usePolling", () => { + it("runs now and then every interval", () => { + const fn = vi.fn(); + renderHook(() => usePolling(fn, 1000)); + expect(fn).toHaveBeenCalledTimes(1); + act(() => { vi.advanceTimersByTime(3000); }); + expect(fn).toHaveBeenCalledTimes(4); + }); + + it("skips ticks while the tab is hidden and catches up when it shows", () => { + const fn = vi.fn(); + renderHook(() => usePolling(fn, 1000)); + hidden = true; + act(() => { vi.advanceTimersByTime(3000); }); + expect(fn).toHaveBeenCalledTimes(1); + hidden = false; + act(() => { document.dispatchEvent(new Event("visibilitychange")); }); + expect(fn).toHaveBeenCalledTimes(2); + }); + + it("stops after unmount and runs when the named window event fires", () => { + const fn = vi.fn(); + const { unmount } = renderHook(() => usePolling(fn, 1000, "whatsapp-unread-changed")); + act(() => { window.dispatchEvent(new Event("whatsapp-unread-changed")); }); + expect(fn).toHaveBeenCalledTimes(2); + unmount(); + act(() => { vi.advanceTimersByTime(3000); window.dispatchEvent(new Event("whatsapp-unread-changed")); }); + expect(fn).toHaveBeenCalledTimes(2); + }); + + it("does nothing when disabled", () => { + const fn = vi.fn(); + renderHook(() => usePolling(fn, 1000, undefined, false)); + act(() => { vi.advanceTimersByTime(3000); }); + expect(fn).not.toHaveBeenCalled(); + }); +}); diff --git a/solvway-admin-portal/app/lib/hooks/usePolling.ts b/solvway-admin-portal/app/lib/hooks/usePolling.ts new file mode 100644 index 0000000..fc7b007 --- /dev/null +++ b/solvway-admin-portal/app/lib/hooks/usePolling.ts @@ -0,0 +1,28 @@ +import { useEffect, useRef } from "react"; + +/** + * Calls `fn` now, then every `ms` while the tab is visible, again when the tab shows, and whenever the + * optional window event fires. The latest `fn` is used without restarting the timer. + */ +// ponytail: polling (30 s list, 10 s thread); server-sent events if the delay ever matters. +export function usePolling(fn: () => void, ms: number, refreshEvent?: string, enabled = true) { + const latest = useRef(fn); + useEffect(() => { + latest.current = fn; + }); + useEffect(() => { + if (!enabled) return; + const run = () => { + if (!document.hidden) latest.current(); + }; + run(); + const id = window.setInterval(run, ms); + document.addEventListener("visibilitychange", run); + if (refreshEvent) window.addEventListener(refreshEvent, run); + return () => { + window.clearInterval(id); + document.removeEventListener("visibilitychange", run); + if (refreshEvent) window.removeEventListener(refreshEvent, run); + }; + }, [ms, refreshEvent, enabled]); +} diff --git a/solvway-admin-portal/app/lib/services/whatsapp.ts b/solvway-admin-portal/app/lib/services/whatsapp.ts new file mode 100644 index 0000000..b27703a --- /dev/null +++ b/solvway-admin-portal/app/lib/services/whatsapp.ts @@ -0,0 +1,113 @@ +import { apiGet, apiPost } from "@/app/lib/clientApi"; + +export type WhatsAppTab = "mine" | "unassigned" | "all"; + +export interface WhatsAppConversation { + uuid: string; + companyId: number; + contactWaId: string; + contactName: string | null; + leadUuid: string | null; + leadName: string | null; + ownerUserId: number | null; + ownerName: string | null; + ownerManual: boolean; + lastInboundAt: string | null; + lastMessageAt: string | null; + lastMessagePreview: string | null; + windowOpen: boolean; + unreadCount: number; +} + +export interface WhatsAppMessage { + uuid: string; + direction: "IN" | "OUT"; + type: string; + body: string | null; + templateName: string | null; + mediaMime: string | null; + mediaFilename: string | null; + locationLat: number | null; + locationLng: number | null; + locationName: string | null; + status: "pending" | "sent" | "delivered" | "read" | "failed" | null; + errorCode: string | null; + errorTitle: string | null; + sentByUserId: number | null; + createdAt: string; + statusAt: string | null; +} + +export interface WhatsAppTemplate { + name: string; + language: string; + category: string; + bodyText: string; + paramCount: number; + supported: boolean; +} + +export interface WhatsAppPage { + items: WhatsAppConversation[]; + total: number; + page: number; + size: number; +} + +export interface WhatsAppThread { + conversation: WhatsAppConversation; + messages: WhatsAppMessage[]; + hasOlder: boolean; +} + +const q = (params: Record) => { + const s = new URLSearchParams(); + for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== null && v !== "") s.set(k, String(v)); + const out = s.toString(); + return out ? `?${out}` : ""; +}; + +const c = (uuid: string) => encodeURIComponent(uuid); + +export const listConversations = (tab: WhatsAppTab, search: string, page: number, companyId?: number | null) => + apiGet(`/api/whatsapp/conversations${q({ tab, q: search, page, companyId })}`); + +export const getThread = (uuid: string, before?: string, companyId?: number | null) => + apiGet(`/api/whatsapp/conversations/${c(uuid)}${q({ before, companyId })}`); + +export const sendText = (uuid: string, text: string, companyId?: number | null) => + apiPost(`/api/whatsapp/conversations/${c(uuid)}/messages${q({ companyId })}`, { text }); + +export const sendTemplate = (uuid: string, template: WhatsAppTemplate, params: string[], companyId?: number | null) => + apiPost(`/api/whatsapp/conversations/${c(uuid)}/messages${q({ companyId })}`, { + template: template.name, + language: template.language, + params, + }); + +export const markRead = (uuid: string, companyId?: number | null) => + apiPost(`/api/whatsapp/conversations/${c(uuid)}/read${q({ companyId })}`); + +export const assignConversation = (uuid: string, userId: number | null, companyId?: number | null) => + apiPost( + `/api/whatsapp/conversations/${c(uuid)}/assign${q({ companyId })}`, + userId === null ? { automatic: true } : { userId }, + ); + +/** Exactly one of leadUuid or eventLeadUuid. */ +export const startChat = (target: { leadUuid: string } | { eventLeadUuid: string }) => + apiPost("/api/whatsapp/start", target); + +export const listTemplates = (companyId?: number | null) => + apiGet(`/api/whatsapp/templates${q({ companyId })}`); + +export const syncTemplates = (companyId?: number | null) => + apiPost(`/api/whatsapp/templates/sync${q({ companyId })}`); + +export const unreadCount = () => apiGet<{ count: number }>("/api/whatsapp/unread-count"); + +export const listAssignees = (companyId?: number | null) => + apiGet<{ id: number; name: string | null }[]>(`/api/whatsapp/assignees${q({ companyId })}`); + +export const mediaUrl = (messageUuid: string, companyId?: number | null) => + `/api/whatsapp/media/${c(messageUuid)}${q({ companyId })}`; -- 2.54.1 From f7bfea44c7f633f7dd11ccb5b2deaa7cef97c8ad Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 10:51:02 +0800 Subject: [PATCH 16/23] feat(portal): WhatsApp sidebar entry with unread badge, start-chat buttons on leads The badge polls the unread count every 30 s and on whatsapp-unread-changed, only for users holding BO_WHATSAPP. The button sits next to the mobile number on Leads and Event leads; it opens the chat when the starter owns it and otherwise says who does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- .../app/components/app/Sidebar.tsx | 55 ++++++++-- .../components/app/Sidebar.whatsapp.test.tsx | 100 ++++++++++++++++++ .../components/app/WhatsAppButton.test.tsx | 65 ++++++++++++ .../app/components/app/WhatsAppButton.tsx | 60 +++++++++++ .../app/components/app/icon-map.ts | 3 +- .../app/event-leads/[eventUuid]/page.tsx | 8 +- .../[eventUuid]/page.whatsapp.test.tsx | 57 ++++++++++ solvway-admin-portal/app/leads/page.tsx | 13 ++- .../app/leads/page.whatsapp.test.tsx | 44 ++++++++ solvway-admin-portal/app/lib/aclSidebar.ts | 2 +- .../app/lib/i18n/defaultMessages.ts | 6 ++ 11 files changed, 402 insertions(+), 11 deletions(-) create mode 100644 solvway-admin-portal/app/components/app/Sidebar.whatsapp.test.tsx create mode 100644 solvway-admin-portal/app/components/app/WhatsAppButton.test.tsx create mode 100644 solvway-admin-portal/app/components/app/WhatsAppButton.tsx create mode 100644 solvway-admin-portal/app/event-leads/[eventUuid]/page.whatsapp.test.tsx create mode 100644 solvway-admin-portal/app/leads/page.whatsapp.test.tsx diff --git a/solvway-admin-portal/app/components/app/Sidebar.tsx b/solvway-admin-portal/app/components/app/Sidebar.tsx index 4657ed4..a89a064 100644 --- a/solvway-admin-portal/app/components/app/Sidebar.tsx +++ b/solvway-admin-portal/app/components/app/Sidebar.tsx @@ -12,6 +12,8 @@ import { cn } from "@/app/lib/utils"; import { Button } from "@/app/components/ui/button"; import { Popover, PopoverContent, PopoverTrigger } from "@/app/components/ui/popover"; import PoweredBy from "./PoweredBy"; +import { usePolling } from "@/app/lib/hooks/usePolling"; +import { unreadCount } from "@/app/lib/services/whatsapp"; // The wordmark is the brand name: data, not translatable copy. const BRAND = "Co-Lite"; @@ -26,7 +28,26 @@ const BRAND = "Co-Lite"; type NavProps = { trail: SidebarLink[]; onNavigate?: () => void }; -function NavNode({ link, depth, trail, onNavigate }: { link: SidebarLink; depth: number } & NavProps) { +const WHATSAPP = "BO_WHATSAPP"; + +/** Unread WhatsApp chats for the signed-in user; 0 without the module. A failed read keeps the last count. */ +function useWhatsAppUnread(enabled: boolean) { + const [count, setCount] = useState(0); + usePolling( + () => { + unreadCount().then((r) => setCount(r?.count ?? 0), () => {}); + }, + 30_000, + "whatsapp-unread-changed", + enabled, + ); + return enabled ? count : 0; +} + +const badgeText = (n: number) => (n > 99 ? "99+" : String(n)); +const badgeClass = "rounded-full bg-primary px-1.5 text-xs leading-5 font-semibold text-primary-foreground tabular-nums"; + +function NavNode({ link, depth, trail, onNavigate, badge = 0 }: { link: SidebarLink; depth: number; badge?: number } & NavProps) { const t = useT(); const Icon = iconFor(link.iconName); const hasChildren = link.children.length > 0; @@ -38,6 +59,7 @@ function NavNode({ link, depth, trail, onNavigate }: { link: SidebarLink; depth: 0 ? `${t(link.name)} ${t("WaUnread", { n: badge })}` : undefined} onClick={onNavigate} className={cn( "flex items-center gap-3 rounded-lg px-3 transition-colors", @@ -53,6 +75,11 @@ function NavNode({ link, depth, trail, onNavigate }: { link: SidebarLink; depth: reference it returns is stable across renders for a given iconName. */} {Icon &&