From e2fdb8a17116c3f1ee45cdfec26fdcc09a30c1ce Mon Sep 17 00:00:00 2001 From: Rogee Date: Sat, 6 Jun 2026 20:10:06 +0800 Subject: [PATCH] feat(channels): align whatsapp calling toggles --- cmd/route_parity/main.go | 2 + docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md | 16 ++-- docs/parity/gochat_routes.txt | 4 +- docs/parity/route_parity.md | 4 +- internal/channel/whatsapp/service.go | 73 ++++++++++++++- internal/channel/whatsapp/service_test.go | 31 +++++++ internal/handler/api/v1/inbox_handler.go | 54 +++++++++++ internal/handler/api/v1/inbox_handler_test.go | 80 ++++++++++++++++ internal/router/router.go | 4 + internal/service/inbox_service.go | 91 +++++++++++++++++++ internal/service/inbox_service_test.go | 78 ++++++++++++++++ .../whatsapp_authorization_service_test.go | 9 ++ 12 files changed, 436 insertions(+), 10 deletions(-) diff --git a/cmd/route_parity/main.go b/cmd/route_parity/main.go index ef773d5e..6471bfe9 100644 --- a/cmd/route_parity/main.go +++ b/cmd/route_parity/main.go @@ -201,6 +201,8 @@ var criticalRoutes = []route{ {Method: "GET", Path: "/api/v1/accounts/:account_id/inboxes/:inbox_id/health", Controller: "api/v1/accounts/inboxes#health", Source: "routes.rb:259"}, {Method: "POST", Path: "/api/v1/accounts/:account_id/inboxes/:inbox_id/register_webhook", Controller: "api/v1/accounts/inboxes#register_webhook", Source: "routes.rb:260"}, {Method: "POST", Path: "/api/v1/accounts/:account_id/inboxes/:inbox_id/reset_secret", Controller: "api/v1/accounts/inboxes#reset_secret", Source: "routes.rb:262"}, + {Method: "POST", Path: "/api/v1/accounts/:account_id/inboxes/:inbox_id/enable_whatsapp_calling", Controller: "api/v1/accounts/inboxes#enable_whatsapp_calling", Source: "routes.rb:266"}, + {Method: "POST", Path: "/api/v1/accounts/:account_id/inboxes/:inbox_id/disable_whatsapp_calling", Controller: "api/v1/accounts/inboxes#disable_whatsapp_calling", Source: "routes.rb:267"}, {Method: "POST", Path: "/api/v1/accounts/:account_id/inbox_members/", Controller: "api/v1/accounts/inbox_members#create", Source: "routes.rb:275"}, {Method: "GET", Path: "/api/v1/accounts/:account_id/inbox_members/:inbox_id", Controller: "api/v1/accounts/inbox_members#show", Source: "routes.rb:275"}, diff --git a/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md b/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md index 2d522adb..128af1c4 100644 --- a/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md +++ b/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md @@ -49,16 +49,16 @@ Hermes task landing checklist: ## Current Baseline -- Current tracking checkpoint: 2026-06-06 WhatsApp embedded signup authorization parity checkpoint, prepared as `feat(channels): align whatsapp authorization`. -- Latest implementation checkpoint: this checkpoint, prepared as `feat(channels): align whatsapp authorization`. +- Current tracking checkpoint: 2026-06-06 WhatsApp calling toggle parity checkpoint, prepared as `feat(channels): align whatsapp calling toggles`. +- Latest implementation checkpoint: this checkpoint, prepared as `feat(channels): align whatsapp calling toggles`. - Latest documentation/tooling checkpoint: this tracker update for P3.24 plus the landed parity tracker history; this document is the active follow-up plan and supersedes `.hermes/plans/*`. - Plan landing status: complete for the current known Hermes plans and user-confirmed scope. Future work should update this file directly instead of opening a parallel tracker. -- Worktree status at this implementation checkpoint: WhatsApp embedded signup authorization from `reference/chatwoot/config/routes.rb:339`, `Api::V1::Accounts::Whatsapp::AuthorizationsController`, `Whatsapp::EmbeddedSignupService`, channel creation/reauthorization/token/phone validation services, request specs, and reused dashboard `whatsappChannel.js` are implemented. GoChat now exposes authenticated-agent/admin `POST /api/v1/accounts/:account_id/whatsapp/authorization`, validates `code/business_id/waba_id`, creates WhatsApp Cloud inboxes, supports inbox reauthorization, returns Chatwoot `{ success, id, name, channel_type, message? }` payloads, and keeps the previously aligned Twitter/Google/Microsoft/Instagram/TikTok/Notion behavior intact. Live API/browser/enterprise smoke still needs the full PostgreSQL/Redis/Meilisearch/GoChat/Vite/Chrome stack. +- Worktree status at this implementation checkpoint: WhatsApp calling toggle parity from `reference/chatwoot/config/routes.rb:266-267`, `enterprise/app/controllers/enterprise/api/v1/accounts/inboxes_controller.rb`, `app/models/channel/whatsapp.rb`, `enterprise/app/services/enterprise/whatsapp/providers/whatsapp_cloud_service.rb`, `app/services/whatsapp/webhook_setup_service.rb`, `app/policies/inbox_policy.rb`, and reused dashboard `api/inboxes.js` is implemented. GoChat now exposes administrator-gated `POST /api/v1/accounts/:account_id/inboxes/:inbox_id/enable_whatsapp_calling` and `disable_whatsapp_calling`, requires WhatsApp Cloud API support, requires `channel_voice` only for enable, calls Meta phone-number `/settings` with `{ calling: { status: "ENABLED" } }`, persists `provider_config.calling_enabled`, updates inbox `voice_enabled`, re-registers webhook fields with `calls` on enable, best-effort drops `calls` on disable, and returns empty `200 OK` or `422 { error }` like Chatwoot. WhatsApp embedded signup authorization remains implemented from the previous checkpoint. Live API/browser/enterprise smoke still needs the full PostgreSQL/Redis/Meilisearch/GoChat/Vite/Chrome stack. - Next executable implementation checkpoint: continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke from fresh reference/smoke evidence. - `go test ./...` passes when run outside the restricted socket sandbox; focused Shopify handler/service tests pass in the sandbox. -- Route dump succeeds with `948` registered routes after WhatsApp authorization tracking. +- Route dump succeeds with `950` registered routes after WhatsApp calling route tracking. - Route parity artifacts now exist under `docs/parity/` and are generated by `cmd/route_parity`. -- Tracked frontend-critical route audit covers 411 Chatwoot routes: 398 exact, 0 method-compatible, 13 parameter-compatible, 0 missing. The 13 parameter-compatible routes are Gin-internal parameter-name differences for nested AgentCapacityPolicy users/inbox limits, dashboard app member `:id` names, plus the public article `.md`/`.png` suffixes served through the same external article route dispatcher. +- Tracked frontend-critical route audit covers 413 Chatwoot routes: 400 exact, 0 method-compatible, 13 parameter-compatible, 0 missing. The 13 parameter-compatible routes are Gin-internal parameter-name differences for nested AgentCapacityPolicy users/inbox limits, dashboard app member `:id` names, plus the public article `.md`/`.png` suffixes served through the same external article route dispatcher. - `/api/v1/widget` stubs are burned down and public inbox/contact/conversation/message core flows are backed by real handlers. - Handler test stability fixes are committed into the baseline before feature parity work continues. - `.codegraph/` is generated indexing output and is not part of tracked product code. @@ -140,6 +140,7 @@ This table is the shortest authoritative handoff view. If an older lower section | Priority | Workstream | Current state | Next checkpoint | Commit close rule | | --- | --- | --- | --- | --- | +| 0 | P3.33 WhatsApp calling toggle parity | Implemented for reused dashboard inbox voice settings: `POST /api/v1/accounts/:account_id/inboxes/:inbox_id/enable_whatsapp_calling` and `disable_whatsapp_calling` are registered and tracked from `routes.rb:266-267`, administrator-gated like `InboxPolicy`, scoped to WhatsApp Cloud API inboxes, enable requires account feature flag `channel_voice`, enable calls Meta phone-number `/settings` with `ENABLED`, webhook setup subscribes `messages/smb_message_echoes/calls`, provider config persists `calling_enabled: true`, disable persists `calling_enabled: false` without calling Meta settings, and webhook re-registration without `calls` is best-effort. Handlers return empty `200 OK` on success and `422 { error }` for unsupported inbox, missing feature flag, provider setup, or Meta update errors. | Keep in Review; reopen only if live WhatsApp calling settings smoke exposes Meta API version/base URL drift, webhook subscribed-field behavior drift, `voice_enabled` serializer drift, or frontend error/status drift beyond the inspected enterprise controller/model/provider/frontend contract. | Focused WhatsApp calling service/channel/handler tests, router/route-parity tests, route dump/parity regeneration (`950` routes; `400 exact`, `13 parameter-compatible`, `0 missing out of 413`), full `go test ./...`, and `git diff --check` must pass before commit. | | 0 | P3.32 WhatsApp authorization parity | Implemented for reused dashboard WhatsApp embedded signup and reauthorization flow: `POST /api/v1/accounts/:account_id/whatsapp/authorization` is registered and tracked from `routes.rb:339`, authenticated agents and administrators can call it like Chatwoot's controller, missing `code`, `business_id`, and `waba_id` return `422 { success: false, error }`, new authorization exchanges the Meta embedded-signup code, fetches WABA phone info, validates token WABA access, creates a WhatsApp Cloud channel/inbox with embedded-signup provider config, sets up the webhook URL, and returns raw `{ success: true, id, name, channel_type: "whatsapp" }`; reauthorization validates the same phone number, refreshes provider config/access token/phone ID, clears `reauthorization_required`, updates inbox channel config/name, and returns the same raw payload plus the reauthorization success message. | Keep in Review; reopen only if live WhatsApp embedded-signup smoke exposes Meta API version/config-source drift, Graph API error-body wording drift, webhook setup side-effect drift, health-check reauthorization prompting drift, or frontend payload drift beyond the inspected controller/spec/service/frontend contract. | Focused WhatsApp authorization service tests, handler/router/route-parity tests, route dump/parity regeneration (`948` routes; `398 exact`, `13 parameter-compatible`, `0 missing out of 411`), full `go test ./...`, and `git diff --check` must pass before commit. | | 0 | P3.31 Instagram/TikTok authorization parity | Implemented for reused dashboard Instagram and TikTok connect/reauthorization flows: `POST /api/v1/accounts/:account_id/instagram/authorization` and `POST /api/v1/accounts/:account_id/tiktok/authorization` are registered and tracked from `routes.rb:327/331`, both routes are administrator-gated like Chatwoot's shared OAuth authorization controller, responses return raw `{ success: true, url }`, Instagram authorize URLs target `https://api.instagram.com/oauth/authorize` with Chatwoot's required Instagram business scopes, `enable_fb_login=0`, and `force_authentication=1`, TikTok authorize URLs target `https://www.tiktok.com/v2/auth/authorize` with Chatwoot's required TikTok business scopes and `client_key`, and both sign account callback state with optional `return_to`. | Keep in Review; reopen only if live Instagram/TikTok OAuth smoke exposes GlobalID state compatibility requirements beyond signed callback state, provider config-source drift, onboarding return routing drift, or frontend payload drift beyond the inspected authorization controllers/specs/frontend clients. | Focused social authorization handler/router/route tests, route dump/parity regeneration (`947` routes; `397 exact`, `13 parameter-compatible`, `0 missing out of 410`), full `go test ./...`, and `git diff --check` must pass before commit. | | 0 | P3.30 Google/Microsoft authorization parity | Implemented for reused dashboard Gmail/Outlook connect and reauthorization flows: `POST /api/v1/accounts/:account_id/google/authorization` and `POST /api/v1/accounts/:account_id/microsoft/authorization` are registered and tracked from `routes.rb:319/323`, both routes are administrator-gated like Chatwoot's shared OAuth authorization controller, responses return raw `{ success: true, url }`, Google authorize URLs target `https://accounts.google.com/o/oauth2/auth` with `email profile https://mail.google.com/`, `prompt=consent`, and `access_type=offline`, Microsoft authorize URLs target `https://login.microsoftonline.com/common/oauth2/v2.0/authorize` with Chatwoot's IMAP/SMTP/openid/profile/email scope and no prompt, and both sign account callback state for existing email OAuth callbacks. | Keep in Review; reopen only if live Gmail/Outlook OAuth smoke exposes GlobalID state compatibility requirements beyond signed callback state, provider config-source drift, onboarding return routing drift, or frontend payload drift beyond the inspected authorization controllers/specs/frontend clients. | Focused email OAuth authorization handler/router/route tests, route dump/parity regeneration (`945` routes; `395 exact`, `13 parameter-compatible`, `0 missing out of 408`), full `go test ./...`, and `git diff --check` must pass before commit. | @@ -151,7 +152,7 @@ This table is the shortest authoritative handoff view. If an older lower section | 0 | P3.24 Slack integration parity | Implemented for reused dashboard Slack settings flow: no-trailing and trailing singleton routes are registered for create/update/delete, `PUT` and `PATCH` update both work, create accepts frontend `code` and exchanges it for a Slack access token, hooks are persisted with `app_id: slack` and disabled status, update accepts frontend `reference_id`, fetches real private/public Slack channels with pagination, joins public channels, persists `reference_id/settings.channel_name/status`, create/update return raw Chatwoot app payloads with hooks, list-all returns raw channel arrays, invalid channels return Chatwoot's `422 { error }`, and delete returns empty `200 OK`. | Keep in Review; reopen only if live Slack OAuth/channel smoke exposes OAuth redirect, provider error, app serializer, or Slack channel pagination drift beyond the inspected controller/builder/spec/frontend contract. | Focused Slack handler/service tests, route dump/parity regeneration, sandbox focused `go test`, escalated full `go test ./...`, and `git diff --check` passed. | | 0 | P3.23 nested contact inbox creation API | Implemented for Chatwoot nested contact inbox creation: raw JSON/form/query params are accepted, contact and inbox are account-scoped, missing source IDs are generated through Chatwoot channel rules, duplicate contact+inbox+source rows are returned idempotently, `hmac_verified` is persisted on creation, and the response is raw `{ source_id, inbox }` rather than the local model/envelope. | Keep in Review; reopen only if live CRM/new-conversation smoke exposes inbox access-policy, unsupported channel, or serializer drift beyond the inspected controller/builder/Jbuilder contract. | Focused nested ContactInbox handler/service/repository tests, route parity check, full `go test ./...`, and `git diff --check` passed. | | 1 | P3.2a invitation/confirmation mail parity | Implemented for current non-SSO reference behavior: profile resend is no longer a TODO-only log, new invited agents and unconfirmed invited profile resends generate reset-password invitation links, normal unconfirmed profile resends generate confirmation links, `users.unconfirmed_email` is modeled for email-update routing, and fakeable/environment SMTP mailers keep default tests offline. | Keep in Review; reopen only if reused frontend smoke or fresh reference evidence exposes additional Devise confirmation states outside excluded SSO/SAML/LDAP/OIDC variants. | Focused profile and agent invitation tests, combined handler/service/repository/router/migrate/app tests, full `go test ./...`, and `git diff --check` passed. | -| 2 | Phase 2/3 drift | Tracked route parity is 0 missing for the current 411-route critical set; dashboard `/app` shell routes from `routes.rb:19-20`, `.well-known` app association and custom-domain challenge routes from `routes.rb:657-660`, Twilio callback routes from `routes.rb:639-640`, enterprise Twilio voice routes from `routes.rb:643-646`, root Linear/Shopify/Notion OAuth callback routes from `routes.rb:630/634/654`, root Twitter/Google/Microsoft/Instagram/TikTok callback routes from `routes.rb:626/649-652`, assignment policy routes from `routes.rb:306-313`, help-center portal/category/article routes from `routes.rb:385-404`, public help-center portal/sitemap/article/category/search/article-detail routes from `routes.rb:590-601`, enterprise contact outbound voice call from `routes.rb:216`, account agent-bot routes from `routes.rb:94-97`, account webhook routes from `routes.rb:342`, account integration app/hook routes from `routes.rb:345-348`, account Slack routes from `routes.rb:350-352`, account Dyte routes from `routes.rb:357-358`, account Shopify routes from `routes.rb:361-364`, account Linear routes from `routes.rb:365-373`, account Notion authorization/destroy routes from `routes.rb:335/379`, account Twitter/Google/Microsoft/Instagram/TikTok authorization routes from `routes.rb:315/319/323/327/331`, account WhatsApp authorization route from `routes.rb:339`, dashboard app routes from `routes.rb:130`, canned response routes from `routes.rb:114`, notification subscription routes from `routes.rb:440`, team/team-member routes from `routes.rb:296-300`, conversation participant routes from `routes.rb:150`, conversation direct upload route from `routes.rb:151`, conversation draft message routes from `routes.rb:152`, conversation inbox assistant route from `routes.rb:165`, conversation reporting events route from `routes.rb:166`, and account reporting events route from `routes.rb:234` are now explicitly tracked. Notification list/action serializers, user notification-settings raw payloads, campaigns raw payload/display-id routes, Devise password reset/confirmation payloads, CRM shared attachment payloads plus fixed 100-row attachment pagination, account/settings payloads, assignable-agent payloads, agent index full-list behavior, agent create/update/delete defaults/errors/scope, account agent-bot route/payload/mutation behavior, account webhook payload/mutation behavior, integration app/hook payload behavior, account Slack OAuth/channel payload behavior, account Dyte create/join payload behavior, account Shopify customer-order payload behavior, account Linear GraphQL issue payload behavior, account Notion authorization/destroy behavior, account Twitter/Google/Microsoft/Instagram/TikTok authorization behavior, account WhatsApp embedded-signup creation and reauthorization behavior, dashboard app raw payload/serializer behavior, canned response raw payload/search/delete behavior, notification subscription payload behavior, team update/frontend route behavior, conversation participant route/payload/final-set update behavior, conversation direct upload ActiveStorage behavior, conversation draft message Redis-key-equivalent behavior, conversation inbox assistant Copilot payload behavior, conversation reporting-event raw array behavior, account reporting-events payload/filter/pagination behavior, label CRUD payloads, custom filters, custom attribute definitions, contact outbound voice calls, assignment policy CRUD and inbox binding payloads, Twilio inbound/status callbacks, enterprise Twilio voice callbacks, Linear/Shopify/Notion root integration callbacks, Shopify OAuth auth redirects, root channel OAuth callbacks, help-center portal/category/article payloads, dashboard app shell route behavior, app association JSON payloads, Cloudflare custom hostname verification, public widget popular-article lists, public help-center category list/show payloads, public portal show/default-locale payloads, public portal search payloads, public article show/markdown/tracking routes, and public sitemap XML now match the inspected Chatwoot contract. | Continue the next evidence-backed route/controller/serializer drift after WhatsApp authorization parity or from B12 findings. | Regenerate parity artifacts when routes change and add endpoint-family fixture tests. | +| 2 | Phase 2/3 drift | Tracked route parity is 0 missing for the current 413-route critical set; dashboard `/app` shell routes from `routes.rb:19-20`, `.well-known` app association and custom-domain challenge routes from `routes.rb:657-660`, Twilio callback routes from `routes.rb:639-640`, enterprise Twilio voice routes from `routes.rb:643-646`, root Linear/Shopify/Notion OAuth callback routes from `routes.rb:630/634/654`, root Twitter/Google/Microsoft/Instagram/TikTok callback routes from `routes.rb:626/649-652`, assignment policy routes from `routes.rb:306-313`, help-center portal/category/article routes from `routes.rb:385-404`, public help-center portal/sitemap/article/category/search/article-detail routes from `routes.rb:590-601`, enterprise contact outbound voice call from `routes.rb:216`, account agent-bot routes from `routes.rb:94-97`, account webhook routes from `routes.rb:342`, account integration app/hook routes from `routes.rb:345-348`, account Slack routes from `routes.rb:350-352`, account Dyte routes from `routes.rb:357-358`, account Shopify routes from `routes.rb:361-364`, account Linear routes from `routes.rb:365-373`, account Notion authorization/destroy routes from `routes.rb:335/379`, account Twitter/Google/Microsoft/Instagram/TikTok authorization routes from `routes.rb:315/319/323/327/331`, account WhatsApp authorization route from `routes.rb:339`, account inbox WhatsApp calling toggle routes from `routes.rb:266-267`, dashboard app routes from `routes.rb:130`, canned response routes from `routes.rb:114`, notification subscription routes from `routes.rb:440`, team/team-member routes from `routes.rb:296-300`, conversation participant routes from `routes.rb:150`, conversation direct upload route from `routes.rb:151`, conversation draft message routes from `routes.rb:152`, conversation inbox assistant route from `routes.rb:165`, conversation reporting events route from `routes.rb:166`, and account reporting events route from `routes.rb:234` are now explicitly tracked. Notification list/action serializers, user notification-settings raw payloads, campaigns raw payload/display-id routes, Devise password reset/confirmation payloads, CRM shared attachment payloads plus fixed 100-row attachment pagination, account/settings payloads, assignable-agent payloads, agent index full-list behavior, agent create/update/delete defaults/errors/scope, account agent-bot route/payload/mutation behavior, account webhook payload/mutation behavior, integration app/hook payload behavior, account Slack OAuth/channel payload behavior, account Dyte create/join payload behavior, account Shopify customer-order payload behavior, account Linear GraphQL issue payload behavior, account Notion authorization/destroy behavior, account Twitter/Google/Microsoft/Instagram/TikTok authorization behavior, account WhatsApp embedded-signup creation and reauthorization behavior, account inbox WhatsApp calling toggle behavior, dashboard app raw payload/serializer behavior, canned response raw payload/search/delete behavior, notification subscription payload behavior, team update/frontend route behavior, conversation participant route/payload/final-set update behavior, conversation direct upload ActiveStorage behavior, conversation draft message Redis-key-equivalent behavior, conversation inbox assistant Copilot payload behavior, conversation reporting-event raw array behavior, account reporting-events payload/filter/pagination behavior, label CRUD payloads, custom filters, custom attribute definitions, contact outbound voice calls, assignment policy CRUD and inbox binding payloads, Twilio inbound/status callbacks, enterprise Twilio voice callbacks, Linear/Shopify/Notion root integration callbacks, Shopify OAuth auth redirects, root channel OAuth callbacks, help-center portal/category/article payloads, dashboard app shell route behavior, app association JSON payloads, Cloudflare custom hostname verification, public widget popular-article lists, public help-center category list/show payloads, public portal show/default-locale payloads, public portal search payloads, public article show/markdown/tracking routes, and public sitemap XML now match the inspected Chatwoot contract. | Continue the next evidence-backed route/controller/serializer drift after WhatsApp calling parity or from B12 findings. | Regenerate parity artifacts when routes change and add endpoint-family fixture tests. | | 3 | Phase 6 placeholder audit | Widget/public/webhook critical placeholders are burned down; inbox WhatsApp health/register-webhook and sync-template drift are closed; refreshed `docs/parity/placeholder_audit.md` shows only webhook nil-handler fallbacks still call `chatwootParityStub`; dashboard conversation transcript/custom-attribute response drift and message retry status drift are closed. | Keep in Review; reopen only if fresh `rg`, route smoke, or B12 finds a frontend-reachable placeholder/stub in account/contact/conversation/message/inbox/widget/public paths. | `rg` placeholder audit and `scripts/parity_frontend_smoke.sh --check` are recorded; no reused-frontend blocker is ownerless. | | 4 | P3.9 account agent-bot API | Implemented for the reused dashboard AgentBots settings route with no-trailing-slash routes, PATCH update, raw Jbuilder-style payloads, account mutation scope, system-bot show/list visibility, empty `200 OK` delete, and full reset/avatar action payloads. | Keep in Review; reopen only if live settings smoke exposes avatar upload storage or administrator-secret gating drift. | Focused AgentBot handler tests, service/router focused tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. | | 5 | P3.10 account webhooks API | Implemented for the reused dashboard Webhooks settings route with PATCH update, Chatwoot `{ payload }` list/mutation serializers, nested `{ webhook: ... }` bodies, generated secret, account-scoped mutations, URL/subscription validation, optional inbox serialization, and empty `200 OK` delete. | Keep in Review; reopen only if live settings smoke exposes audit writer or delivery-signature drift beyond the existing delivery service boundary. | Focused webhook handler/service/router tests, migration test, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. | @@ -178,6 +179,7 @@ These rows are the executable development plan from this point forward. A checkp | ID | Owner files | Reference files | Work to land | Exit gate | | --- | --- | --- | --- | --- | +| P3.33 WhatsApp calling toggle parity | `internal/service/inbox_service.go`, `internal/channel/whatsapp/service.go`, `internal/handler/api/v1/inbox_handler.go`, `internal/router/router.go`, `cmd/route_parity/main.go`, WhatsApp calling service/channel/handler tests | `reference/chatwoot/config/routes.rb:266-267`, `reference/chatwoot/enterprise/app/controllers/enterprise/api/v1/accounts/inboxes_controller.rb`, `reference/chatwoot/app/models/channel/whatsapp.rb`, `reference/chatwoot/enterprise/app/services/enterprise/whatsapp/providers/whatsapp_cloud_service.rb`, `reference/chatwoot/app/services/whatsapp/webhook_setup_service.rb`, `reference/chatwoot/app/services/whatsapp/facebook_api_client.rb`, `reference/chatwoot/app/policies/inbox_policy.rb`, `reference/chatwoot/app/javascript/dashboard/api/inboxes.js` | Done. WhatsApp calling enable/disable now matches the reused dashboard and enterprise backend boundary: member routes are tracked and registered; administrator policy is enforced at the router; unsupported non-WhatsApp/non-Cloud inboxes return Chatwoot's `422` error; enable requires `channel_voice`, calls Meta `/settings` with status `ENABLED`, registers webhook fields including `calls`, and persists `calling_enabled`; disable persists `calling_enabled: false`, updates inbox `voice_enabled`, and best-effort re-registers only `messages/smb_message_echoes`. | Review by `feat(channels): align whatsapp calling toggles`; focused service tests cover enable persistence/webhook, unsupported/feature gates, and disable best-effort behavior; channel provider tests cover Meta settings request/error parsing; handler tests cover bad params and empty `200 OK`; route dump/parity regenerated to `TOTAL: 950` and `400 exact, 13 parameter-compatible, 0 missing out of 413`; full `go test ./...` and `git diff --check` must pass. | | P3.32 WhatsApp authorization parity | `internal/service/whatsapp_authorization_service.go`, `internal/handler/api/v1/inbox_handler.go`, `internal/router/router.go`, `cmd/route_parity/main.go`, WhatsApp authorization service tests | `reference/chatwoot/config/routes.rb:338-339`, `reference/chatwoot/app/controllers/api/v1/accounts/whatsapp/authorizations_controller.rb`, `reference/chatwoot/spec/controllers/api/v1/accounts/whatsapp/authorizations_controller_spec.rb`, `reference/chatwoot/app/services/whatsapp/embedded_signup_service.rb`, `reference/chatwoot/app/services/whatsapp/channel_creation_service.rb`, `reference/chatwoot/app/services/whatsapp/reauthorization_service.rb`, `reference/chatwoot/app/services/whatsapp/token_exchange_service.rb`, `reference/chatwoot/app/services/whatsapp/phone_info_service.rb`, `reference/chatwoot/app/services/whatsapp/token_validation_service.rb`, `reference/chatwoot/app/javascript/dashboard/api/channel/whatsappChannel.js` | Done. WhatsApp embedded signup now matches the reused dashboard boundary: the account route is tracked and registered; authenticated agents/admins can create or reauthorize; missing required params return Chatwoot-shaped `422` errors; Meta code exchange, phone info, and token WABA-access checks run through a fakeable HTTP boundary; new channels create WhatsApp Cloud inboxes with embedded-signup provider config and webhook setup; reauthorization validates phone-number continuity, refreshes access token/phone/provider config, clears `reauthorization_required`, updates inbox channel config/name, and returns raw `{ success, id, name, channel_type, message? }` payloads. | Review by `feat(channels): align whatsapp authorization`; focused WhatsApp authorization service tests cover create, reauthorize, validation, and provider failures; handler/router/route-parity focused tests pass; route dump/parity regenerated to `TOTAL: 948` and `398 exact, 13 parameter-compatible, 0 missing out of 411`; full `go test ./...` and `git diff --check` must pass. | | P3.24 Slack integration parity | `internal/handler/api/v1/slack_integration_handler.go`, `internal/service/slack_integration_service.go`, `internal/repository/integration_hook_repo.go`, `internal/handler/api/v1/integration_hook_handler.go`, `cmd/route_parity/main.go`, Slack handler/service tests | `reference/chatwoot/config/routes.rb:350-352`, `reference/chatwoot/app/controllers/api/v1/accounts/integrations/slack_controller.rb`, `reference/chatwoot/lib/integrations/slack/hook_builder.rb`, `reference/chatwoot/lib/integrations/slack/channel_builder.rb`, `reference/chatwoot/app/views/api/v1/accounts/integrations/slack/create.json.jbuilder`, `reference/chatwoot/app/views/api/v1/accounts/integrations/slack/update.json.jbuilder`, `reference/chatwoot/app/views/api/v1/models/_app.json.jbuilder`, `reference/chatwoot/app/views/api/v1/models/_hook.json.jbuilder`, `reference/chatwoot/spec/requests/api/v1/accounts/integrations/slack_request_spec.rb`, `reference/chatwoot/app/javascript/dashboard/api/integrations.js`, `reference/chatwoot/app/javascript/dashboard/store/modules/integrations.js` | Done. Chatwoot Slack singleton behavior is implemented for the reused dashboard flow: frontend no-trailing `POST/PATCH/DELETE` routes and Rails `PUT` update are registered alongside trailing aliases; create accepts `code`/`inbox_id`, exchanges OAuth against Slack, persists disabled `app_id: slack` hooks with access tokens; update accepts `reference_id`, fetches private/public Slack channels with cursor pagination, joins public channels, persists `reference_id`, `settings.channel_name`, and enabled status only when the channel exists; create/update return the raw app partial with hooks; list-all returns raw Slack channel arrays; invalid channel returns `422 { error: "Invalid slack channel. Please try again" }`; delete returns empty `200 OK`. | Review by `feat(integrations): align slack parity`; focused handler tests cover no-trailing create raw app payload, empty delete, and PUT route availability; service tests cover OAuth exchange redirect/body, disabled hook creation, channel fetch/update/join, invalid/not-found, and raw channel lists through a fake Slack client; route parity is `379 exact, 13 parameter-compatible, 0 missing out of 392`; escalated full `go test ./...` and `git diff --check` passed. | | P3.23 nested contact inbox creation parity | `internal/handler/api/v1/contact_handler.go`, `internal/service/contact_inbox_service.go`, `internal/repository/contact_inbox_repo.go`, `internal/handler/api/v1/crm_serializer.go`, `internal/router/router.go`, `cmd/route_parity/main.go`, nested contact inbox handler/service/repository tests | `reference/chatwoot/config/routes.rb:212`, `reference/chatwoot/app/controllers/api/v1/accounts/contacts/contact_inboxes_controller.rb`, `reference/chatwoot/app/controllers/concerns/hmac_concern.rb`, `reference/chatwoot/app/builders/contact_inbox_builder.rb`, `reference/chatwoot/app/views/api/v1/accounts/contacts/contact_inboxes/create.json.jbuilder`, `reference/chatwoot/app/views/api/v1/models/_contact_inbox.json.jbuilder`, `reference/chatwoot/spec/controllers/api/v1/accounts/contacts/contact_inboxes_controller_spec.rb` | Done. Chatwoot `ContactInboxBuilder` behavior is implemented for `POST /api/v1/accounts/:account_id/contacts/:contact_id/contact_inboxes`: raw JSON/form/query params provide `inbox_id`, optional `source_id`, and `hmac_verified`; contact and inbox resolution is account-scoped; missing source IDs are generated by supported channel (`api`/`web_widget` UUID, email, sms phone, whatsapp phone without `+`, twilio sms/whatsapp medium); existing contact+inbox+source rows are returned idempotently; `hmac_verified` is set on creation; tokens are generated; inbox is preloaded; and the response is only `{ source_id, inbox: inbox_slim }`. | Review by `feat(contacts): align contact inbox creation`; focused handler tests cover raw payload shape, HMAC creation, generated source IDs, email idempotency, cross-account inbox rejection, and missing-phone Twilio failure; service tests cover WhatsApp/Twilio generation and idempotency; repository tests cover contact+inbox+source lookup; route parity, full `go test ./...`, and `git diff --check` passed. | @@ -248,6 +250,7 @@ This ledger records the committed parity checkpoints that future slices should b | Commit | Scope | Verification summary | Follow-up state | | --- | --- | --- | --- | +| `feat(channels): align whatsapp calling toggles` | Advances P3.33 WhatsApp calling toggle parity by matching Chatwoot enterprise inbox member actions, WhatsApp channel model voice gates, Meta calling status provider call, webhook subscribed-field behavior, inbox policy, routes `266-267`, and reused dashboard `api/inboxes.js`. GoChat now exposes administrator-gated enable/disable member routes, supports only WhatsApp Cloud API inboxes, requires `channel_voice` for enable, calls Meta phone-number `/settings` with `ENABLED`, persists `provider_config.calling_enabled`, mirrors `voice_enabled` into the inbox serializer config, and best-effort removes the `calls` webhook field on disable. | `go test ./internal/service -run 'WhatsAppCalling\|WhatsAppAuthorization\|InboxService_(RegisterWebhook\|SyncTemplates)' -count=1`; `go test ./internal/channel/whatsapp -run 'UpdateCallingStatus\|FetchHealthStatus' -count=1`; `go test ./internal/handler/api/v1 -run 'InboxWhatsAppCalling\|Inbox(RegisterWebhook\|SyncTemplates)' -count=1`; `go test ./internal/router ./cmd/route_parity -run 'Router\|RouteParity' -count=1`; `go run ./cmd/dump_routes > docs/parity/gochat_routes.txt`; `go run ./cmd/route_parity`; full `go test ./...`; `git diff --check`. Route dump is `TOTAL: 950`; tracked route parity is `400 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 413`. | P3.33 moves to Review for current WhatsApp calling toggle evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. | | `feat(channels): align whatsapp authorization` | Advances P3.32 WhatsApp embedded signup authorization parity by matching Chatwoot `Api::V1::Accounts::Whatsapp::AuthorizationsController#create`, `Whatsapp::EmbeddedSignupService`, channel creation/reauthorization/token/phone validation services, route `339`, request specs, and reused dashboard `whatsappChannel.js`. GoChat now exposes authenticated-agent/admin `POST /api/v1/accounts/:account_id/whatsapp/authorization`, returns raw `{ success, id, name, channel_type, message? }` payloads, creates WhatsApp Cloud inboxes from embedded signup, validates token access to the requested WABA, and reauthorizes existing WhatsApp Cloud inboxes by refreshing provider config and clearing `reauthorization_required`. | `go test ./internal/service -run 'WhatsAppAuthorization' -count=1`; `go test ./internal/handler/api/v1 ./internal/router ./cmd/route_parity -run 'WhatsAppAuthorization\|Router\|RouteParity' -count=1`; `go run ./cmd/dump_routes > docs/parity/gochat_routes.txt`; `go run ./cmd/route_parity`; full `go test ./...`; `git diff --check`. Route dump is `TOTAL: 948`; tracked route parity is `398 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 411`. | P3.32 moves to Review for current WhatsApp embedded-signup evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. | | `feat(channels): align social authorization` | Advances P3.31 Instagram/TikTok authorization parity by matching Chatwoot `Api::V1::Accounts::Instagram::AuthorizationsController#create`, `Api::V1::Accounts::Tiktok::AuthorizationsController#create`, shared OAuth authorization behavior, routes `327/331`, request specs, callback return hints, and reused dashboard `instagramClient.js`/`tiktokClient.js`. GoChat now exposes administrator-gated `POST /api/v1/accounts/:account_id/instagram/authorization` and `POST /api/v1/accounts/:account_id/tiktok/authorization`, returns raw `{ success: true, url }`, builds Chatwoot-scoped provider authorize URLs with frontend callback redirects, and signs account state with optional `return_to` for the existing social callback paths. | `go test ./internal/handler/api/v1 -run 'InstagramAuthorization\|TikTokAuthorization\|SocialAuthorization' -count=1`; `go test ./internal/router ./cmd/route_parity -run 'Router\|RouteParity' -count=1`; `go run ./cmd/dump_routes > docs/parity/gochat_routes.txt`; `go run ./cmd/route_parity`; full `go test ./...`; `git diff --check`. Route dump is `TOTAL: 947`; tracked route parity is `397 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 410`. | P3.31 moves to Review for current Instagram/TikTok authorization evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. | | `feat(channels): align email oauth authorization` | Advances P3.30 Google/Microsoft authorization parity by matching Chatwoot `Api::V1::Accounts::Google::AuthorizationsController#create`, `Api::V1::Accounts::Microsoft::AuthorizationsController#create`, shared `OauthAuthorizationController`, routes `319/323`, request specs, email OAuth callbacks, and reused dashboard `googleClient.js`/`microsoftClient.js`. GoChat now exposes administrator-gated `POST /api/v1/accounts/:account_id/google/authorization` and `POST /api/v1/accounts/:account_id/microsoft/authorization`, returns raw `{ success: true, url }`, builds Chatwoot-scoped provider authorize URLs with frontend callback redirects, and signs callback state for the existing email OAuth callback paths. | `go test ./internal/handler/api/v1 -run 'GoogleAuthorization\|MicrosoftAuthorization\|EmailOAuthAuthorization' -count=1`; `go test ./cmd/route_parity ./internal/router -run 'RouteParity\|Router' -count=1`; `go run ./cmd/dump_routes > docs/parity/gochat_routes.txt`; `go run ./cmd/route_parity`; full `go test ./...`; `git diff --check`. Route dump is `TOTAL: 945`; tracked route parity is `395 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 408`. | P3.30 moves to Review for current Google/Microsoft authorization evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. | @@ -2462,3 +2465,4 @@ Verification milestone gates: - 2026-06-06: P3.30 Google/Microsoft authorization checkpoint prepared as `feat(channels): align email oauth authorization`; audited Chatwoot Google and Microsoft account authorization controllers/specs, shared OAuth authorization controller, routes `319/323`, email callback behavior, and reused dashboard `googleClient.js`/`microsoftClient.js`. GoChat now exposes administrator-gated `POST /api/v1/accounts/:account_id/google/authorization` and `POST /api/v1/accounts/:account_id/microsoft/authorization`, returns raw `{ success: true, url }`, builds Chatwoot provider authorize URLs with exact frontend callback redirects and scopes, includes Google `prompt=consent` plus `access_type=offline`, omits Microsoft prompt, signs account callback state for the existing email OAuth callbacks, and tracks both account authorization routes in route parity. Focused email authorization handler/router tests, route dump/parity regeneration (`945` routes; `395 exact`, `13 parameter-compatible`, `0 missing out of 408`), full `go test ./...`, and `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke. - 2026-06-06: P3.31 Instagram/TikTok authorization checkpoint prepared as `feat(channels): align social authorization`; audited Chatwoot Instagram and TikTok account authorization controllers/specs, shared OAuth authorization behavior, routes `327/331`, callback return hints, and reused dashboard `instagramClient.js`/`tiktokClient.js`. GoChat now exposes administrator-gated `POST /api/v1/accounts/:account_id/instagram/authorization` and `POST /api/v1/accounts/:account_id/tiktok/authorization`, returns raw `{ success: true, url }`, builds Chatwoot provider authorize URLs with exact frontend callback redirects and required social scopes, includes Instagram `enable_fb_login=0` plus `force_authentication=1`, includes TikTok `client_key`, signs account callback state with optional `return_to`, and tracks both account authorization routes in route parity. Focused social authorization handler/router tests, route dump/parity regeneration (`947` routes; `397 exact`, `13 parameter-compatible`, `0 missing out of 410`), full `go test ./...`, and `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke. - 2026-06-06: P3.32 WhatsApp authorization checkpoint prepared as `feat(channels): align whatsapp authorization`; audited Chatwoot WhatsApp authorization controller/specs, embedded signup/channel creation/reauthorization/token/phone validation services, route `339`, and reused dashboard `whatsappChannel.js`. GoChat now exposes authenticated-agent/admin `POST /api/v1/accounts/:account_id/whatsapp/authorization`, validates embedded signup params, exchanges Meta codes, fetches phone info, validates WABA token access, creates WhatsApp Cloud inboxes with embedded-signup provider config, reauthorizes existing inboxes with same-phone validation and `reauthorization_required` clearing, and returns raw `{ success, id, name, channel_type, message? }`. Focused WhatsApp authorization service tests, handler/router/route-parity tests, route dump/parity regeneration (`948` routes; `398 exact`, `13 parameter-compatible`, `0 missing out of 411`), full `go test ./...`, and `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke. +- 2026-06-06: P3.33 WhatsApp calling toggle checkpoint prepared as `feat(channels): align whatsapp calling toggles`; audited Chatwoot enterprise inbox calling actions, WhatsApp channel voice gates, Meta calling-status provider, webhook setup subscribed fields, inbox policy, routes `266-267`, and reused dashboard `api/inboxes.js`. GoChat now exposes administrator-gated `POST /api/v1/accounts/:account_id/inboxes/:inbox_id/enable_whatsapp_calling` and `disable_whatsapp_calling`, supports only WhatsApp Cloud API inboxes, requires `channel_voice` for enable, calls Meta `/settings` with `ENABLED`, persists `provider_config.calling_enabled`, mirrors `voice_enabled` into inbox config, and best-effort removes `calls` from webhook fields on disable. Focused service/channel/handler/router tests, route dump/parity regeneration (`950` routes; `400 exact`, `13 parameter-compatible`, `0 missing out of 413`), full `go test ./...`, and `git diff --check` must pass before commit; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke. diff --git a/docs/parity/gochat_routes.txt b/docs/parity/gochat_routes.txt index 777dfce5..7eafb992 100644 --- a/docs/parity/gochat_routes.txt +++ b/docs/parity/gochat_routes.txt @@ -690,6 +690,8 @@ POST /api/v1/accounts/:account_id/inboxes/:inbox_id/assignment_policy/ POST /api/v1/accounts/:account_id/inboxes/:inbox_id/assignment_policy_v2/ POST /api/v1/accounts/:account_id/inboxes/:inbox_id/csat_template POST /api/v1/accounts/:account_id/inboxes/:inbox_id/csat_template/analyze +POST /api/v1/accounts/:account_id/inboxes/:inbox_id/disable_whatsapp_calling +POST /api/v1/accounts/:account_id/inboxes/:inbox_id/enable_whatsapp_calling POST /api/v1/accounts/:account_id/inboxes/:inbox_id/inbox_limits POST /api/v1/accounts/:account_id/inboxes/:inbox_id/instagram_comments/:comment_id/hide POST /api/v1/accounts/:account_id/inboxes/:inbox_id/instagram_comments/:comment_id/reply @@ -946,4 +948,4 @@ PUT /public/api/v1/csat_survey/:id PUT /public/api/v1/inboxes/:inbox_id/contacts/:contact_id PUT /public/api/v1/inboxes/:inbox_id/contacts/:contact_id/conversations/:conversation_id/messages/:message_id PUT /widget/direct_uploads/:upload_uuid -TOTAL: 948 +TOTAL: 950 diff --git a/docs/parity/route_parity.md b/docs/parity/route_parity.md index 27e44fbf..9e946907 100644 --- a/docs/parity/route_parity.md +++ b/docs/parity/route_parity.md @@ -7,7 +7,7 @@ Generated from: This report covers tracked frontend-critical Chatwoot routes from `reference/chatwoot/config/routes.rb`, including API v1 account routes, Captain/Copilot, assignment policies, widget/public APIs, and API v2 reports. Ruby is not installed in the workspace, so Chatwoot routes are sourced from static route declarations instead of `bin/rails routes`. -Summary: 398 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 411 tracked critical routes. +Summary: 400 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 413 tracked critical routes. ## Missing Critical Routes @@ -342,6 +342,8 @@ These routes exist with equivalent method and path shape but different parameter | POST | `/api/v1/accounts/:account_id/inbox_members/` | `/api/v1/accounts/:account_id/inbox_members/` | `api/v1/accounts/inbox_members#create` | `routes.rb:275` | exact | | POST | `/api/v1/accounts/:account_id/inboxes/` | `/api/v1/accounts/:account_id/inboxes/` | `api/v1/accounts/inboxes#create` | `routes.rb:252` | exact | | POST | `/api/v1/accounts/:account_id/inboxes/:inbox_id/assignment_policy/` | `/api/v1/accounts/:account_id/inboxes/:inbox_id/assignment_policy/` | `api/v1/accounts/inboxes/assignment_policy#create` | `routes.rb:311` | exact | +| POST | `/api/v1/accounts/:account_id/inboxes/:inbox_id/disable_whatsapp_calling` | `/api/v1/accounts/:account_id/inboxes/:inbox_id/disable_whatsapp_calling` | `api/v1/accounts/inboxes#disable_whatsapp_calling` | `routes.rb:267` | exact | +| POST | `/api/v1/accounts/:account_id/inboxes/:inbox_id/enable_whatsapp_calling` | `/api/v1/accounts/:account_id/inboxes/:inbox_id/enable_whatsapp_calling` | `api/v1/accounts/inboxes#enable_whatsapp_calling` | `routes.rb:266` | exact | | POST | `/api/v1/accounts/:account_id/inboxes/:inbox_id/register_webhook` | `/api/v1/accounts/:account_id/inboxes/:inbox_id/register_webhook` | `api/v1/accounts/inboxes#register_webhook` | `routes.rb:260` | exact | | POST | `/api/v1/accounts/:account_id/inboxes/:inbox_id/reset_secret` | `/api/v1/accounts/:account_id/inboxes/:inbox_id/reset_secret` | `api/v1/accounts/inboxes#reset_secret` | `routes.rb:262` | exact | | POST | `/api/v1/accounts/:account_id/inboxes/:inbox_id/set_agent_bot` | `/api/v1/accounts/:account_id/inboxes/:inbox_id/set_agent_bot` | `api/v1/accounts/inboxes#set_agent_bot` | `routes.rb:256` | exact | diff --git a/internal/channel/whatsapp/service.go b/internal/channel/whatsapp/service.go index 3baf61b7..e8f463b8 100644 --- a/internal/channel/whatsapp/service.go +++ b/internal/channel/whatsapp/service.go @@ -48,11 +48,15 @@ func NewWhatsAppService(repository *Repository) *WhatsAppService { if apiVersion == "" { apiVersion = "v22.0" } + cloudBase := os.Getenv("WHATSAPP_CLOUD_BASE_URL") + if cloudBase == "" { + cloudBase = "https://graph.facebook.com" + } return &WhatsAppService{ client: client, repository: repository, - graphAPIBase: "https://graph.facebook.com/" + apiVersion, + graphAPIBase: fmt.Sprintf("%s/%s", cloudBase, apiVersion), dialogAPIBase: "https://waba.360dialog.io", } } @@ -400,6 +404,12 @@ func buildExpectedWhatsAppWebhookURL(phoneNumber string) string { // Cloud API: POST /v18.0/{business_account_id}/subscribed_apps // 360dialog: Webhook is configured via 360dialog Hub dashboard func (s *WhatsAppService) SetupWebhook(ctx context.Context, channel *channelmodel.ChannelWhatsApp, webhookURL string) error { + return s.SetupWebhookFields(ctx, channel, webhookURL, nil) +} + +// SetupWebhookFields subscribes the app and overrides the callback URL/fields for a WABA. +// Reference: Whatsapp::FacebookApiClient#subscribe_waba_webhook. +func (s *WhatsAppService) SetupWebhookFields(ctx context.Context, channel *channelmodel.ChannelWhatsApp, webhookURL string, fields []string) error { if channel.IsCloudAPI() { url := fmt.Sprintf("%s/%s/subscribed_apps", s.graphAPIBase, channel.BusinessAccountID) resp, err := s.client.R(). @@ -409,9 +419,29 @@ func (s *WhatsAppService) SetupWebhook(ctx context.Context, channel *channelmode if err != nil { return fmt.Errorf("WhatsApp Cloud API webhook subscription failed: %w", err) } - if resp.StatusCode() != 200 { + if resp.StatusCode() < 200 || resp.StatusCode() >= 300 { return fmt.Errorf("WhatsApp Cloud API webhook subscription returned status %d", resp.StatusCode()) } + + if len(fields) == 0 { + fields = []string{"messages", "smb_message_echoes", "calls"} + } + body := map[string]any{ + "override_callback_uri": webhookURL, + "verify_token": channel.WebhookVerifyToken, + "subscribed_fields": fields, + } + resp, err = s.client.R(). + SetContext(ctx). + SetAuthToken(channel.AccessToken). + SetBody(body). + Post(url) + if err != nil { + return fmt.Errorf("WhatsApp Cloud API webhook callback override failed: %w", err) + } + if resp.StatusCode() < 200 || resp.StatusCode() >= 300 { + return fmt.Errorf("WhatsApp Cloud API webhook callback override returned status %d", resp.StatusCode()) + } applogger.L().Info("WhatsApp Cloud API webhook subscription created", "business_account_id", channel.BusinessAccountID, ) @@ -425,6 +455,45 @@ func (s *WhatsAppService) SetupWebhook(ctx context.Context, channel *channelmode return nil } +// UpdateCallingStatus enables or disables Meta's WhatsApp Calling setting for a phone number. +// Reference: Enterprise::Whatsapp::Providers::WhatsappCloudService#update_calling_status. +func (s *WhatsAppService) UpdateCallingStatus(ctx context.Context, channel *channelmodel.ChannelWhatsApp, status string) error { + if !channel.IsCloudAPI() { + return fmt.Errorf("WhatsApp calling requires a whatsapp_cloud inbox") + } + url := fmt.Sprintf("%s/%s/settings", s.graphAPIBase, channel.PhoneNumberID) + resp, err := s.client.R(). + SetContext(ctx). + SetAuthToken(channel.AccessToken). + SetBody(map[string]any{"calling": map[string]any{"status": status}}). + Post(url) + if err != nil { + return fmt.Errorf("WhatsApp calling status update failed: %w", err) + } + if resp.StatusCode() >= 200 && resp.StatusCode() < 300 { + return nil + } + return fmt.Errorf("%s", extractWhatsAppCallingError(resp.Body())) +} + +func extractWhatsAppCallingError(body []byte) string { + var parsed map[string]any + if err := json.Unmarshal(body, &parsed); err != nil { + return "Failed to update calling status" + } + errorValue, ok := parsed["error"].(map[string]any) + if !ok { + return "Failed to update calling status" + } + if value, ok := errorValue["error_user_msg"].(string); ok && value != "" { + return value + } + if value, ok := errorValue["message"].(string); ok && value != "" { + return value + } + return "Failed to update calling status" +} + // === Internal Helper Methods === // validateAccessToken validates the WhatsApp access token by making a test API call. diff --git a/internal/channel/whatsapp/service_test.go b/internal/channel/whatsapp/service_test.go index d2346878..0b3baadd 100644 --- a/internal/channel/whatsapp/service_test.go +++ b/internal/channel/whatsapp/service_test.go @@ -45,6 +45,37 @@ func TestWhatsAppService_FetchHealthStatusFormatsChatwootPayload(t *testing.T) { assert.NotContains(t, payload, "healthy") } +func TestWhatsAppService_UpdateCallingStatusPostsSettings(t *testing.T) { + svc := NewWhatsAppService(nil) + svc.graphAPIBase = "https://graph.example.test/v22.0" + svc.client.SetTransport(roundTripFunc(func(r *http.Request) (*http.Response, error) { + require.Equal(t, "/v22.0/phone-123/settings", r.URL.Path) + assert.Equal(t, "Bearer token-abc", r.Header.Get("Authorization")) + body, err := io.ReadAll(r.Body) + require.NoError(t, err) + assert.JSONEq(t, `{"calling":{"status":"ENABLED"}}`, string(body)) + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewBufferString(`{"success":true}`))}, nil + })) + channel := &channelmodel.ChannelWhatsApp{Provider: "whatsapp_cloud", PhoneNumberID: "phone-123", AccessToken: "token-abc"} + + err := svc.UpdateCallingStatus(context.Background(), channel, "ENABLED") + require.NoError(t, err) +} + +func TestWhatsAppService_UpdateCallingStatusUsesMetaErrorMessage(t *testing.T) { + svc := NewWhatsAppService(nil) + svc.graphAPIBase = "https://graph.example.test/v22.0" + svc.client.SetTransport(roundTripFunc(func(r *http.Request) (*http.Response, error) { + body := `{"error":{"error_user_msg":"Calling is not available for this number","message":"fallback"}}` + return &http.Response{StatusCode: http.StatusBadRequest, Body: io.NopCloser(bytes.NewBufferString(body))}, nil + })) + channel := &channelmodel.ChannelWhatsApp{Provider: "whatsapp_cloud", PhoneNumberID: "phone-123", AccessToken: "token-abc"} + + err := svc.UpdateCallingStatus(context.Background(), channel, "ENABLED") + require.Error(t, err) + assert.Equal(t, "Calling is not available for this number", err.Error()) +} + type roundTripFunc func(*http.Request) (*http.Response, error) func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { diff --git a/internal/handler/api/v1/inbox_handler.go b/internal/handler/api/v1/inbox_handler.go index d4bafc60..398379d4 100644 --- a/internal/handler/api/v1/inbox_handler.go +++ b/internal/handler/api/v1/inbox_handler.go @@ -749,6 +749,60 @@ func (h *InboxHandler) RegisterWebhook(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "Webhook registered successfully"}) } +// EnableWhatsAppCalling enables WhatsApp Calling for a Cloud API inbox. +// POST /api/v1/accounts/:id/inboxes/:inbox_id/enable_whatsapp_calling +// Reference: Enterprise::Api::V1::Accounts::InboxesController#enable_whatsapp_calling +func (h *InboxHandler) EnableWhatsAppCalling(c *gin.Context) { + h.handleWhatsAppCallingToggle(c, true) +} + +// DisableWhatsAppCalling disables WhatsApp Calling for a Cloud API inbox. +// POST /api/v1/accounts/:id/inboxes/:inbox_id/disable_whatsapp_calling +// Reference: Enterprise::Api::V1::Accounts::InboxesController#disable_whatsapp_calling +func (h *InboxHandler) DisableWhatsAppCalling(c *gin.Context) { + h.handleWhatsAppCallingToggle(c, false) +} + +func (h *InboxHandler) handleWhatsAppCallingToggle(c *gin.Context, enable bool) { + accountID := parseAccountIDParam(c) + if accountID == 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid account id"}) + return + } + + inboxID, err := parseUintParam(c, "inbox_id") + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid inbox id"}) + return + } + + if !h.svc.Ready() { + response.AbortWithStatusError(c, http.StatusUnprocessableEntity, response.ErrInternal, "failed to update WhatsApp calling") + return + } + + var svcErr error + if enable { + svcErr = h.svc.EnableWhatsAppCalling(c.Request.Context(), accountID, inboxID) + } else { + svcErr = h.svc.DisableWhatsAppCalling(c.Request.Context(), accountID, inboxID) + } + if svcErr != nil { + if errors.Is(svcErr, service.ErrInboxWhatsAppCallingUnsupported) || errors.Is(svcErr, service.ErrInboxWhatsAppCallingFeatureRequired) { + c.JSON(http.StatusUnprocessableEntity, gin.H{"error": svcErr.Error()}) + return + } + if strings.Contains(strings.ToLower(svcErr.Error()), "not found") { + handleServiceError(c, svcErr) + return + } + c.JSON(http.StatusUnprocessableEntity, gin.H{"error": svcErr.Error()}) + return + } + + c.Status(http.StatusOK) +} + // GetAgentBot retrieves the currently active agent bot for an inbox. // GET /api/v1/accounts/:id/inboxes/:inbox_id/agent_bot // Reference: Chatwoot InboxesController#agent_bot diff --git a/internal/handler/api/v1/inbox_handler_test.go b/internal/handler/api/v1/inbox_handler_test.go index de187b96..fbbb5241 100644 --- a/internal/handler/api/v1/inbox_handler_test.go +++ b/internal/handler/api/v1/inbox_handler_test.go @@ -2,6 +2,7 @@ package v1 import ( "bytes" + "context" "encoding/json" "net/http" "net/http/httptest" @@ -32,6 +33,8 @@ func setupInboxMemberActionRouter(handler *InboxHandler) *gin.Engine { r.GET("/api/v1/accounts/:account_id/inboxes/:inbox_id/health", handler.Health) r.POST("/api/v1/accounts/:account_id/inboxes/:inbox_id/sync_templates", handler.SyncTemplates) r.POST("/api/v1/accounts/:account_id/inboxes/:inbox_id/register_webhook", handler.RegisterWebhook) + r.POST("/api/v1/accounts/:account_id/inboxes/:inbox_id/enable_whatsapp_calling", handler.EnableWhatsAppCalling) + r.POST("/api/v1/accounts/:account_id/inboxes/:inbox_id/disable_whatsapp_calling", handler.DisableWhatsAppCalling) return r } @@ -39,6 +42,28 @@ func newNilInboxHandler() *InboxHandler { return NewInboxHandler(&service.InboxService{}) } +type fakeInboxHandlerWhatsAppService struct{} + +func (f *fakeInboxHandlerWhatsAppService) FetchMessageTemplates(context.Context, *channelmodel.ChannelWhatsApp) ([]interface{}, error) { + return nil, nil +} + +func (f *fakeInboxHandlerWhatsAppService) FetchHealthStatus(context.Context, *channelmodel.ChannelWhatsApp) (map[string]interface{}, error) { + return map[string]interface{}{}, nil +} + +func (f *fakeInboxHandlerWhatsAppService) SetupWebhook(context.Context, *channelmodel.ChannelWhatsApp, string) error { + return nil +} + +func (f *fakeInboxHandlerWhatsAppService) SetupWebhookFields(context.Context, *channelmodel.ChannelWhatsApp, string, []string) error { + return nil +} + +func (f *fakeInboxHandlerWhatsAppService) UpdateCallingStatus(context.Context, *channelmodel.ChannelWhatsApp, string) error { + return nil +} + // parseJSONResponse extracts the "error" key from a JSON response body. func parseJSONError(body []byte) string { var resp map[string]interface{} @@ -193,3 +218,58 @@ func TestInboxRegisterWebhook_BadInboxID(t *testing.T) { assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, parseJSONError(w.Body.Bytes()), "invalid inbox id") } + +// ======================================== +// WhatsApp calling — param and response parity tests +// ======================================== + +func TestInboxWhatsAppCalling_BadParams(t *testing.T) { + handler := newNilInboxHandler() + router := setupInboxMemberActionRouter(handler) + + w := httptest.NewRecorder() + req, _ := http.NewRequest("POST", "/api/v1/accounts/abc/inboxes/5/enable_whatsapp_calling", nil) + router.ServeHTTP(w, req) + assert.Equal(t, http.StatusBadRequest, w.Code) + assert.Contains(t, parseJSONError(w.Body.Bytes()), "invalid account id") + + w = httptest.NewRecorder() + req, _ = http.NewRequest("POST", "/api/v1/accounts/1/inboxes/xyz/disable_whatsapp_calling", nil) + router.ServeHTTP(w, req) + assert.Equal(t, http.StatusBadRequest, w.Code) + assert.Contains(t, parseJSONError(w.Body.Bytes()), "invalid inbox id") +} + +func TestInboxWhatsAppCalling_EnableDisableReturnEmptyOK(t *testing.T) { + db, err := gorm.Open(sqlite.Open("file:inbox_whatsapp_calling_handler?mode=memory&cache=shared"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + t.Cleanup(func() { + sqlDB, dbErr := db.DB() + if dbErr == nil { + _ = sqlDB.Close() + } + }) + require.NoError(t, db.AutoMigrate(&model.Account{}, &model.Inbox{}, &channelmodel.ChannelWhatsApp{})) + account := &model.Account{Name: "Calling", Locale: "en", Active: true, FeatureFlags: `{"channel_voice":true}`} + require.NoError(t, db.Create(account).Error) + inbox := &model.Inbox{AccountID: account.ID, Name: "WhatsApp", ChannelType: "whatsapp", ChannelID: 1} + require.NoError(t, db.Create(inbox).Error) + channel := &channelmodel.ChannelWhatsApp{AccountID: account.ID, InboxID: inbox.ID, PhoneNumber: "+1555010000", PhoneNumberID: "phone-1", BusinessAccountID: "waba-1", AccessToken: "token", Provider: "whatsapp_cloud"} + require.NoError(t, db.Create(channel).Error) + + svc := service.NewInboxService(repository.NewInboxRepo(db), nil, nil, nil, nil, &fakeInboxHandlerWhatsAppService{}, whatsappchannel.NewRepository(db)) + handler := NewInboxHandler(svc) + router := setupInboxMemberActionRouter(handler) + + w := httptest.NewRecorder() + req, _ := http.NewRequest("POST", "/api/v1/accounts/1/inboxes/1/enable_whatsapp_calling", nil) + router.ServeHTTP(w, req) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + assert.Empty(t, w.Body.String()) + + w = httptest.NewRecorder() + req, _ = http.NewRequest("POST", "/api/v1/accounts/1/inboxes/1/disable_whatsapp_calling", nil) + router.ServeHTTP(w, req) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + assert.Empty(t, w.Body.String()) +} diff --git a/internal/router/router.go b/internal/router/router.go index cb49de31..815ee070 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -710,6 +710,10 @@ func registerV1Routes(g *gin.RouterGroup, h *Handlers) { inboxes.POST("/:inbox_id/sync_templates", h.Inbox.SyncTemplates) // POST /api/v1/accounts/:id/inboxes/:inbox_id/register_webhook — register channel webhook inboxes.POST("/:inbox_id/register_webhook", h.Inbox.RegisterWebhook) + // POST /api/v1/accounts/:id/inboxes/:inbox_id/enable_whatsapp_calling — enable WhatsApp Calling + inboxes.POST("/:inbox_id/enable_whatsapp_calling", middleware.RoleCheck("administrator"), h.Inbox.EnableWhatsAppCalling) + // POST /api/v1/accounts/:id/inboxes/:inbox_id/disable_whatsapp_calling — disable WhatsApp Calling + inboxes.POST("/:inbox_id/disable_whatsapp_calling", middleware.RoleCheck("administrator"), h.Inbox.DisableWhatsAppCalling) // GET /api/v1/accounts/:id/inboxes/:inbox_id/agent_bot — get currently active agent bot inboxes.GET("/:inbox_id/agent_bot", h.Inbox.GetAgentBot) diff --git a/internal/service/inbox_service.go b/internal/service/inbox_service.go index 0ef4f28c..8a1bbaee 100644 --- a/internal/service/inbox_service.go +++ b/internal/service/inbox_service.go @@ -25,16 +25,22 @@ const InboxLimitExceededMessage = "Account limit exceeded. Upgrade to a higher p const InboxHealthWhatsAppCloudOnlyMessage = "Health data only available for WhatsApp Cloud API channels" const InboxTemplateSyncInitiatedMessage = "Template sync initiated successfully" const InboxTemplateSyncWhatsAppOnlyMessage = "Template sync is only available for WhatsApp channels" +const InboxWhatsAppCallingUnsupportedMessage = "Inbox does not support WhatsApp calling" +const InboxWhatsAppCallingFeatureRequiredMessage = "WhatsApp calling requires the channel_voice feature" const TaskTypeInboxSyncTemplates = "inbox:sync_templates" var ErrInboxLimitExceeded = errors.New(InboxLimitExceededMessage) var ErrInboxHealthWhatsAppCloudOnly = errors.New(InboxHealthWhatsAppCloudOnlyMessage) var ErrInboxTemplateSyncWhatsAppOnly = errors.New(InboxTemplateSyncWhatsAppOnlyMessage) +var ErrInboxWhatsAppCallingUnsupported = errors.New(InboxWhatsAppCallingUnsupportedMessage) +var ErrInboxWhatsAppCallingFeatureRequired = errors.New(InboxWhatsAppCallingFeatureRequiredMessage) type WhatsAppChannelService interface { FetchMessageTemplates(ctx context.Context, channel *channelmodel.ChannelWhatsApp) ([]interface{}, error) FetchHealthStatus(ctx context.Context, channel *channelmodel.ChannelWhatsApp) (map[string]interface{}, error) SetupWebhook(ctx context.Context, channel *channelmodel.ChannelWhatsApp, webhookURL string) error + SetupWebhookFields(ctx context.Context, channel *channelmodel.ChannelWhatsApp, webhookURL string, fields []string) error + UpdateCallingStatus(ctx context.Context, channel *channelmodel.ChannelWhatsApp, status string) error } // InboxService implements business logic for Inbox operations. @@ -1725,6 +1731,84 @@ func (s *InboxService) RegisterWebhook(ctx context.Context, accountID, inboxID u return nil } +// EnableWhatsAppCalling matches Chatwoot Enterprise InboxesController#enable_whatsapp_calling. +// It enables Meta calling remotely, registers the calls webhook field, then persists calling_enabled. +func (s *InboxService) EnableWhatsAppCalling(ctx context.Context, accountID, inboxID uint) error { + account, inbox, waChannel, err := s.whatsAppCallingPrereqs(ctx, accountID, inboxID) + if err != nil { + return err + } + if !featureFlagStringEnabled(account.FeatureFlags, "channel_voice") { + return ErrInboxWhatsAppCallingFeatureRequired + } + if s.whatsappService == nil { + return fmt.Errorf("WhatsApp service not available") + } + if err := s.whatsappService.UpdateCallingStatus(ctx, waChannel, "ENABLED"); err != nil { + return err + } + if err := s.setupWhatsAppWebhookFields(ctx, waChannel, whatsappWebhookCallbackURL(waChannel.PhoneNumber), nil); err != nil { + return err + } + setWhatsAppCallingEnabled(waChannel, true) + if err := s.whatsappRepo.Update(ctx, waChannel); err != nil { + return err + } + return s.refreshWhatsAppInboxConfig(ctx, inbox, waChannel, true) +} + +// DisableWhatsAppCalling matches Chatwoot Enterprise InboxesController#disable_whatsapp_calling. +// It only gates calling locally; webhook re-registration without calls is best-effort. +func (s *InboxService) DisableWhatsAppCalling(ctx context.Context, accountID, inboxID uint) error { + _, inbox, waChannel, err := s.whatsAppCallingPrereqs(ctx, accountID, inboxID) + if err != nil { + return err + } + setWhatsAppCallingEnabled(waChannel, false) + if err := s.whatsappRepo.Update(ctx, waChannel); err != nil { + return err + } + if err := s.refreshWhatsAppInboxConfig(ctx, inbox, waChannel, false); err != nil { + return err + } + if err := s.setupWhatsAppWebhookFields(ctx, waChannel, whatsappWebhookCallbackURL(waChannel.PhoneNumber), []string{"messages", "smb_message_echoes"}); err != nil { + applogger.L().Warnf("WhatsApp calling disable webhook re-subscribe failed for inbox %d: %v", inbox.ID, err) + } + return nil +} + +func (s *InboxService) whatsAppCallingPrereqs(ctx context.Context, accountID, inboxID uint) (*model.Account, *model.Inbox, *channelmodel.ChannelWhatsApp, error) { + inbox, err := s.repo.FindByAccountAndID(ctx, accountID, inboxID) + if err != nil { + return nil, nil, nil, fmt.Errorf("inbox not found: %w", err) + } + if inbox.ChannelType != "whatsapp" { + return nil, nil, nil, ErrInboxWhatsAppCallingUnsupported + } + waChannel, err := s.getWhatsAppChannel(ctx, inbox.ID) + if err != nil || !waChannel.IsCloudAPI() { + return nil, nil, nil, ErrInboxWhatsAppCallingUnsupported + } + var account model.Account + if err := s.repo.DB().WithContext(ctx).First(&account, accountID).Error; err != nil { + return nil, nil, nil, fmt.Errorf("account not found: %w", err) + } + return &account, inbox, waChannel, nil +} + +func setWhatsAppCallingEnabled(channel *channelmodel.ChannelWhatsApp, enabled bool) { + config := parseJSONMap(channel.ProviderConfig) + config["calling_enabled"] = enabled + channel.ProviderConfig = marshalInboxJSON(config) +} + +func (s *InboxService) refreshWhatsAppInboxConfig(ctx context.Context, inbox *model.Inbox, channel *channelmodel.ChannelWhatsApp, voiceEnabled bool) error { + config := whatsappInboxChannelConfig(channel) + config["voice_enabled"] = voiceEnabled + inbox.ChannelConfig = marshalInboxJSON(config) + return s.repo.Update(ctx, inbox) +} + // DeleteAvatar removes the avatar URL from an inbox and dispatches an update event. // Reference: Chatwoot InboxesController#destroy_avatar func (s *InboxService) DeleteAvatar(ctx context.Context, accountID, inboxID uint) (*model.Inbox, error) { @@ -1842,6 +1926,13 @@ func (s *InboxService) setupWhatsAppWebhook(ctx context.Context, waChannel *chan return s.whatsappService.SetupWebhook(ctx, waChannel, webhookURL) } +func (s *InboxService) setupWhatsAppWebhookFields(ctx context.Context, waChannel *channelmodel.ChannelWhatsApp, webhookURL string, fields []string) error { + if s.whatsappService == nil { + return fmt.Errorf("WhatsApp service not available") + } + return s.whatsappService.SetupWebhookFields(ctx, waChannel, webhookURL, fields) +} + // generateInboxSecret creates a random HMAC secret for webhook verification. func generateInboxSecret() string { b := make([]byte, 32) diff --git a/internal/service/inbox_service_test.go b/internal/service/inbox_service_test.go index debc1af1..bac7bd21 100644 --- a/internal/service/inbox_service_test.go +++ b/internal/service/inbox_service_test.go @@ -64,7 +64,10 @@ type fakeInboxWhatsAppService struct { templateErr error fetchCalls int webhookURL string + webhookFields []string webhookErr error + callingStatus string + callingErr error } func (f *fakeInboxWhatsAppService) FetchMessageTemplates(context.Context, *channelmodel.ChannelWhatsApp) ([]interface{}, error) { @@ -84,6 +87,17 @@ func (f *fakeInboxWhatsAppService) SetupWebhook(_ context.Context, _ *channelmod return f.webhookErr } +func (f *fakeInboxWhatsAppService) SetupWebhookFields(_ context.Context, _ *channelmodel.ChannelWhatsApp, webhookURL string, fields []string) error { + f.webhookURL = webhookURL + f.webhookFields = fields + return f.webhookErr +} + +func (f *fakeInboxWhatsAppService) UpdateCallingStatus(_ context.Context, _ *channelmodel.ChannelWhatsApp, status string) error { + f.callingStatus = status + return f.callingErr +} + // createInboxTestPrereqs creates prerequisite Account and Inbox for service tests. func createInboxTestPrereqs(t *testing.T, db *gorm.DB, channelType string) (*model.Account, *model.Inbox) { t.Helper() @@ -447,3 +461,67 @@ func TestInboxService_RegisterWebhook_NonCloudWhatsAppRejected(t *testing.T) { err := svc.RegisterWebhook(context.Background(), account.ID, inbox.ID, RegisterWebhookRequest{}) require.ErrorIs(t, err, ErrInboxHealthWhatsAppCloudOnly) } + +// ======================================== +// WhatsApp calling service tests +// ======================================== + +func TestInboxService_EnableWhatsAppCalling_SetsProviderConfigAndWebhook(t *testing.T) { + svc, db := setupInboxServiceTest(t) + account, inbox, channel := createWhatsAppInboxTestPrereqs(t, db, "whatsapp_cloud") + account.FeatureFlags = `{"channel_voice":true}` + require.NoError(t, db.Save(account).Error) + fake := &fakeInboxWhatsAppService{} + svc.whatsappService = fake + t.Setenv("FRONTEND_URL", "https://app.example.test") + + err := svc.EnableWhatsAppCalling(context.Background(), account.ID, inbox.ID) + require.NoError(t, err) + assert.Equal(t, "ENABLED", fake.callingStatus) + assert.Equal(t, "https://app.example.test/webhooks/whatsapp/+1555010000", fake.webhookURL) + assert.Empty(t, fake.webhookFields) + + var updated channelmodel.ChannelWhatsApp + require.NoError(t, db.First(&updated, channel.ID).Error) + providerConfig := parseJSONMap(updated.ProviderConfig) + assert.Equal(t, true, providerConfig["calling_enabled"]) + + var updatedInbox model.Inbox + require.NoError(t, db.First(&updatedInbox, inbox.ID).Error) + channelConfig := parseJSONMap(updatedInbox.ChannelConfig) + assert.Equal(t, true, channelConfig["voice_enabled"]) +} + +func TestInboxService_EnableWhatsAppCalling_RequiresCloudAndFeature(t *testing.T) { + svc, db := setupInboxServiceTest(t) + account, inbox, _ := createWhatsAppInboxTestPrereqs(t, db, "360dialog") + account.FeatureFlags = `{"channel_voice":true}` + require.NoError(t, db.Save(account).Error) + svc.whatsappService = &fakeInboxWhatsAppService{} + + err := svc.EnableWhatsAppCalling(context.Background(), account.ID, inbox.ID) + require.ErrorIs(t, err, ErrInboxWhatsAppCallingUnsupported) + + account, inbox, _ = createWhatsAppInboxTestPrereqs(t, db, "whatsapp_cloud") + err = svc.EnableWhatsAppCalling(context.Background(), account.ID, inbox.ID) + require.ErrorIs(t, err, ErrInboxWhatsAppCallingFeatureRequired) +} + +func TestInboxService_DisableWhatsAppCalling_PersistsFalseAndIgnoresWebhookFailure(t *testing.T) { + svc, db := setupInboxServiceTest(t) + account, inbox, channel := createWhatsAppInboxTestPrereqs(t, db, "whatsapp_cloud") + channel.ProviderConfig = `{"calling_enabled":true,"phone_number_id":"phone-1","business_account_id":"waba-1"}` + require.NoError(t, db.Save(channel).Error) + fake := &fakeInboxWhatsAppService{webhookErr: fmt.Errorf("meta unavailable")} + svc.whatsappService = fake + t.Setenv("FRONTEND_URL", "https://app.example.test") + + err := svc.DisableWhatsAppCalling(context.Background(), account.ID, inbox.ID) + require.NoError(t, err) + assert.Equal(t, []string{"messages", "smb_message_echoes"}, fake.webhookFields) + + var updated channelmodel.ChannelWhatsApp + require.NoError(t, db.First(&updated, channel.ID).Error) + providerConfig := parseJSONMap(updated.ProviderConfig) + assert.Equal(t, false, providerConfig["calling_enabled"]) +} diff --git a/internal/service/whatsapp_authorization_service_test.go b/internal/service/whatsapp_authorization_service_test.go index c036b71d..4be7f449 100644 --- a/internal/service/whatsapp_authorization_service_test.go +++ b/internal/service/whatsapp_authorization_service_test.go @@ -36,6 +36,15 @@ func (f *fakeWhatsAppAuthorizationChannelService) SetupWebhook(_ context.Context return nil } +func (f *fakeWhatsAppAuthorizationChannelService) SetupWebhookFields(_ context.Context, _ *channelmodel.ChannelWhatsApp, webhookURL string, _ []string) error { + f.webhookURL = webhookURL + return nil +} + +func (f *fakeWhatsAppAuthorizationChannelService) UpdateCallingStatus(context.Context, *channelmodel.ChannelWhatsApp, string) error { + return nil +} + func setupWhatsAppAuthorizationService(t *testing.T) (*InboxService, *gorm.DB, *fakeWhatsAppAuthorizationChannelService) { t.Helper() db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})