feat(notifications): tighten chatwoot scoping

This commit is contained in:
2026-06-06 20:57:14 +08:00
parent 4a7df91556
commit 3aa21996f6
5 changed files with 251 additions and 43 deletions
+23 -19
View File
@@ -49,13 +49,13 @@ Hermes task landing checklist:
## Current Baseline
- Current tracking checkpoint: 2026-06-06 API v2 year-in-review parity checkpoint, prepared as `feat(reports): align year in review`.
- Latest implementation checkpoint: this checkpoint, prepared as `feat(reports): align year in review`.
- 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/*`.
- Current tracking checkpoint: 2026-06-06 account notification scoping hardening checkpoint, prepared as `feat(notifications): tighten chatwoot scoping`.
- Latest implementation checkpoint: this checkpoint, prepared as `feat(notifications): tighten chatwoot scoping`.
- Latest documentation/tooling checkpoint: this tracker update for P3.35 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: API v2 year-in-review parity from `reference/chatwoot/config/routes.rb:505`, `app/controllers/api/v2/accounts/year_in_reviews_controller.rb`, `app/builders/year_in_review_builder.rb`, and reused dashboard `api/yearInReview.js` is implemented. GoChat now exposes `GET /api/v2/accounts/:account_id/year_in_review?year=YYYY`, returns a raw Chatwoot payload without the local `{ success, data }` envelope, defaults missing `year` to `2025`, scopes to the current user/account, reads and writes `Current.user.ui_settings` cache key `year_in_review_<account_id>_<year>`, counts assigned conversations in the selected year, computes the busiest assigned day as `Mon DD`, and truncates average `first_response` reporting-event value into `support_personality.avg_response_time_seconds`. WhatsApp calling toggle parity remains implemented from the previous checkpoint. Live API/browser/enterprise smoke still needs the full PostgreSQL/Redis/Meilisearch/GoChat/Vite/Chrome stack.
- Worktree status at this implementation checkpoint: account notification mutation scoping from `reference/chatwoot/config/routes.rb:283-291`, `app/controllers/api/v1/accounts/notifications_controller.rb`, `app/finders/notification_finder.rb`, `app/views/api/v1/accounts/notifications/index.json.jbuilder`, and reused dashboard `api/notifications.js` is hardened. GoChat now fetches, updates, deletes, snoozes, marks unread, and counts notifications through the current user/current account scope; `snoozed_until` accepts Chatwoot Unix timestamp input and records `meta.last_snoozed_at`; missing snooze time is a scoped no-op that returns the current notification; destroy remains empty `200 OK`. API v2 year-in-review and WhatsApp calling toggle parity remain implemented from previous checkpoints. 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 YearInReview service/handler/router tests pass in the sandbox.
- `go test ./...` passes when run outside the restricted socket sandbox; focused Notification handler/repository/service tests pass in the sandbox.
- Route dump succeeds with `951` registered routes after API v2 year-in-review route tracking.
- Route parity artifacts now exist under `docs/parity/` and are generated by `cmd/route_parity`.
- Tracked frontend-critical route audit covers 414 Chatwoot routes: 401 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.
@@ -140,20 +140,21 @@ This table is the shortest authoritative handoff view. If an older lower section
| Priority | Workstream | Current state | Next checkpoint | Commit close rule |
| --- | --- | --- | --- | --- |
| 0 | P3.34 API v2 year-in-review parity | Implemented for reused dashboard year-in-review client: `GET /api/v2/accounts/:account_id/year_in_review?year=YYYY` is registered and tracked from `routes.rb:505`, returns raw `{ year, total_conversations, busiest_day, support_personality }`, defaults missing `year` to `2025`, reads/writes the current user's `ui_settings` cache under `year_in_review_<account_id>_<year>`, counts conversations assigned to the current user during the selected year, formats the busiest assigned conversation day as `Mon DD`, and truncates the average `first_response` reporting-event value into seconds. | Keep in Review; reopen only if live reused-dashboard year-in-review smoke exposes timezone, cache-present, invalid-year, or payload-shape drift beyond the inspected controller/builder/frontend contract. | Focused YearInReview service/handler tests, router/route-parity tests, route dump/parity regeneration (`951` routes; `401 exact`, `13 parameter-compatible`, `0 missing out of 414`), full `go test ./...`, and `git diff --check` must pass before commit. |
| 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. |
| 0 | P3.29 Twitter authorization parity | Implemented for reused dashboard Twitter connect flow: `POST /api/v1/accounts/:account_id/twitter/authorization` is registered and tracked from `routes.rb:315`, the route is administrator-gated like Chatwoot's controller, the response returns raw `{ success: true, url }`, the request-token call uses Twitter OAuth1 signing with configured consumer key/secret and frontend `/twitter/callback?state=...`, and the returned URL targets `/oauth/authorize?oauth_token=...`. | Keep in Review; reopen only if live Twitter OAuth smoke exposes request-token signing/header drift, Redis request-token mapping requirements beyond signed callback state, provider base URL drift, or frontend payload drift beyond the inspected authorization controller/spec/frontend contract. | Focused Twitter authorization handler/router/route tests, route dump/parity regeneration (`943` routes; `393 exact`, `13 parameter-compatible`, `0 missing out of 406`), full `go test ./...`, and `git diff --check` must pass before commit. |
| 0 | P3.28 Notion authorization parity | Implemented for reused dashboard Notion connect flow: `POST /api/v1/accounts/:account_id/notion/authorization` is registered and tracked from `routes.rb:335`, the route is administrator-gated like Chatwoot's `OauthAuthorizationController`, the response returns raw `{ success: true, url }`, the URL targets `https://api.notion.com/v1/oauth/authorize` with `response_type=code`, `owner=user`, frontend `/notion/callback`, configured `client_id`, and signed account state for the existing callback. | Keep in Review; reopen only if live Notion OAuth smoke exposes GlobalID state compatibility, config-source drift, feature-gate behavior, or frontend payload drift beyond the inspected authorization controller/spec/frontend contract. | Focused Notion authorization handler/service tests, route dump/parity regeneration (`942` routes; `392 exact`, `13 parameter-compatible`, `0 missing out of 405`), full `go test ./...`, and `git diff --check` must pass before commit. |
| 0 | P3.27 Notion integration destroy parity | Implemented for reused dashboard Notion integration disconnect flow: no-trailing and trailing destroy routes are registered, the account route is tracked from `routes.rb:379`, OAuth callback-created hooks are found by `app_id: notion` with legacy hook-type fallback, and delete returns empty `200 OK` instead of a local success/message envelope. | Keep in Review; reopen only if live Notion OAuth/disconnect smoke exposes feature-gate drift, callback-created hook shape drift, or frontend delete error handling beyond the inspected controller/spec/frontend contract. | Focused Notion handler/service tests, route dump/parity regeneration (`941` routes; `391 exact`, `13 parameter-compatible`, `0 missing out of 404`), full `go test ./...`, and `git diff --check` must pass before commit. |
| 0 | P3.35 account notification scoping hardening | Implemented for reused dashboard notification actions: account notifications now follow Chatwoot `fetch_notification` scope (`current_user.notifications.where(account_id: Current.account.id)`) for show, update/read, destroy, snooze, unread, and unread count. `snoozed_until` is parsed as Unix seconds like `DateRangeHelper`, snooze merges `meta.last_snoozed_at: null`, missing `snoozed_until` returns the scoped notification without mutation, destroy returns empty `200 OK`, and cross-user/cross-account mutations return `404`. | Keep in Review; reopen only if live notification-center smoke exposes list metadata, snooze timestamp, read/unread, destroy_all async, or notification serializer drift beyond the inspected controller/finder/Jbuilder/frontend contract. | Focused Notification handler/repository/service tests, full `go test ./...`, and `git diff --check` passed. No route artifacts change because only handler/repository/service behavior changed. |
| 0 | P3.34 API v2 year-in-review parity | Implemented for reused dashboard year-in-review client: `GET /api/v2/accounts/:account_id/year_in_review?year=YYYY` is registered and tracked from `routes.rb:505`, returns raw `{ year, total_conversations, busiest_day, support_personality }`, defaults missing `year` to `2025`, reads/writes the current user's `ui_settings` cache under `year_in_review_<account_id>_<year>`, counts conversations assigned to the current user during the selected year, formats the busiest assigned conversation day as `Mon DD`, and truncates the average `first_response` reporting-event value into seconds. | Keep in Review; reopen only if live reused-dashboard year-in-review smoke exposes timezone, cache-present, invalid-year, or payload-shape drift beyond the inspected controller/builder/frontend contract. | Focused YearInReview service/handler tests, router/route-parity tests, route dump/parity regeneration (`951` routes; `401 exact`, `13 parameter-compatible`, `0 missing out of 414`), full `go test ./...`, and `git diff --check` passed. |
| 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` passed. |
| 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` passed. |
| 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` passed. |
| 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` passed. |
| 0 | P3.29 Twitter authorization parity | Implemented for reused dashboard Twitter connect flow: `POST /api/v1/accounts/:account_id/twitter/authorization` is registered and tracked from `routes.rb:315`, the route is administrator-gated like Chatwoot's controller, the response returns raw `{ success: true, url }`, the request-token call uses Twitter OAuth1 signing with configured consumer key/secret and frontend `/twitter/callback?state=...`, and the returned URL targets `/oauth/authorize?oauth_token=...`. | Keep in Review; reopen only if live Twitter OAuth smoke exposes request-token signing/header drift, Redis request-token mapping requirements beyond signed callback state, provider base URL drift, or frontend payload drift beyond the inspected authorization controller/spec/frontend contract. | Focused Twitter authorization handler/router/route tests, route dump/parity regeneration (`943` routes; `393 exact`, `13 parameter-compatible`, `0 missing out of 406`), full `go test ./...`, and `git diff --check` passed. |
| 0 | P3.28 Notion authorization parity | Implemented for reused dashboard Notion connect flow: `POST /api/v1/accounts/:account_id/notion/authorization` is registered and tracked from `routes.rb:335`, the route is administrator-gated like Chatwoot's `OauthAuthorizationController`, the response returns raw `{ success: true, url }`, the URL targets `https://api.notion.com/v1/oauth/authorize` with `response_type=code`, `owner=user`, frontend `/notion/callback`, configured `client_id`, and signed account state for the existing callback. | Keep in Review; reopen only if live Notion OAuth smoke exposes GlobalID state compatibility, config-source drift, feature-gate behavior, or frontend payload drift beyond the inspected authorization controller/spec/frontend contract. | Focused Notion authorization handler/service tests, route dump/parity regeneration (`942` routes; `392 exact`, `13 parameter-compatible`, `0 missing out of 405`), full `go test ./...`, and `git diff --check` passed. |
| 0 | P3.27 Notion integration destroy parity | Implemented for reused dashboard Notion integration disconnect flow: no-trailing and trailing destroy routes are registered, the account route is tracked from `routes.rb:379`, OAuth callback-created hooks are found by `app_id: notion` with legacy hook-type fallback, and delete returns empty `200 OK` instead of a local success/message envelope. | Keep in Review; reopen only if live Notion OAuth/disconnect smoke exposes feature-gate drift, callback-created hook shape drift, or frontend delete error handling beyond the inspected controller/spec/frontend contract. | Focused Notion handler/service tests, route dump/parity regeneration (`941` routes; `391 exact`, `13 parameter-compatible`, `0 missing out of 404`), full `go test ./...`, and `git diff --check` passed. |
| 0 | P3.26 Shopify integration parity | Implemented for reused dashboard Shopify integration and customer-order panel: no-trailing and trailing destroy routes are registered, auth returns raw `{ redirect_url }`, missing shop domains return Chatwoot's `422 { error: "Shop domain is required" }`, orders returns raw `{ orders: [...] }`, account-scoped contacts are required, contacts without email/phone return `422 { error: "Contact information missing" }`, Shopify customers/search and orders REST calls are made through fakeable clients, order payloads include `admin_url`, callback-created hooks are found by `app_id: shopify`, and delete returns empty `200 OK`. | Keep in Review; reopen only if live Shopify OAuth/order smoke exposes token/session setup drift, REST API version drift, Shopify error-body wording, or frontend order payload drift beyond the inspected controller/helper/spec/frontend contract. | Focused Shopify handler/service tests, route dump/parity regeneration (`940` routes; `390 exact`, `13 parameter-compatible`, `0 missing out of 403`), sandbox package tests, escalated full `go test ./...`, and `git diff --check` passed. |
| 0 | P3.25 Linear integration parity | Implemented for reused dashboard Linear issue flow: no-trailing and trailing destroy routes are registered, teams/team_entities/search/linked/create/link/unlink return raw Chatwoot payloads, provider errors return `422 { error }`, blank search returns Chatwoot's exact search-string error, requests proxy Linear GraphQL via fakeable clients, delete revokes Linear tokens and returns empty `200 OK`, create/link/unlink resolve conversations by account display ID, conversation links use the reused frontend URL, and successful mutations create Chatwoot-style Linear activity messages. | Keep in Review; reopen only if live Linear OAuth/GraphQL smoke exposes token refresh behavior, GraphQL query/mutation field drift, activity job queue semantics, or frontend payload drift beyond the inspected controller/processor/client/spec contract. | Focused Linear handler/service tests, route dump/parity regeneration (`939` routes; `387 exact`, `13 parameter-compatible`, `0 missing out of 400`), sandbox package tests, escalated full `go test ./...`, and `git diff --check` passed. |
| 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 414-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`, API v2 year-in-review route from `routes.rb:505`, 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, API v2 year-in-review raw/cache/aggregate 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 P3.34 year-in-review 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 414-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`, API v2 year-in-review route from `routes.rb:505`, 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 plus current-user/current-account mutation scoping, 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, API v2 year-in-review raw/cache/aggregate 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 P3.35 notification scoping hardening 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. |
@@ -180,6 +181,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.35 account notification scoping hardening | `internal/repository/notification_repo.go`, `internal/service/notification_service.go`, `internal/handler/api/v1/notification_handler.go`, notification handler/repository/service tests | `reference/chatwoot/config/routes.rb:283-291`, `reference/chatwoot/app/controllers/api/v1/accounts/notifications_controller.rb`, `reference/chatwoot/app/finders/notification_finder.rb`, `reference/chatwoot/app/views/api/v1/accounts/notifications/index.json.jbuilder`, `reference/chatwoot/app/javascript/dashboard/api/notifications.js` | Done. Account notification show/update/destroy/snooze/unread/unread_count now use current-user/current-account scope; cross-account and cross-user rows do not leak; `snoozed_until` accepts Unix seconds; snooze merges `meta.last_snoozed_at`; absent `snoozed_until` is a scoped no-op; destroy keeps Chatwoot empty `200 OK`. | Review by `feat(notifications): tighten chatwoot scoping`; focused handler tests cover mutation scoping, account unread count, Unix snooze, no-body snooze, and destroy route coverage; repository/service notification tests cover scoped helpers; full `go test ./...` and `git diff --check` passed. No route artifacts change. |
| P3.34 API v2 year-in-review parity | `internal/service/year_in_review_service.go`, `internal/handler/api/v1/year_in_review_handler.go`, `internal/router/router.go`, `internal/app/bootstrap.go`, `cmd/route_parity/main.go`, YearInReview service/handler/router tests | `reference/chatwoot/config/routes.rb:505`, `reference/chatwoot/app/controllers/api/v2/accounts/year_in_reviews_controller.rb`, `reference/chatwoot/app/builders/year_in_review_builder.rb`, `reference/chatwoot/app/javascript/dashboard/api/yearInReview.js` | Done. API v2 year-in-review now matches the reused dashboard route and builder boundary: account-scoped `GET /api/v2/accounts/:account_id/year_in_review` is tracked and registered; response is raw JSON; missing `year` defaults to `2025`; the current user/account cache key is persisted in `ui_settings`; assigned yearly conversation totals, busiest day, and average first-response seconds are derived from persisted conversations/reporting events. | Review by `feat(reports): align year in review`; focused service tests cover aggregate payload, busiest day, average truncation, cache storage, cache reuse, and empty personality; handler tests cover raw response shape, auth, and invalid year; router/route-parity tests and route artifacts regenerate to `TOTAL: 951` and `401 exact, 13 parameter-compatible, 0 missing out of 414`; full `go test ./...` and `git diff --check` must pass. |
| 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. |
@@ -192,7 +194,7 @@ These rows are the executable development plan from this point forward. A checkp
| P5.13a analytics placeholder burn-down | `internal/service/analytics_service.go`, `internal/service/analytics_query_helpers.go`, live/report handlers | Chatwoot `live_reports_controller.rb`, `reports_controller.rb`, `BotMetricsBuilder`, `InboxLabelMatrixBuilder`, `FirstResponseTimeDistributionBuilder`, `OutgoingMessagesCountBuilder` | Replace frontend-visible zero/empty placeholder responses for live conversations, grouped live conversations, bot summary/metrics, conversation summary, inbox-label matrix, first-response distribution, and outgoing-message counts with persisted conversation/message/reporting-event queries. | Review by `feat(reports): derive analytics aggregates`; focused service/handler tests prove non-zero values from persisted rows and `rg` finds no placeholder TODOs in these methods. |
| P5.13b scheduled/cached analytics | `internal/service/analytics_service.go`, `internal/service/analytics_query_helpers.go`, `internal/service/reporting_rollup_worker.go`, `internal/service/reporting_rollup_service.go`, report handlers/services, worker bootstrap | Chatwoot report controllers/services used by dashboard analytics, `Reports::DataSource`, reporting rollup/backfill jobs | Wire scheduled or lazy cached rollup freshness/idempotency and route `GET /reports` to metric timeseries instead of the summary handler. Define freshness rules for expensive rollups. | Review by `feat(reports): add analytics timeseries rollups`; report fixtures prove timeseries values are derived from persisted conversations/messages/reporting events, rollups refresh idempotently, durable `reporting:rollup_day` jobs replay, and hidden placeholder report JSON does not reappear. |
| P3.6 label CRUD payload parity | `internal/handler/api/v1/label_handler.go`, `internal/service/tag_service.go`, `internal/model/tag.go`, `internal/repository/tag_repo.go`, migrations, label handler/service tests | `reference/chatwoot/app/controllers/api/v1/accounts/labels_controller.rb`, `app/views/api/v1/accounts/labels/*.json.jbuilder`, `app/models/label.rb`, `db/schema.rb`, dashboard `api/labels.js`, `store/modules/labels.js` | Account `/labels` CRUD now returns Chatwoot `{ payload: [...] }` lists, raw mutation/show payloads, empty `200 OK` delete, `title/description/color/show_on_sidebar` persistence, title lowercasing/uniqueness, account scope, nested `{ label: ... }` request bodies, legacy `name` compatibility, default color, and local association cleanup/rename side effects. | Review by `feat(labels): align chatwoot label payloads`; focused handler/service/repository tests, combined handler/service/router tests, `go test ./cmd/migrate -count=1`, full `go test ./...`, and `git diff --check` passed. |
| P3.6 custom filters/custom attribute definitions payload parity | `internal/handler/api/v1/custom_filter_handler.go`, `internal/service/custom_filter_service.go`, `internal/repository/custom_filter_repo.go`, `internal/handler/api/v1/custom_attribute_definition_handler.go`, `internal/service/custom_attribute_definition_service.go`, `internal/service/custom_attribute_value_service.go`, handler/service/repository tests | `reference/chatwoot/app/controllers/api/v1/accounts/custom_filters_controller.rb`, `app/views/api/v1/accounts/custom_filters/*.json.jbuilder`, `app/views/api/v1/models/_custom_filter.json.jbuilder`, dashboard `api/customViews.js`, `store/modules/customViews.js`, `custom_attribute_definitions_controller.rb`, `_custom_attribute_definition.json.jbuilder`, dashboard `api/attributes.js`, `store/modules/attributes.js`, settings attributes screens/constants | `/custom_filters` and `/custom_attribute_definitions` now return raw Chatwoot arrays/objects instead of local envelopes, accept raw reused-frontend bodies plus Rails-style wrappers, use `200 OK` mutation responses, preserve `204` deletes, scope saved views by current user and default `filter_type=conversation`, normalize custom attribute enum integers to Chatwoot string values, and keep custom attribute value validation compatible with normalized `*_attribute` definitions plus legacy rows. | Review by `feat(custom-fields): align chatwoot saved view payloads`; focused handler/service/repository tests, combined handler/service/router tests, full `go test ./...`, and `git diff --check` must pass. |
| P3.6 custom filters/custom attribute definitions payload parity | `internal/handler/api/v1/custom_filter_handler.go`, `internal/service/custom_filter_service.go`, `internal/repository/custom_filter_repo.go`, `internal/handler/api/v1/custom_attribute_definition_handler.go`, `internal/service/custom_attribute_definition_service.go`, `internal/service/custom_attribute_value_service.go`, handler/service/repository tests | `reference/chatwoot/app/controllers/api/v1/accounts/custom_filters_controller.rb`, `app/views/api/v1/accounts/custom_filters/*.json.jbuilder`, `app/views/api/v1/models/_custom_filter.json.jbuilder`, dashboard `api/customViews.js`, `store/modules/customViews.js`, `custom_attribute_definitions_controller.rb`, `_custom_attribute_definition.json.jbuilder`, dashboard `api/attributes.js`, `store/modules/attributes.js`, settings attributes screens/constants | `/custom_filters` and `/custom_attribute_definitions` now return raw Chatwoot arrays/objects instead of local envelopes, accept raw reused-frontend bodies plus Rails-style wrappers, use `200 OK` mutation responses, preserve `204` deletes, scope saved views by current user and default `filter_type=conversation`, normalize custom attribute enum integers to Chatwoot string values, and keep custom attribute value validation compatible with normalized `*_attribute` definitions plus legacy rows. | Review by `feat(custom-fields): align chatwoot saved view payloads`; focused handler/service/repository tests, combined handler/service/router tests, full `go test ./...`, and `git diff --check` passed. |
| P3.7a help center portal route/payload parity | `internal/router/router.go`, `internal/handler/api/v1/portal_handler.go`, `internal/service/portal_service.go`, `internal/repository/portal_repo.go`, portal handler/service/repository tests | `reference/chatwoot/app/controllers/api/v1/accounts/portals_controller.rb`, `app/views/api/v1/accounts/portals/*.json.jbuilder`, dashboard `api/helpCenter/portals.js`, help-center portal store/actions | Frontend no-trailing-slash `GET/POST /portals`, `PATCH /portals/:portal_id`, and PATCH archive routes are registered; `:portal_id` resolves as Chatwoot portal slug with legacy numeric fallback; raw portal bodies plus `{ portal: ... }` wrappers are accepted; portal index/show/create/update return raw Jbuilder-style payloads; delete/logo/archive return empty `200 OK`; `send_instructions` returns `{ message }`; and `ssl_status` returns enterprise `{ status, verification_errors }`/`422` semantics. | Review by `feat(help-center): align portal payloads`; focused portal handler/service/repository tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. |
| P3.7b help center category route/payload parity | `internal/router/router.go`, `internal/handler/api/v1/category_handler.go`, `internal/service/category_service.go`, `internal/repository/category_repo.go`, category tests | `reference/chatwoot/app/controllers/api/v1/accounts/categories_controller.rb`, `app/views/api/v1/accounts/categories/*.json.jbuilder`, dashboard `api/helpCenter/categories.js` | Category APIs now resolve portal slugs account-scoped for `/portals/:portal_id/categories`, accept raw category bodies plus wrappers, expose frontend no-trailing-slash and `PATCH` routes, return Chatwoot `{ payload, meta }` and `{ payload: category }` serializers with locale filtering and article counts, make delete/reorder empty `200 OK`, accept Chatwoot `positions_hash`, and keep category mutations scoped to the resolved portal. | Review by `feat(help-center): align category payloads`; focused category handler/service/repository tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. |
| P3.7c help center article and bulk-action parity | `internal/router/router.go`, `internal/handler/api/v1/article_handler.go`, `internal/service/article_service.go`, `internal/repository/article_repo.go`, article tests | `reference/chatwoot/app/controllers/api/v1/accounts/articles_controller.rb`, `app/controllers/api/v1/accounts/articles/bulk_actions_controller.rb`, `app/views/api/v1/accounts/articles/*.json.jbuilder`, dashboard `api/helpCenter/articles.js` | Article APIs now resolve portal slugs account-scoped with numeric fallback, accept raw article bodies plus wrappers, expose no-trailing-slash index/create plus frontend `PATCH`, return Chatwoot `{ payload, meta }` list/search payloads and `{ payload: article }` show/create/update/edit payloads, serialize category/author/views/Unix updated-at/meta/associated articles, make delete/reorder/bulk actions empty `200 OK`, accept Chatwoot `positions_hash`, scope mutations to the resolved portal, and implement frontend bulk update-status/update-category/delete routes. | Review by `feat(help-center): align article payloads`; focused article handler tests, service/repository article tests, router test, route dump/parity regeneration, escalated full `go test ./...`, and `git diff --check` passed. |
@@ -212,9 +214,9 @@ These rows are the executable development plan from this point forward. A checkp
| P3.21 conversation reporting events API parity | `internal/router/router.go`, `internal/handler/api/v1/conversation_handler.go`, `internal/service/conversation_service.go`, `internal/repository/reporting_event_repo.go`, conversation handler tests, `cmd/route_parity` | `reference/chatwoot/config/routes.rb:166`, `reference/chatwoot/enterprise/app/controllers/enterprise/api/v1/accounts/conversations_controller.rb`, `reference/chatwoot/enterprise/app/views/api/v1/accounts/conversations/reporting_events.json.jbuilder`, `reference/chatwoot/enterprise/app/views/api/v1/models/_reporting_event.json.jbuilder`, `reference/chatwoot/app/models/reporting_event.rb` | Conversation reporting events now match Chatwoot's enterprise member route boundary: `GET /api/v1/accounts/:account_id/conversations/:conversation_id/reporting_events` is tracked and registered, resolves conversations by account display ID with legacy ID fallback, scopes event rows by account and conversation, orders by `created_at ASC`, and serializes a raw array with nullable `inbox_id`, `user_id`, and `conversation_id` keys preserved. | Review by `feat(conversations): expose reporting events`; focused Conversation handler tests cover raw array shape, ascending order, display-ID lookup, invalid params, and cross-account non-leakage; route dump/parity regenerated to `TOTAL: 933` and `373 exact, 13 parameter-compatible, 0 missing out of 386`; full `go test ./...` and `git diff --check` passed. |
| P3.22 account reporting events API parity | `cmd/route_parity`, `internal/handler/api/v1/reporting_event_handler.go`, `internal/service/reporting_event_service.go`, `internal/repository/reporting_event_repo.go`, reporting event handler tests | `reference/chatwoot/config/routes.rb:234`, `reference/chatwoot/enterprise/app/controllers/api/v1/accounts/reporting_events_controller.rb`, `reference/chatwoot/enterprise/app/views/api/v1/accounts/reporting_events/index.json.jbuilder`, `reference/chatwoot/enterprise/app/views/api/v1/models/_reporting_event.json.jbuilder`, `reference/chatwoot/spec/enterprise/controllers/api/v1/accounts/reporting_events_controller_spec.rb`, `reference/chatwoot/app/helpers/date_range_helper.rb` | Account reporting events now match Chatwoot's enterprise index boundary: `GET /api/v1/accounts/:account_id/reporting_events` is tracked, returns raw `{ payload, meta: { count, current_page, total_pages } }`, filters by optional Unix timestamp `since/until`, `inbox_id`, `user_id`, and `name`, orders by `created_at DESC`, uses a fixed 25-row page size, and serializes event rows with nullable relation keys preserved. | Review by `feat(reporting): align account events`; focused ReportingEvent handler tests cover payload shape, ordering, combined filters, pagination, and invalid filters; route parity regenerated to `374 exact, 13 parameter-compatible, 0 missing out of 387`; full `go test ./...` and `git diff --check` passed. |
| P6.8 contact outbound voice call parity | `internal/router/router.go`, `internal/handler/api/v1/contact_handler.go`, `internal/service/contact_service.go`, `internal/model/call.go`, contact handler tests | `reference/chatwoot/config/routes.rb:216`, `reference/chatwoot/enterprise/app/controllers/api/v1/accounts/contacts/calls_controller.rb`, `reference/chatwoot/enterprise/app/services/voice/outbound_call_builder.rb`, `reference/chatwoot/enterprise/app/services/voice/call_message_builder.rb`, `reference/chatwoot/enterprise/app/models/call.rb`, dashboard `api/contacts.js`, `store/modules/contacts/actions.js`, `api/channel/voice/voiceAPIClient.js` | Contact outbound calls now match the Chatwoot enterprise route boundary: account contact lookup, current user's assigned `Channel::TwilioSms` inbox lookup, `voice_enabled` guard, phone-number guard, open display-ID conversation reuse only for same inbox/contact, new ContactInbox/open conversation creation when needed, persisted outgoing Twilio call metadata, linked `voice_call` message content attributes, and raw `{ conversation_id, inbox_id, call_sid, conference_sid }` response. | Review by `feat(contacts): initiate voice calls`; focused contact call tests cover success/reuse/resolved-hint ignored/no-phone/non-voice/unassigned cases; route dump/parity regenerated to `TOTAL: 861` and `299 exact, 7 parameter-compatible, 0 missing out of 306`; full `go test ./...` and `git diff --check` passed. |
| P6 conversation transcript response parity | `internal/handler/api/v1/conversation_handler.go`, conversation handler tests | `reference/chatwoot/app/controllers/api/v1/accounts/conversations_controller.rb`, dashboard `api/inbox/conversation.js` | Account conversation transcript now follows Chatwoot's controller contract: missing email returns `422 { error: "email param missing" }`, nonblank email schedules through the existing service boundary and returns empty `200 OK`, and invalid-looking but nonblank email values are not rejected by local email format validation. | Review by `feat(conversations): align transcript responses`; focused transcript handler/service tests, combined handler/service/router tests, full `go test ./...`, and `git diff --check` must pass. |
| P6 conversation transcript response parity | `internal/handler/api/v1/conversation_handler.go`, conversation handler tests | `reference/chatwoot/app/controllers/api/v1/accounts/conversations_controller.rb`, dashboard `api/inbox/conversation.js` | Account conversation transcript now follows Chatwoot's controller contract: missing email returns `422 { error: "email param missing" }`, nonblank email schedules through the existing service boundary and returns empty `200 OK`, and invalid-looking but nonblank email values are not rejected by local email format validation. | Review by `feat(conversations): align transcript responses`; focused transcript handler/service tests, combined handler/service/router tests, full `go test ./...`, and `git diff --check` passed. |
| P6 conversation custom attributes response parity | `internal/handler/api/v1/conversation_handler.go`, conversation handler tests | `reference/chatwoot/app/controllers/api/v1/accounts/conversations_controller.rb`, `app/views/api/v1/accounts/conversations/custom_attributes.json.jbuilder`, dashboard `api/inbox/conversation.js`, conversation store action | Account conversation custom attribute updates now return Chatwoot `{ custom_attributes: ... }` only, matching the store action that reads `response.data.custom_attributes`, instead of returning the full conversation serializer with unrelated fields. Empty/null JSON serializes as `{}`. | Review by `feat(conversations): align custom attribute response`; focused handler tests, combined handler/service/router tests, full `go test ./...`, and `git diff --check` passed. |
| P6 message retry status parity | `internal/service/message_service.go`, `internal/handler/api/v1/message_handler.go`, message service/handler tests | `reference/chatwoot/app/controllers/api/v1/accounts/conversations/messages_controller.rb`, `app/views/api/v1/accounts/conversations/messages/retry.json.jbuilder`, dashboard `api/inbox/message.js` | Account message retry now follows Chatwoot: status resets to `sent`, `content_attributes` is cleared to `{}`, response returns the message serializer, and the existing durable SendReplyJob path is queued when a worker pool is configured. | Review by `feat(messages): align retry status parity`; focused retry service/handler tests, combined handler/service tests, full `go test ./...`, and `git diff --check` must pass. |
| P6 message retry status parity | `internal/service/message_service.go`, `internal/handler/api/v1/message_handler.go`, message service/handler tests | `reference/chatwoot/app/controllers/api/v1/accounts/conversations/messages_controller.rb`, `app/views/api/v1/accounts/conversations/messages/retry.json.jbuilder`, dashboard `api/inbox/message.js` | Account message retry now follows Chatwoot: status resets to `sent`, `content_attributes` is cleared to `{}`, response returns the message serializer, and the existing durable SendReplyJob path is queued when a worker pool is configured. | Review by `feat(messages): align retry status parity`; focused retry service/handler tests, combined handler/service tests, full `go test ./...`, and `git diff --check` passed. |
| P4.9 assignment policies payload/binding parity | `internal/router/router.go`, `internal/handler/api/v1/assignment_policy_handler.go`, `internal/service/assignment_policy_service.go`, `internal/repository/assignment_policy_repo.go`, `internal/model/assignment_policy.go`, assignment policy handler/service/repository/router tests | `reference/chatwoot/config/routes.rb:306-313`, `reference/chatwoot/app/controllers/api/v1/accounts/assignment_policies_controller.rb`, `reference/chatwoot/app/controllers/api/v1/accounts/assignment_policies/inboxes_controller.rb`, `reference/chatwoot/app/controllers/api/v1/accounts/inboxes/assignment_policies_controller.rb`, assignment policy Jbuilder views, dashboard `api/assignmentPolicies.js`, `store/modules/assignmentPolicies.js` | Account assignment policies now use the Chatwoot model fields and response contracts: list returns a raw array, show/create/update return raw policy objects, delete returns empty `200 OK`, raw and `{ assignment_policy: ... }` request bodies are accepted, inbox assignment policy GET/POST/DELETE returns raw policy/empty `200 OK`, and policy inbox lists return `{ inboxes: [...] }`. | Review by `feat(assignment-policies): align chatwoot payloads`; focused AssignmentPolicy handler tests, service/repository/router/app/migrate/route-parity packages, escalated full `go test ./...`, route dump `TOTAL: 906`, tracked route parity `353 exact, 0 method-compatible, 9 parameter-compatible, 0 missing out of 362`, and `git diff --check` passed. |
| Phase 2/3 drift audit | `cmd/route_parity`, `docs/parity/*`, serializer tests | `reference/chatwoot/config/routes.rb`, controller Jbuilder views, reused frontend API clients | Convert any smoke/reference mismatch into a named route, controller, or serializer slice. Static route extraction remains acceptable until Ruby/Bundler is available. | Regenerated route parity shows 0 missing tracked frontend routes; new serializer fixtures cover the drift. |
| Phase 6 placeholder burn-down | Account/contact/conversation/message/inbox handlers and services | Matching reference controllers/Jbuilder views plus reused frontend screens | Re-run placeholder audit and assign every frontend-reachable stub to a specific owner. Burn down the highest-impact stubs before broad feature expansion. | `rg` placeholder audit is recorded here; no reused-frontend critical path is ownerless. |
@@ -252,6 +254,7 @@ This ledger records the committed parity checkpoints that future slices should b
| Commit | Scope | Verification summary | Follow-up state |
| --- | --- | --- | --- |
| `feat(notifications): tighten chatwoot scoping` | Advances P3.35 account notification scoping hardening by matching Chatwoot `NotificationsController#fetch_notification`, `NotificationFinder`, notification routes `283-291`, index Jbuilder behavior, and reused dashboard `notifications.js`. GoChat now scopes show, update/read, destroy, snooze, unread, and unread_count to the current user and account; parses snooze timestamps as Unix seconds; merges `meta.last_snoozed_at: null`; treats missing `snoozed_until` as a scoped no-op; and keeps destroy as empty `200 OK`. | `go test ./internal/handler/api/v1 -run Notification -count=1`; `go test ./internal/repository -run Notification -count=1`; `go test ./internal/service -run Notification -count=1`; full `go test ./...`; `git diff --check`. Route artifacts are unchanged. | P3.35 moves to Review for current notification action scoping evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. |
| `feat(reports): align year in review` | Advances P3.34 API v2 year-in-review parity by matching Chatwoot `Api::V2::Accounts::YearInReviewsController#show`, `YearInReviewBuilder`, route `505`, current-user `ui_settings` caching, and reused dashboard `api/yearInReview.js`. GoChat now exposes `GET /api/v2/accounts/:account_id/year_in_review`, returns raw `{ year, total_conversations, busiest_day, support_personality }`, defaults missing `year` to `2025`, stores cached data under `year_in_review_<account_id>_<year>`, counts current-user assigned conversations in the selected year, formats the busiest day as `Mon DD`, and truncates average `first_response` seconds. | `go test ./internal/service -run YearInReview -count=1`; `go test ./internal/handler/api/v1 -run YearInReview -count=1`; `go test ./internal/router ./cmd/route_parity -run 'RegisterRoutes\|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: 951`; tracked route parity is `401 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 414`. | P3.34 moves to Review for current API v2 year-in-review evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. |
| `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. |
@@ -2267,6 +2270,7 @@ Verification milestone gates:
## Progress Log
- 2026-06-06: P3.35 account notification scoping checkpoint prepared as `feat(notifications): tighten chatwoot scoping`; audited Chatwoot notification routes `283-291`, `NotificationsController`, `NotificationFinder`, notification index Jbuilder, and reused dashboard `api/notifications.js`. Account notification show/update/destroy/snooze/unread/unread_count now use current-user/current-account scope, cross-account and cross-user rows return `404`, `snoozed_until` is parsed as Unix seconds, snooze merges `meta.last_snoozed_at: null`, absent `snoozed_until` is a scoped no-op returning the notification, and destroy returns empty `200 OK`. Focused notification handler/repository/service tests, full `go test ./...`, and `git diff --check` passed. No route artifacts changed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke.
- 2026-06-06: P3.13 dashboard apps checkpoint prepared as `feat(dashboard-apps): align chatwoot payloads`; audited Chatwoot `routes.rb:130`, `DashboardAppsController`, dashboard app Jbuilder views, `DashboardApp` content schema, reused dashboard `api/dashboardApps.js`, Vuex `dashboardApps` store, and DashboardApps modal/index components. Dashboard app routes are now tracked, create/update accept raw frontend bodies as well as `{ dashboard_app: ... }`, create returns raw `200 OK` payloads, list/show/create/update return only `id`, `title`, `content`, and `created_at`, show/update/delete are account-scoped, delete returns `204`, and content validation rejects empty arrays, non-frame widgets, and non-HTTP(S) URLs. Focused dashboard app handler/service tests, combined handler/service/repository/router/route-parity tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed; route dump remains `TOTAL: 907` and tracked route parity is `357 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 370`.
- 2026-06-06: P3.12 account Dyte integration checkpoint prepared as `feat(integrations): align dyte meeting routes`; audited Chatwoot `routes.rb:357-358`, `Api::V1::Accounts::Integrations::DyteController`, `Integrations::Dyte::ProcessorService`, `lib/dyte.rb`, reused dashboard `api/integrations/dyte.js`, `VideoCallButton.vue`, and the Dyte message bubble. Account Dyte create-meeting/add-participant routes are now registered and tracked, create-meeting resolves conversations by display ID, checks inbox access, loads account hook credentials, creates an outgoing `integrations` message with `content_attributes.type=dyte`, and returns the normal message serializer; add-participant rejects non-integration messages with the reference error and returns the Dyte participant token payload through a fakeable backend. Focused Dyte service/handler tests, combined handler/service/router/app/route-parity tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed; route dump is `TOTAL: 907` and tracked route parity is `355 exact, 0 method-compatible, 9 parameter-compatible, 0 missing out of 364`.
- 2026-06-06: P3.2 account-user inviter checkpoint prepared as `feat(account-users): align inviter id`; audited Chatwoot `AccountUser` schema, `AgentBuilder#create_account_user`, `api/v1/models/_user.json.jbuilder`, and enterprise `Audit::AccountUser`. GoChat now persists invitation source through the Chatwoot `inviter_id` column/JSON name instead of the local `invited_by` column, copies existing `invited_by` values forward in migration `000031`, emits account-user lifecycle events with `inviter_id`, and verifies agent creation stores the current user as inviter without leaking inviter fields through the `_agent` serializer. Focused model/agent/service/repository/migration tests, full `go test ./...`, and `git diff --check` passed. Continue remaining P3.2 invitation mail/confirmation drift or B12 live smoke.
@@ -2468,5 +2472,5 @@ 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.
- 2026-06-06: P3.34 API v2 year-in-review checkpoint prepared as `feat(reports): align year in review`; audited Chatwoot year-in-review route/controller/builder and reused dashboard `api/yearInReview.js`. GoChat now exposes and tracks `GET /api/v2/accounts/:account_id/year_in_review`, returns raw `{ year, total_conversations, busiest_day, support_personality }`, defaults missing `year` to `2025`, caches per current user in `ui_settings`, counts selected-year assigned conversations, formats busiest day as `Mon DD`, and truncates average `first_response` seconds from reporting events. Focused YearInReview service/handler tests, router/route-parity tests, route dump/parity regeneration (`951` routes; `401 exact`, `13 parameter-compatible`, `0 missing out of 414`), 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.
- 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` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke.
- 2026-06-06: P3.34 API v2 year-in-review checkpoint prepared as `feat(reports): align year in review`; audited Chatwoot year-in-review route/controller/builder and reused dashboard `api/yearInReview.js`. GoChat now exposes and tracks `GET /api/v2/accounts/:account_id/year_in_review`, returns raw `{ year, total_conversations, busiest_day, support_personality }`, defaults missing `year` to `2025`, caches per current user in `ui_settings`, counts selected-year assigned conversations, formats busiest day as `Mon DD`, and truncates average `first_response` seconds from reporting events. Focused YearInReview service/handler tests, router/route-parity tests, route dump/parity regeneration (`951` routes; `401 exact`, `13 parameter-compatible`, `0 missing out of 414`), full `go test ./...`, and `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke.
+48 -14
View File
@@ -2,7 +2,9 @@ package v1
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
@@ -81,7 +83,9 @@ func (h *NotificationHandler) Get(c *gin.Context) {
return
}
notification, svcErr := h.notificationService.GetNotification(c.Request.Context(), notificationID)
accountID := getAccountID(c)
userID := getUserID(c)
notification, svcErr := h.notificationService.GetNotificationByAccount(c.Request.Context(), notificationID, userID, accountID)
if svcErr != nil {
handleServiceError(c, svcErr)
return
@@ -99,15 +103,10 @@ func (h *NotificationHandler) Update(c *gin.Context) {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid notification id")
return
}
accountID := getAccountID(c)
userID := getUserID(c)
// MarkRead only returns error; need to fetch updated notification for response
if svcErr := h.notificationService.MarkRead(c.Request.Context(), notificationID); svcErr != nil {
handleServiceError(c, svcErr)
return
}
// Return the updated notification (Chatwoot renders json: @notification)
notification, svcErr := h.notificationService.GetNotification(c.Request.Context(), notificationID)
notification, svcErr := h.notificationService.MarkReadByAccount(c.Request.Context(), notificationID, userID, accountID)
if svcErr != nil {
handleServiceError(c, svcErr)
return
@@ -147,9 +146,10 @@ func (h *NotificationHandler) MarkAllRead(c *gin.Context) {
// GET /api/v1/accounts/:account_id/notifications/unread_count
// Reference: Chatwoot unread_count — render json: @unread_count
func (h *NotificationHandler) UnreadCount(c *gin.Context) {
accountID := getAccountID(c)
userID := getUserID(c)
count, err := h.notificationService.GetUnreadCount(c.Request.Context(), userID)
count, err := h.notificationService.GetUnreadCountByAccount(c.Request.Context(), userID, accountID)
if err != nil {
applogger.L().Errorf("UnreadCount notifications: %v", err)
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "Failed to count unread notifications")
@@ -173,14 +173,23 @@ func (h *NotificationHandler) Snooze(c *gin.Context) {
userID := getUserID(c)
var req struct {
SnoozedUntil string `json:"snoozed_until"`
SnoozedUntil interface{} `json:"snoozed_until"`
}
if err := c.ShouldBindJSON(&req); err != nil {
if err := bindOptionalNotificationJSON(c, &req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid request body")
return
}
if req.SnoozedUntil == nil || fmt.Sprint(req.SnoozedUntil) == "" {
notification, svcErr := h.notificationService.GetNotificationByAccount(c.Request.Context(), notificationID, userID, accountID)
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
c.JSON(http.StatusOK, serializeNotification(notification))
return
}
snoozedUntil, parseErr := time.Parse(time.RFC3339, req.SnoozedUntil)
snoozedUntil, parseErr := parseNotificationUnixTime(req.SnoozedUntil)
if parseErr != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid snoozed_until format")
return
@@ -227,7 +236,9 @@ func (h *NotificationHandler) Destroy(c *gin.Context) {
return
}
if svcErr := h.notificationService.DeleteNotification(c.Request.Context(), notificationID); svcErr != nil {
accountID := getAccountID(c)
userID := getUserID(c)
if svcErr := h.notificationService.DeleteNotificationByAccount(c.Request.Context(), notificationID, userID, accountID); svcErr != nil {
handleServiceError(c, svcErr)
return
}
@@ -341,3 +352,26 @@ func bindOptionalNotificationJSON(c *gin.Context, target interface{}) error {
}
return c.ShouldBindJSON(target)
}
func parseNotificationUnixTime(value interface{}) (time.Time, error) {
switch v := value.(type) {
case float64:
return time.Unix(int64(v), 0).UTC(), nil
case int64:
return time.Unix(v, 0).UTC(), nil
case int:
return time.Unix(int64(v), 0).UTC(), nil
case string:
seconds, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return time.Time{}, err
}
return time.Unix(seconds, 0).UTC(), nil
default:
seconds, err := strconv.ParseInt(fmt.Sprint(v), 10, 64)
if err != nil {
return time.Time{}, err
}
return time.Unix(seconds, 0).UTC(), nil
}
}
@@ -54,14 +54,16 @@ func setupNotificationRouter(handler *NotificationHandler) *gin.Engine {
c.Next()
})
router.GET("/api/v1/accounts/:account_id/notifications", handler.List)
router.GET("/api/v1/accounts/:account_id/notifications/:notification_id", handler.Get)
router.POST("/api/v1/accounts/:account_id/notifications/read_all", handler.MarkAllRead)
router.GET("/api/v1/accounts/:account_id/notifications/unread_count", handler.UnreadCount)
router.POST("/api/v1/accounts/:account_id/notifications/destroy_all", handler.DestroyAll)
router.DELETE("/api/v1/accounts/:account_id/notifications/destroy_all", handler.DestroyAll)
router.GET("/api/v1/accounts/:account_id/notifications/:notification_id", handler.Get)
router.PUT("/api/v1/accounts/:account_id/notifications/:notification_id", handler.Update)
router.DELETE("/api/v1/accounts/:account_id/notifications/:notification_id", handler.Destroy)
// G8 extension routes
router.POST("/api/v1/accounts/:account_id/notifications/:notification_id/snooze", handler.Snooze)
router.POST("/api/v1/accounts/:account_id/notifications/:notification_id/unread", handler.Unread)
router.POST("/api/v1/accounts/:account_id/notifications/destroy_all", handler.DestroyAll)
router.DELETE("/api/v1/accounts/:account_id/notifications/destroy_all", handler.DestroyAll)
return router
}
@@ -174,6 +176,87 @@ func TestNotificationGetDifferentID(t *testing.T) {
sqlDB.Close()
}
func TestNotificationMutationsAreScopedToCurrentUserAndAccount(t *testing.T) {
db := setupNotificationDB(t)
handler := setupNotificationHandler(t, db)
router := setupNotificationRouter(handler)
user := &model.User{Name: "Scoped User", Email: "scoped@example.com", Password: "pass", AccountID: 1}
otherUser := &model.User{Name: "Other User", Email: "scoped-other@example.com", Password: "pass", AccountID: 2}
require.NoError(t, db.Create(user).Error)
require.NoError(t, db.Create(otherUser).Error)
accountID := uint(1)
otherAccountID := uint(2)
own := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "message_created", PrimaryActorType: "Conversation", PrimaryActorID: 1}
otherAccount := &model.Notification{UserID: user.ID, AccountID: &otherAccountID, NotificationType: "message_created", PrimaryActorType: "Conversation", PrimaryActorID: 2}
otherOwner := &model.Notification{UserID: otherUser.ID, AccountID: &accountID, NotificationType: "message_created", PrimaryActorType: "Conversation", PrimaryActorID: 3}
require.NoError(t, db.Create(own).Error)
require.NoError(t, db.Create(otherAccount).Error)
require.NoError(t, db.Create(otherOwner).Error)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/1/notifications/%d", otherAccount.ID), nil)
req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10))
router.ServeHTTP(w, req)
require.Equal(t, http.StatusNotFound, w.Code)
w = httptest.NewRecorder()
req, _ = http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/1/notifications/%d", otherOwner.ID), nil)
req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10))
router.ServeHTTP(w, req)
require.Equal(t, http.StatusNotFound, w.Code)
w = httptest.NewRecorder()
req, _ = http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/1/notifications/%d", own.ID), nil)
req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10))
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
var reloaded model.Notification
require.NoError(t, db.First(&reloaded, own.ID).Error)
assert.NotNil(t, reloaded.ReadAt)
w = httptest.NewRecorder()
req, _ = http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/1/notifications/%d", otherAccount.ID), nil)
req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10))
router.ServeHTTP(w, req)
require.Equal(t, http.StatusNotFound, w.Code)
var otherAccountReloaded model.Notification
require.NoError(t, db.First(&otherAccountReloaded, otherAccount.ID).Error)
w = httptest.NewRecorder()
req, _ = http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/1/notifications/%d", own.ID), nil)
req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10))
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
require.Error(t, db.First(&reloaded, own.ID).Error)
sqlDB, _ := db.DB()
sqlDB.Close()
}
func TestNotificationUnreadCountIsAccountScoped(t *testing.T) {
db := setupNotificationDB(t)
handler := setupNotificationHandler(t, db)
router := setupNotificationRouter(handler)
user := &model.User{Name: "Unread Scoped User", Email: "unread-scoped@example.com", Password: "pass", AccountID: 1}
require.NoError(t, db.Create(user).Error)
accountID := uint(1)
otherAccountID := uint(2)
require.NoError(t, db.Create(&model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "message_created"}).Error)
require.NoError(t, db.Create(&model.Notification{UserID: user.ID, AccountID: &otherAccountID, NotificationType: "message_created"}).Error)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/v1/accounts/1/notifications/unread_count", nil)
req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10))
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "1", strings.TrimSpace(w.Body.String()))
sqlDB, _ := db.DB()
sqlDB.Close()
}
func TestNotificationReadAll(t *testing.T) {
db := setupNotificationDB(t)
handler := setupNotificationHandler(t, db)
@@ -461,9 +544,9 @@ func TestNotificationHandler_SnoozeWithDB(t *testing.T) {
notif := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "conversation_assignment", PrimaryActorType: "conversation", PrimaryActorID: 1}
db.Create(notif)
// Snooze the notification
snoozeTime := time.Now().Add(2 * time.Hour).Format(time.RFC3339)
body := fmt.Sprintf(`{"snoozed_until":"%s"}`, snoozeTime)
// Chatwoot DateRangeHelper parses snoozed_until as Unix seconds.
snoozeUnix := time.Now().Add(2 * time.Hour).Unix()
body := fmt.Sprintf(`{"snoozed_until":%d}`, snoozeUnix)
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/1/notifications/%d/snooze", notif.ID), strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
@@ -476,6 +559,10 @@ func TestNotificationHandler_SnoozeWithDB(t *testing.T) {
var updated model.Notification
require.NoError(t, db.First(&updated, notif.ID).Error)
assert.NotNil(t, updated.SnoozedUntil)
assert.Equal(t, snoozeUnix, updated.SnoozedUntil.Unix())
var meta map[string]any
require.NoError(t, json.Unmarshal(updated.AdditionalAttributes, &meta))
assert.Contains(t, meta, "last_snoozed_at")
sqlDB, _ := db.DB()
sqlDB.Close()
@@ -486,8 +573,8 @@ func TestNotificationHandler_Snooze_InvalidID(t *testing.T) {
handler := setupNotificationHandler(t, db)
router := setupNotificationRouter(handler)
snoozeTime := time.Now().Add(2 * time.Hour).Format(time.RFC3339)
body := fmt.Sprintf(`{"snoozed_until":"%s"}`, snoozeTime)
snoozeTime := time.Now().Add(2 * time.Hour).Unix()
body := fmt.Sprintf(`{"snoozed_until":%d}`, snoozeTime)
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/api/v1/accounts/1/notifications/abc/snooze", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
@@ -517,7 +604,7 @@ func TestNotificationHandler_Snooze_MissingBody(t *testing.T) {
req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10))
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Equal(t, http.StatusOK, w.Code)
sqlDB, _ := db.DB()
sqlDB.Close()
+64 -1
View File
@@ -2,6 +2,7 @@ package repository
import (
"context"
"encoding/json"
"time"
"gorm.io/gorm"
@@ -38,6 +39,16 @@ func (r *NotificationRepo) FindByID(ctx context.Context, id uint) (*model.Notifi
return &n, nil
}
// FindByUserAndAccount retrieves a notification using Chatwoot's current_user/current_account scope.
func (r *NotificationRepo) FindByUserAndAccount(ctx context.Context, id, userID, accountID uint) (*model.Notification, error) {
var n model.Notification
err := r.db.WithContext(ctx).Where("id = ? AND user_id = ? AND account_id = ?", id, userID, accountID).First(&n).Error
if err != nil {
return nil, err
}
return &n, nil
}
// ListByUser retrieves all notifications for a user with pagination.
func (r *NotificationRepo) ListByUser(ctx context.Context, userID uint, offset, limit int) ([]model.Notification, int64, error) {
var notifications []model.Notification
@@ -135,6 +146,21 @@ func (r *NotificationRepo) MarkRead(ctx context.Context, id uint) error {
return nil
}
// MarkReadByUserAndAccount marks a single scoped notification as read.
func (r *NotificationRepo) MarkReadByUserAndAccount(ctx context.Context, id, userID, accountID uint) (*model.Notification, error) {
now := time.Now().UTC()
result := r.db.WithContext(ctx).Model(&model.Notification{}).
Where("id = ? AND user_id = ? AND account_id = ?", id, userID, accountID).
Update("read_at", &now)
if result.Error != nil {
return nil, result.Error
}
if result.RowsAffected == 0 {
return nil, gorm.ErrRecordNotFound
}
return r.FindByUserAndAccount(ctx, id, userID, accountID)
}
// MarkAllReadByUser marks all unread notifications for a user as read.
func (r *NotificationRepo) MarkAllReadByUser(ctx context.Context, userID uint) error {
now := time.Now()
@@ -163,6 +189,20 @@ func (r *NotificationRepo) Delete(ctx context.Context, id uint) error {
return r.db.WithContext(ctx).Delete(&model.Notification{}, id).Error
}
// DeleteByUserAndAccount deletes a notification using Chatwoot's current user/account scope.
func (r *NotificationRepo) DeleteByUserAndAccount(ctx context.Context, id, userID, accountID uint) error {
result := r.db.WithContext(ctx).
Where("id = ? AND user_id = ? AND account_id = ?", id, userID, accountID).
Delete(&model.Notification{})
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
return nil
}
// CountUnreadByUser counts unread notifications for a user.
func (r *NotificationRepo) CountUnreadByUser(ctx context.Context, userID uint) (int64, error) {
var count int64
@@ -172,13 +212,36 @@ func (r *NotificationRepo) CountUnreadByUser(ctx context.Context, userID uint) (
return count, err
}
// CountUnreadByUserAndAccount counts unread notifications for the current account only.
func (r *NotificationRepo) CountUnreadByUserAndAccount(ctx context.Context, userID, accountID uint) (int64, error) {
var count int64
err := r.db.WithContext(ctx).Model(&model.Notification{}).
Where("user_id = ? AND account_id = ? AND read_at IS NULL", userID, accountID).
Count(&count).Error
return count, err
}
// Snooze sets the snoozed_until timestamp and clears read_at for a notification.
// Returns the updated notification.
// Reference: Chatwoot notifications_controller.rb#snooze
func (r *NotificationRepo) Snooze(ctx context.Context, id, userID, accountID uint, snoozedUntil time.Time) (*model.Notification, error) {
var notification model.Notification
if err := r.db.WithContext(ctx).Where("id = ? AND user_id = ? AND account_id = ?", id, userID, accountID).First(&notification).Error; err != nil {
return nil, err
}
meta := map[string]interface{}{}
if len(notification.AdditionalAttributes) > 0 {
_ = json.Unmarshal(notification.AdditionalAttributes, &meta)
}
meta["last_snoozed_at"] = nil
encodedMeta, err := json.Marshal(meta)
if err != nil {
return nil, err
}
result := r.db.WithContext(ctx).Model(&model.Notification{}).
Where("id = ? AND user_id = ? AND account_id = ?", id, userID, accountID).
Updates(map[string]interface{}{"snoozed_until": snoozedUntil, "read_at": nil})
Updates(map[string]interface{}{"snoozed_until": snoozedUntil.UTC(), "read_at": nil, "additional_attributes": encodedMeta})
if result.Error != nil {
return nil, result.Error
}
+20
View File
@@ -50,6 +50,11 @@ func (s *NotificationService) GetNotification(ctx context.Context, id uint) (*mo
return s.notifRepo.FindByID(ctx, id)
}
// GetNotificationByAccount retrieves a notification scoped like Chatwoot fetch_notification.
func (s *NotificationService) GetNotificationByAccount(ctx context.Context, id, userID, accountID uint) (*model.Notification, error) {
return s.notifRepo.FindByUserAndAccount(ctx, id, userID, accountID)
}
// ListNotifications retrieves all notifications for a user with pagination.
func (s *NotificationService) ListNotifications(ctx context.Context, userID uint, page, perPage int) ([]model.Notification, int64, error) {
offset := (page - 1) * perPage
@@ -85,6 +90,11 @@ func (s *NotificationService) MarkRead(ctx context.Context, id uint) error {
return s.notifRepo.MarkRead(ctx, id)
}
// MarkReadByAccount marks a single notification as read within current user/account scope.
func (s *NotificationService) MarkReadByAccount(ctx context.Context, id, userID, accountID uint) (*model.Notification, error) {
return s.notifRepo.MarkReadByUserAndAccount(ctx, id, userID, accountID)
}
// MarkAllRead marks all unread notifications for a user as read.
func (s *NotificationService) MarkAllRead(ctx context.Context, userID uint) error {
return s.notifRepo.MarkAllReadByUser(ctx, userID)
@@ -104,11 +114,21 @@ func (s *NotificationService) DeleteNotification(ctx context.Context, id uint) e
return s.notifRepo.Delete(ctx, id)
}
// DeleteNotificationByAccount deletes a scoped notification.
func (s *NotificationService) DeleteNotificationByAccount(ctx context.Context, id, userID, accountID uint) error {
return s.notifRepo.DeleteByUserAndAccount(ctx, id, userID, accountID)
}
// GetUnreadCount returns the number of unread notifications for a user.
func (s *NotificationService) GetUnreadCount(ctx context.Context, userID uint) (int64, error) {
return s.notifRepo.CountUnreadByUser(ctx, userID)
}
// GetUnreadCountByAccount returns the unread count for the current account only.
func (s *NotificationService) GetUnreadCountByAccount(ctx context.Context, userID, accountID uint) (int64, error) {
return s.notifRepo.CountUnreadByUserAndAccount(ctx, userID, accountID)
}
// --- Notification Preference operations ---
// GetPreferences retrieves all notification preferences for a user within an account.