diff --git a/cmd/route_parity/main.go b/cmd/route_parity/main.go index fd8d057d..723fe566 100644 --- a/cmd/route_parity/main.go +++ b/cmd/route_parity/main.go @@ -226,6 +226,11 @@ var criticalRoutes = []route{ {Method: "PATCH", Path: "/api/v1/accounts/:account_id/integrations/hooks/:id", Controller: "api/v1/accounts/integrations/hooks#update", Source: "routes.rb:346"}, {Method: "DELETE", Path: "/api/v1/accounts/:account_id/integrations/hooks/:id", Controller: "api/v1/accounts/integrations/hooks#destroy", Source: "routes.rb:346"}, {Method: "POST", Path: "/api/v1/accounts/:account_id/integrations/hooks/:id/process_event", Controller: "api/v1/accounts/integrations/hooks#process_event", Source: "routes.rb:348"}, + {Method: "POST", Path: "/api/v1/accounts/:account_id/integrations/slack", Controller: "api/v1/accounts/integrations/slack#create", Source: "routes.rb:350"}, + {Method: "PUT", Path: "/api/v1/accounts/:account_id/integrations/slack", Controller: "api/v1/accounts/integrations/slack#update", Source: "routes.rb:350"}, + {Method: "PATCH", Path: "/api/v1/accounts/:account_id/integrations/slack", Controller: "api/v1/accounts/integrations/slack#update", Source: "routes.rb:350"}, + {Method: "DELETE", Path: "/api/v1/accounts/:account_id/integrations/slack", Controller: "api/v1/accounts/integrations/slack#destroy", Source: "routes.rb:350"}, + {Method: "GET", Path: "/api/v1/accounts/:account_id/integrations/slack/list_all_channels", Controller: "api/v1/accounts/integrations/slack#list_all_channels", Source: "routes.rb:352"}, {Method: "POST", Path: "/api/v1/accounts/:account_id/integrations/dyte/create_a_meeting", Controller: "api/v1/accounts/integrations/dyte#create_a_meeting", Source: "routes.rb:357"}, {Method: "POST", Path: "/api/v1/accounts/:account_id/integrations/dyte/add_participant_to_meeting", Controller: "api/v1/accounts/integrations/dyte#add_participant_to_meeting", Source: "routes.rb:358"}, diff --git a/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md b/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md index 1b21fa39..5f334af4 100644 --- a/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md +++ b/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md @@ -49,16 +49,16 @@ Hermes task landing checklist: ## Current Baseline -- Current tracking checkpoint: 2026-06-06 nested contact inbox creation checkpoint, prepared as `feat(contacts): align contact inbox creation`. -- Latest implementation checkpoint: this checkpoint, prepared as `feat(contacts): align contact inbox creation`. -- Latest documentation/tooling checkpoint: this tracker update for P3.23 plus the landed parity tracker history; this document is the active follow-up plan and supersedes `.hermes/plans/*`. +- Current tracking checkpoint: 2026-06-06 Slack integration parity checkpoint, prepared as `feat(integrations): align slack parity`. +- Latest implementation checkpoint: this checkpoint, prepared as `feat(integrations): align slack parity`. +- Latest documentation/tooling checkpoint: this tracker update for P3.24 plus the landed parity tracker history; this document is the active follow-up plan and supersedes `.hermes/plans/*`. - Plan landing status: complete for the current known Hermes plans and user-confirmed scope. Future work should update this file directly instead of opening a parallel tracker. -- Worktree status at this implementation checkpoint: nested contact inbox creation from `reference/chatwoot/config/routes.rb:212`, `Api::V1::Accounts::Contacts::ContactInboxesController#create`, `ContactInboxBuilder`, `HmacConcern`, and the contact inbox Jbuilder partial is implemented. `POST /api/v1/accounts/:account_id/contacts/:contact_id/contact_inboxes` now account-scopes contact/inbox resolution, accepts `inbox_id`, optional `source_id`, and `hmac_verified`, generates missing source IDs by supported channel, returns existing contact+inbox+source rows idempotently, stores HMAC verification only on creation, and returns raw `{ source_id, inbox }`. Live API/browser/enterprise smoke still needs the full PostgreSQL/Redis/Meilisearch/GoChat/Vite/Chrome stack. +- Worktree status at this implementation checkpoint: Slack integration create/update/delete/list channels from `reference/chatwoot/config/routes.rb:350-352`, `Api::V1::Accounts::Integrations::SlackController`, `Integrations::Slack::HookBuilder`, `Integrations::Slack::ChannelBuilder`, Slack Jbuilder app/hook partials, request specs, and the reused dashboard `integrations.js` API are implemented. GoChat now exposes no-trailing and trailing `POST/PATCH/PUT/DELETE /api/v1/accounts/:account_id/integrations/slack`, returns raw Chatwoot app payloads for create/update, returns raw channel arrays for `list_all_channels`, uses Slack OAuth code exchange on create, persists disabled Slack hooks with `app_id: slack`, updates `reference_id/settings/status` only after matching a real Slack channel, joins public channels, and returns empty `200 OK` deletes. 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. -- Route dump succeeds with `TOTAL: 933`; P3.22 changes account reporting-events behavior and expands tracked route parity without adding a new Go route. +- `go test ./...` passes when run outside the restricted socket sandbox; focused Slack handler/service/route tests pass in the sandbox. +- Route dump succeeds with `939` registered routes after Slack no-trailing and `PUT` aliases. - Route parity artifacts now exist under `docs/parity/` and are generated by `cmd/route_parity`. -- Tracked frontend-critical route audit covers 387 Chatwoot routes: 374 exact, 0 method-compatible, 13 parameter-compatible, 0 missing. The 13 parameter-compatible routes are Gin-internal parameter-name differences for nested AgentCapacityPolicy users/inbox limits, dashboard app member `:id` names, plus the public article `.md`/`.png` suffixes served through the same external article route dispatcher. +- Tracked frontend-critical route audit covers 392 Chatwoot routes: 379 exact, 0 method-compatible, 13 parameter-compatible, 0 missing. The 13 parameter-compatible routes are Gin-internal parameter-name differences for nested AgentCapacityPolicy users/inbox limits, dashboard app member `:id` names, plus the public article `.md`/`.png` suffixes served through the same external article route dispatcher. - `/api/v1/widget` stubs are burned down and public inbox/contact/conversation/message core flows are backed by real handlers. - Handler test stability fixes are committed into the baseline before feature parity work continues. - `.codegraph/` is generated indexing output and is not part of tracked product code. @@ -140,9 +140,10 @@ This table is the shortest authoritative handoff view. If an older lower section | Priority | Workstream | Current state | Next checkpoint | Commit close rule | | --- | --- | --- | --- | --- | +| 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 387-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 Dyte routes from `routes.rb:357-358`, 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 Dyte create/join payload 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 account reporting-events 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 392-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`, 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, 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 Slack parity or from B12 findings. | Regenerate parity artifacts when routes change and add endpoint-family fixture tests. | | 3 | Phase 6 placeholder audit | Widget/public/webhook critical placeholders are burned down; inbox WhatsApp health/register-webhook and sync-template drift are closed; refreshed `docs/parity/placeholder_audit.md` shows only webhook nil-handler fallbacks still call `chatwootParityStub`; dashboard conversation transcript/custom-attribute response drift and message retry status drift are closed. | Keep in Review; reopen only if fresh `rg`, route smoke, or B12 finds a frontend-reachable placeholder/stub in account/contact/conversation/message/inbox/widget/public paths. | `rg` placeholder audit and `scripts/parity_frontend_smoke.sh --check` are recorded; no reused-frontend blocker is ownerless. | | 4 | P3.9 account agent-bot API | Implemented for the reused dashboard AgentBots settings route with no-trailing-slash routes, PATCH update, raw Jbuilder-style payloads, account mutation scope, system-bot show/list visibility, empty `200 OK` delete, and full reset/avatar action payloads. | Keep in Review; reopen only if live settings smoke exposes avatar upload storage or administrator-secret gating drift. | Focused AgentBot handler tests, service/router focused tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. | | 5 | P3.10 account webhooks API | Implemented for the reused dashboard Webhooks settings route with PATCH update, Chatwoot `{ payload }` list/mutation serializers, nested `{ webhook: ... }` bodies, generated secret, account-scoped mutations, URL/subscription validation, optional inbox serialization, and empty `200 OK` delete. | Keep in Review; reopen only if live settings smoke exposes audit writer or delivery-signature drift beyond the existing delivery service boundary. | Focused webhook handler/service/router tests, migration test, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. | @@ -169,6 +170,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.24 Slack integration parity | `internal/handler/api/v1/slack_integration_handler.go`, `internal/service/slack_integration_service.go`, `internal/repository/integration_hook_repo.go`, `internal/handler/api/v1/integration_hook_handler.go`, `cmd/route_parity/main.go`, Slack handler/service tests | `reference/chatwoot/config/routes.rb:350-352`, `reference/chatwoot/app/controllers/api/v1/accounts/integrations/slack_controller.rb`, `reference/chatwoot/lib/integrations/slack/hook_builder.rb`, `reference/chatwoot/lib/integrations/slack/channel_builder.rb`, `reference/chatwoot/app/views/api/v1/accounts/integrations/slack/create.json.jbuilder`, `reference/chatwoot/app/views/api/v1/accounts/integrations/slack/update.json.jbuilder`, `reference/chatwoot/app/views/api/v1/models/_app.json.jbuilder`, `reference/chatwoot/app/views/api/v1/models/_hook.json.jbuilder`, `reference/chatwoot/spec/requests/api/v1/accounts/integrations/slack_request_spec.rb`, `reference/chatwoot/app/javascript/dashboard/api/integrations.js`, `reference/chatwoot/app/javascript/dashboard/store/modules/integrations.js` | Done. Chatwoot Slack singleton behavior is implemented for the reused dashboard flow: frontend no-trailing `POST/PATCH/DELETE` routes and Rails `PUT` update are registered alongside trailing aliases; create accepts `code`/`inbox_id`, exchanges OAuth against Slack, persists disabled `app_id: slack` hooks with access tokens; update accepts `reference_id`, fetches private/public Slack channels with cursor pagination, joins public channels, persists `reference_id`, `settings.channel_name`, and enabled status only when the channel exists; create/update return the raw app partial with hooks; list-all returns raw Slack channel arrays; invalid channel returns `422 { error: "Invalid slack channel. Please try again" }`; delete returns empty `200 OK`. | Review by `feat(integrations): align slack parity`; focused handler tests cover no-trailing create raw app payload, empty delete, and PUT route availability; service tests cover OAuth exchange redirect/body, disabled hook creation, channel fetch/update/join, invalid/not-found, and raw channel lists through a fake Slack client; route parity is `379 exact, 13 parameter-compatible, 0 missing out of 392`; escalated full `go test ./...` and `git diff --check` passed. | | P3.23 nested contact inbox creation parity | `internal/handler/api/v1/contact_handler.go`, `internal/service/contact_inbox_service.go`, `internal/repository/contact_inbox_repo.go`, `internal/handler/api/v1/crm_serializer.go`, `internal/router/router.go`, `cmd/route_parity/main.go`, nested contact inbox handler/service/repository tests | `reference/chatwoot/config/routes.rb:212`, `reference/chatwoot/app/controllers/api/v1/accounts/contacts/contact_inboxes_controller.rb`, `reference/chatwoot/app/controllers/concerns/hmac_concern.rb`, `reference/chatwoot/app/builders/contact_inbox_builder.rb`, `reference/chatwoot/app/views/api/v1/accounts/contacts/contact_inboxes/create.json.jbuilder`, `reference/chatwoot/app/views/api/v1/models/_contact_inbox.json.jbuilder`, `reference/chatwoot/spec/controllers/api/v1/accounts/contacts/contact_inboxes_controller_spec.rb` | Done. Chatwoot `ContactInboxBuilder` behavior is implemented for `POST /api/v1/accounts/:account_id/contacts/:contact_id/contact_inboxes`: raw JSON/form/query params provide `inbox_id`, optional `source_id`, and `hmac_verified`; contact and inbox resolution is account-scoped; missing source IDs are generated by supported channel (`api`/`web_widget` UUID, email, sms phone, whatsapp phone without `+`, twilio sms/whatsapp medium); existing contact+inbox+source rows are returned idempotently; `hmac_verified` is set on creation; tokens are generated; inbox is preloaded; and the response is only `{ source_id, inbox: inbox_slim }`. | Review by `feat(contacts): align contact inbox creation`; focused handler tests cover raw payload shape, HMAC creation, generated source IDs, email idempotency, cross-account inbox rejection, and missing-phone Twilio failure; service tests cover WhatsApp/Twilio generation and idempotency; repository tests cover contact+inbox+source lookup; route parity, full `go test ./...`, and `git diff --check` passed. | | P3.2a invitation/confirmation mail parity | `internal/service/profile_service.go`, `internal/service/profile_confirmation_mailer.go`, `internal/handler/api/v1/profile_handler.go`, `internal/service/agent_service.go`, `internal/repository/agent_repo.go`, `internal/model/user.go`, `migrations/000032_add_users_unconfirmed_email.*`, profile/agent handler tests | `reference/chatwoot/app/controllers/api/v1/accounts/agents_controller.rb`, `reference/chatwoot/app/builders/agent_builder.rb`, `reference/chatwoot/app/views/devise/mailer/confirmation_instructions.html.erb`, `reference/chatwoot/spec/mailers/confirmation_instructions_spec.rb`, `reference/chatwoot/spec/enterprise/mailers/devise_mailer_spec.rb` for non-SAML invitation wording only | Done. A shared fakeable confirmation mailer builds Chatwoot-shaped confirmation/invitation payloads; profile resend persists confirmation/reset tokens and delivers no-op/confirmation/invitation states; newly created invited agents get workspace invitation mail; `unconfirmed_email` is modeled for email-update branch routing; environment SMTP remains a no-op when not configured. SSO/SAML/LDAP/OIDC mail variants stay excluded. | Review by `feat(profile): send confirmation invitations`; focused tests cover confirmed no-op, normal confirmation mail, invited workspace invitation mail, agent creation/inviter context, hashed reset-token persistence, and no network in default tests; full `go test ./...` and `git diff --check` passed. | | P5.11a Captain document crawl/schedule | `internal/service/captain_document_service.go`, `internal/service/captain_document_worker.go`, `internal/app/bootstrap.go` | `reference/chatwoot/enterprise/app/jobs/captain/documents/crawl_job.rb`, `schedule_syncs_job.rb`, `perform_sync_job.rb`, Firecrawl/simple parser jobs | Durable schedule/crawl producers and handlers with fakeable crawl/parser boundaries. Missing provider config is a failed `crawl_disabled` state, not placeholder success. | Review by `feat(captain): queue document crawl jobs`; focused worker tests prove enqueue, replay, account scope, idempotent scheduler, and disabled/failure states. | @@ -2436,3 +2438,4 @@ Verification milestone gates: - 2026-06-06: P3.22 account reporting events checkpoint prepared as `feat(reporting): align account events`; audited Chatwoot enterprise account reporting events controller/specs, route `234`, `DateRangeHelper`, and `_reporting_event` Jbuilder serializer. GoChat now returns `{ payload, meta }`, accepts optional Unix `since/until`, `inbox_id`, `user_id`, and `name` filters, orders account reporting events by `created_at DESC`, uses fixed 25-row pagination, and tracks the account reporting-events route. Focused ReportingEvent handler tests and route parity regeneration (`TOTAL: 933`, `374 exact`, `13 parameter-compatible`, `0 missing out of 387`) passed; full `go test ./...` and `git diff --check` passed. - 2026-06-06: Documentation checkpoint prepared as `docs: land contact inbox parity plan`; worktree was clean at `2072396 feat(reporting): align account events`, and the active plan now lands P3.23 nested contact inbox creation as the next executable slice. The row records Chatwoot `contacts/contact_inboxes#create`, `ContactInboxBuilder`, `HmacConcern`, contact inbox Jbuilder references, current Go owner files, source-ID/HMAC/idempotency/account-scope/serializer gaps, and focused exit gates. Verification for this docs-only checkpoint: `git diff --check`; next slice is `feat(contacts): align contact inbox creation`. - 2026-06-06: P3.23 nested contact inbox creation checkpoint prepared as `feat(contacts): align contact inbox creation`; audited Chatwoot nested contact inbox controller/specs, `ContactInboxBuilder`, `HmacConcern`, route `212`, and contact inbox Jbuilder serializer. GoChat now account-scopes nested contact/inbox creation, accepts raw JSON/form/query `inbox_id`, `source_id`, and `hmac_verified`, generates missing source IDs for API/WebWidget/Email/Sms/Whatsapp/Twilio channels, returns existing contact+inbox+source rows idempotently, persists HMAC verification on creation, and returns raw `{ source_id, inbox }`. Focused handler/service/repository tests passed; route parity and full `go test ./...` plus `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke. +- 2026-06-06: P3.24 Slack integration checkpoint prepared as `feat(integrations): align slack parity`; audited Chatwoot Slack singleton routes/controller/request specs, `Integrations::Slack::HookBuilder`, `Integrations::Slack::ChannelBuilder`, app/hook Jbuilder partials, and reused dashboard integrations API/store. GoChat now exposes no-trailing and trailing Slack singleton routes, supports `PUT` and `PATCH` update, creates disabled Slack hooks from OAuth `code`, returns raw app payloads, fetches Slack private/public channels with cursor pagination, joins public channels, persists selected channel `reference_id/settings/status`, returns raw channel arrays, maps invalid channels to Chatwoot's `422 { error }`, and deletes with empty `200 OK`. Focused handler/service tests, route dump/parity regeneration (`939` routes; `379 exact`, `13 parameter-compatible`, `0 missing out of 392`), escalated full `go test ./...`, and `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke. diff --git a/docs/parity/gochat_routes.txt b/docs/parity/gochat_routes.txt index 50918ae6..fa611828 100644 --- a/docs/parity/gochat_routes.txt +++ b/docs/parity/gochat_routes.txt @@ -74,6 +74,7 @@ DELETE /api/v1/accounts/:account_id/integrations/hooks/:id DELETE /api/v1/accounts/:account_id/integrations/linear/ DELETE /api/v1/accounts/:account_id/integrations/notion/ DELETE /api/v1/accounts/:account_id/integrations/shopify/ +DELETE /api/v1/accounts/:account_id/integrations/slack DELETE /api/v1/accounts/:account_id/integrations/slack/ DELETE /api/v1/accounts/:account_id/labels/:tag_id DELETE /api/v1/accounts/:account_id/macros/:macro_id @@ -531,6 +532,7 @@ PATCH /api/v1/accounts/:account_id/inboxes/:inbox_id/members/update_multiple PATCH /api/v1/accounts/:account_id/inboxes/:inbox_id/tiktok_channels/:tt_id PATCH /api/v1/accounts/:account_id/inboxes/:inbox_id/twilio_sms_channels/:tw_id PATCH /api/v1/accounts/:account_id/integrations/hooks/:id +PATCH /api/v1/accounts/:account_id/integrations/slack PATCH /api/v1/accounts/:account_id/integrations/slack/ PATCH /api/v1/accounts/:account_id/notification_settings PATCH /api/v1/accounts/:account_id/notification_settings/ @@ -704,6 +706,7 @@ POST /api/v1/accounts/:account_id/integrations/linear/create_issue POST /api/v1/accounts/:account_id/integrations/linear/link_issue POST /api/v1/accounts/:account_id/integrations/linear/unlink_issue POST /api/v1/accounts/:account_id/integrations/shopify/auth +POST /api/v1/accounts/:account_id/integrations/slack POST /api/v1/accounts/:account_id/integrations/slack/ POST /api/v1/accounts/:account_id/labels/ POST /api/v1/accounts/:account_id/labels/batch_add @@ -892,6 +895,8 @@ PUT /api/v1/accounts/:account_id/inboxes/:inbox_id/web_widget/theme_config PUT /api/v1/accounts/:account_id/inboxes/:inbox_id/web_widget_config PUT /api/v1/accounts/:account_id/inboxes/:inbox_id/working_hours PUT /api/v1/accounts/:account_id/integrations/hooks/:id +PUT /api/v1/accounts/:account_id/integrations/slack +PUT /api/v1/accounts/:account_id/integrations/slack/ PUT /api/v1/accounts/:account_id/labels/:tag_id PUT /api/v1/accounts/:account_id/macros/:macro_id PUT /api/v1/accounts/:account_id/notification_settings @@ -931,4 +936,4 @@ PUT /public/api/v1/csat_survey/:id PUT /public/api/v1/inboxes/:inbox_id/contacts/:contact_id PUT /public/api/v1/inboxes/:inbox_id/contacts/:contact_id/conversations/:conversation_id/messages/:message_id PUT /widget/direct_uploads/:upload_uuid -TOTAL: 933 +TOTAL: 938 diff --git a/docs/parity/route_parity.md b/docs/parity/route_parity.md index bfefbec8..a1e49ca3 100644 --- a/docs/parity/route_parity.md +++ b/docs/parity/route_parity.md @@ -7,7 +7,7 @@ Generated from: This report covers tracked frontend-critical Chatwoot routes from `reference/chatwoot/config/routes.rb`, including API v1 account routes, Captain/Copilot, assignment policies, widget/public APIs, and API v2 reports. Ruby is not installed in the workspace, so Chatwoot routes are sourced from static route declarations instead of `bin/rails routes`. -Summary: 374 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 387 tracked critical routes. +Summary: 379 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 392 tracked critical routes. ## Missing Critical Routes @@ -77,6 +77,7 @@ These routes exist with equivalent method and path shape but different parameter | DELETE | `/api/v1/accounts/:account_id/inboxes/:inbox_id/assignment_policy/` | `/api/v1/accounts/:account_id/inboxes/:inbox_id/assignment_policy/` | `api/v1/accounts/inboxes/assignment_policy#destroy` | `routes.rb:311` | exact | | DELETE | `/api/v1/accounts/:account_id/inboxes/:inbox_id/avatar` | `/api/v1/accounts/:account_id/inboxes/:inbox_id/avatar` | `api/v1/accounts/inboxes#avatar` | `routes.rb:257` | exact | | DELETE | `/api/v1/accounts/:account_id/integrations/hooks/:id` | `/api/v1/accounts/:account_id/integrations/hooks/:id` | `api/v1/accounts/integrations/hooks#destroy` | `routes.rb:346` | exact | +| DELETE | `/api/v1/accounts/:account_id/integrations/slack` | `/api/v1/accounts/:account_id/integrations/slack` | `api/v1/accounts/integrations/slack#destroy` | `routes.rb:350` | exact | | DELETE | `/api/v1/accounts/:account_id/labels/:tag_id` | `/api/v1/accounts/:account_id/labels/:tag_id` | `api/v1/accounts/labels#destroy` | `routes.rb:281` | exact | | DELETE | `/api/v1/accounts/:account_id/macros/:macro_id` | `/api/v1/accounts/:account_id/macros/:macro_id` | `api/v1/accounts/macros#destroy` | `routes.rb:118` | exact | | DELETE | `/api/v1/accounts/:account_id/notifications/:notification_id` | `/api/v1/accounts/:account_id/notifications/:notification_id` | `api/v1/accounts/notifications#destroy` | `routes.rb:283` | exact | @@ -173,6 +174,7 @@ These routes exist with equivalent method and path shape but different parameter | GET | `/api/v1/accounts/:account_id/integrations/apps` | `/api/v1/accounts/:account_id/integrations/apps` | `api/v1/accounts/integrations/apps#index` | `routes.rb:345` | exact | | GET | `/api/v1/accounts/:account_id/integrations/apps/:id` | `/api/v1/accounts/:account_id/integrations/apps/:id` | `api/v1/accounts/integrations/apps#show` | `routes.rb:345` | exact | | GET | `/api/v1/accounts/:account_id/integrations/hooks/:id` | `/api/v1/accounts/:account_id/integrations/hooks/:id` | `api/v1/accounts/integrations/hooks#show` | `routes.rb:346` | exact | +| GET | `/api/v1/accounts/:account_id/integrations/slack/list_all_channels` | `/api/v1/accounts/:account_id/integrations/slack/list_all_channels` | `api/v1/accounts/integrations/slack#list_all_channels` | `routes.rb:352` | exact | | GET | `/api/v1/accounts/:account_id/labels/` | `/api/v1/accounts/:account_id/labels/` | `api/v1/accounts/labels#index` | `routes.rb:281` | exact | | GET | `/api/v1/accounts/:account_id/labels/:tag_id` | `/api/v1/accounts/:account_id/labels/:tag_id` | `api/v1/accounts/labels#show` | `routes.rb:281` | exact | | GET | `/api/v1/accounts/:account_id/macros/` | `/api/v1/accounts/:account_id/macros/` | `api/v1/accounts/macros#index` | `routes.rb:118` | exact | @@ -260,6 +262,7 @@ These routes exist with equivalent method and path shape but different parameter | PATCH | `/api/v1/accounts/:account_id/conversations/:conversation_id/participants` | `/api/v1/accounts/:account_id/conversations/:conversation_id/participants` | `api/v1/accounts/conversations/participants#update` | `routes.rb:150` | exact | | PATCH | `/api/v1/accounts/:account_id/inbox_members/` | `/api/v1/accounts/:account_id/inbox_members/` | `api/v1/accounts/inbox_members#update` | `routes.rb:278` | exact | | PATCH | `/api/v1/accounts/:account_id/integrations/hooks/:id` | `/api/v1/accounts/:account_id/integrations/hooks/:id` | `api/v1/accounts/integrations/hooks#update` | `routes.rb:346` | exact | +| PATCH | `/api/v1/accounts/:account_id/integrations/slack` | `/api/v1/accounts/:account_id/integrations/slack` | `api/v1/accounts/integrations/slack#update` | `routes.rb:350` | exact | | PATCH | `/api/v1/accounts/:account_id/portals/:portal_id` | `/api/v1/accounts/:account_id/portals/:portal_id` | `api/v1/accounts/portals#update` | `routes.rb:385` | exact | | PATCH | `/api/v1/accounts/:account_id/portals/:portal_id/archive` | `/api/v1/accounts/:account_id/portals/:portal_id/archive` | `api/v1/accounts/portals#archive` | `routes.rb:387` | exact | | PATCH | `/api/v1/accounts/:account_id/portals/:portal_id/articles/:article_id` | `/api/v1/accounts/:account_id/portals/:portal_id/articles/:article_id` | `api/v1/accounts/articles#update` | `routes.rb:403` | exact | @@ -338,6 +341,7 @@ These routes exist with equivalent method and path shape but different parameter | POST | `/api/v1/accounts/:account_id/integrations/dyte/create_a_meeting` | `/api/v1/accounts/:account_id/integrations/dyte/create_a_meeting` | `api/v1/accounts/integrations/dyte#create_a_meeting` | `routes.rb:357` | exact | | POST | `/api/v1/accounts/:account_id/integrations/hooks` | `/api/v1/accounts/:account_id/integrations/hooks` | `api/v1/accounts/integrations/hooks#create` | `routes.rb:346` | exact | | POST | `/api/v1/accounts/:account_id/integrations/hooks/:id/process_event` | `/api/v1/accounts/:account_id/integrations/hooks/:id/process_event` | `api/v1/accounts/integrations/hooks#process_event` | `routes.rb:348` | exact | +| POST | `/api/v1/accounts/:account_id/integrations/slack` | `/api/v1/accounts/:account_id/integrations/slack` | `api/v1/accounts/integrations/slack#create` | `routes.rb:350` | exact | | POST | `/api/v1/accounts/:account_id/labels/` | `/api/v1/accounts/:account_id/labels/` | `api/v1/accounts/labels#create` | `routes.rb:281` | exact | | POST | `/api/v1/accounts/:account_id/macros/` | `/api/v1/accounts/:account_id/macros/` | `api/v1/accounts/macros#create` | `routes.rb:118` | exact | | POST | `/api/v1/accounts/:account_id/macros/:macro_id/execute` | `/api/v1/accounts/:account_id/macros/:macro_id/execute` | `api/v1/accounts/macros#execute` | `routes.rb:119` | exact | @@ -406,6 +410,7 @@ These routes exist with equivalent method and path shape but different parameter | PUT | `/api/v1/accounts/:account_id/custom_filters/:id` | `/api/v1/accounts/:account_id/custom_filters/:id` | `api/v1/accounts/custom_filters#update` | `routes.rb:251` | exact | | PUT | `/api/v1/accounts/:account_id/inboxes/:inbox_id` | `/api/v1/accounts/:account_id/inboxes/:inbox_id` | `api/v1/accounts/inboxes#update` | `routes.rb:252` | exact | | PUT | `/api/v1/accounts/:account_id/integrations/hooks/:id` | `/api/v1/accounts/:account_id/integrations/hooks/:id` | `api/v1/accounts/integrations/hooks#update` | `routes.rb:346` | exact | +| PUT | `/api/v1/accounts/:account_id/integrations/slack` | `/api/v1/accounts/:account_id/integrations/slack` | `api/v1/accounts/integrations/slack#update` | `routes.rb:350` | exact | | PUT | `/api/v1/accounts/:account_id/labels/:tag_id` | `/api/v1/accounts/:account_id/labels/:tag_id` | `api/v1/accounts/labels#update` | `routes.rb:281` | exact | | PUT | `/api/v1/accounts/:account_id/macros/:macro_id` | `/api/v1/accounts/:account_id/macros/:macro_id` | `api/v1/accounts/macros#update` | `routes.rb:118` | exact | | PUT | `/api/v1/accounts/:account_id/notification_settings/` | `/api/v1/accounts/:account_id/notification_settings/` | `api/v1/accounts/notification_settings#update` | `routes.rb:293` | exact | diff --git a/internal/handler/api/v1/slack_integration_handler.go b/internal/handler/api/v1/slack_integration_handler.go index 21b89188..fb10a9d8 100644 --- a/internal/handler/api/v1/slack_integration_handler.go +++ b/internal/handler/api/v1/slack_integration_handler.go @@ -1,10 +1,12 @@ package v1 import ( + "errors" "net/http" "github.com/gin-gonic/gin" + "github.com/gochat/gochat/internal/model" "github.com/gochat/gochat/internal/service" "github.com/gochat/gochat/pkg/response" ) @@ -30,7 +32,7 @@ func (h *SlackIntegrationHandler) Create(c *gin.Context) { } var req service.CreateSlackRequest - if err := c.ShouldBindJSON(&req); err != nil { + if err := c.ShouldBind(&req); err != nil { response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, err.Error()) return } @@ -40,7 +42,7 @@ func (h *SlackIntegrationHandler) Create(c *gin.Context) { handleServiceError(c, svcErr) return } - response.OK(c, hook) + c.JSON(http.StatusOK, h.slackAppPayload(c, accountID, []model.IntegrationHook{*hook})) } // Update updates a Slack integration for an account. @@ -53,17 +55,21 @@ func (h *SlackIntegrationHandler) Update(c *gin.Context) { } var req service.UpdateSlackRequest - if err := c.ShouldBindJSON(&req); err != nil { + if err := c.ShouldBind(&req); err != nil { response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, err.Error()) return } hook, svcErr := h.svc.Update(c.Request.Context(), accountID, req) if svcErr != nil { + if errors.Is(svcErr, service.ErrSlackInvalidChannel) { + c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Invalid slack channel. Please try again"}) + return + } handleServiceError(c, svcErr) return } - response.OK(c, hook) + c.JSON(http.StatusOK, h.slackAppPayload(c, accountID, []model.IntegrationHook{*hook})) } // Delete removes a Slack integration for an account. @@ -79,7 +85,7 @@ func (h *SlackIntegrationHandler) Delete(c *gin.Context) { handleServiceError(c, svcErr) return } - response.OK(c, gin.H{"message": "Slack integration deleted"}) + c.Status(http.StatusOK) } // ListAllChannels lists available Slack channels. @@ -96,16 +102,45 @@ func (h *SlackIntegrationHandler) ListAllChannels(c *gin.Context) { handleServiceError(c, svcErr) return } - response.OK(c, channels) + c.JSON(http.StatusOK, channels) } // RegisterSlackIntegrationRoutes registers Slack integration routes. func RegisterSlackIntegrationRoutes(g *gin.RouterGroup, h *SlackIntegrationHandler) { + g.POST("/slack", h.Create) + g.PATCH("/slack", h.Update) + g.PUT("/slack", h.Update) + g.DELETE("/slack", h.Delete) + slack := g.Group("/slack") { slack.POST("/", h.Create) slack.PATCH("/", h.Update) + slack.PUT("/", h.Update) slack.DELETE("/", h.Delete) slack.GET("/list_all_channels", h.ListAllChannels) } } + +func (h *SlackIntegrationHandler) slackAppPayload(c *gin.Context, accountID uint, fallback []model.IntegrationHook) gin.H { + hooks, err := h.svc.ListHooks(c.Request.Context(), accountID) + if err != nil || len(hooks) == 0 { + hooks = fallback + } + serializedHooks := make([]gin.H, 0, len(hooks)) + for _, hook := range hooks { + serializedHooks = append(serializedHooks, serializeIntegrationHook(hook)) + } + return gin.H{ + "id": "slack", + "name": "Slack", + "description": "Connect Slack channels for real-time notifications", + "short_description": "Connect Slack channels for real-time notifications", + "enabled": len(serializedHooks) > 0, + "hooks": serializedHooks, + "hook_type": integrationAppHookType("slack"), + "allow_multiple_hooks": integrationAppAllowsMultipleHooks("slack"), + "settings_form_schema": integrationAppSettingsFormSchema("slack"), + "visible_properties": integrationAppVisibleProperties("slack"), + } +} diff --git a/internal/handler/api/v1/slack_integration_handler_test.go b/internal/handler/api/v1/slack_integration_handler_test.go index 25bf22a6..1c0828f0 100644 --- a/internal/handler/api/v1/slack_integration_handler_test.go +++ b/internal/handler/api/v1/slack_integration_handler_test.go @@ -9,6 +9,14 @@ import ( "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/sqlite" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "github.com/gochat/gochat/internal/model" + "github.com/gochat/gochat/internal/repository" + "github.com/gochat/gochat/internal/service" ) func setupSlackIntegrationRouter() *gin.Engine { @@ -24,6 +32,31 @@ func setupSlackIntegrationRouter() *gin.Engine { return r } +func setupSlackIntegrationRouterWithService(svc *service.SlackIntegrationService) *gin.Engine { + gin.SetMode(gin.TestMode) + r := gin.New() + r.RedirectTrailingSlash = false + + handler := NewSlackIntegrationHandler(svc) + integrations := r.Group("/api/v1/accounts/:account_id/integrations") + RegisterSlackIntegrationRoutes(integrations, handler) + return r +} + +func setupSlackIntegrationHandlerDB(t *testing.T) (*gorm.DB, uint) { + t.Helper() + db, err := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + require.NoError(t, db.AutoMigrate(&model.Account{}, &model.IntegrationHook{})) + account := &model.Account{Name: "Slack Handler Account"} + require.NoError(t, db.Create(account).Error) + t.Cleanup(func() { + sqlDB, _ := db.DB() + _ = sqlDB.Close() + }) + return db, account.ID +} + // ======================================== // SlackIntegration — param validation tests // ======================================== @@ -117,3 +150,51 @@ func TestSlackIntegration_ListAllChannels_BadAccountID(t *testing.T) { errBody := resp["error"].(map[string]interface{}) assert.Contains(t, errBody["message"], "invalid account_id") } + +func TestSlackIntegration_Create_NoTrailingSlash_ReturnsRawAppPayload(t *testing.T) { + db, accountID := setupSlackIntegrationHandlerDB(t) + svc := service.NewSlackIntegrationService(repository.NewIntegrationHookRepo(db)) + r := setupSlackIntegrationRouterWithService(svc) + + w := httptest.NewRecorder() + body := bytes.NewReader([]byte(`{"slack_token":"xoxb-handler-token"}`)) + req, _ := http.NewRequest("POST", "/api/v1/accounts/1/integrations/slack", body) + req.Header.Set("Content-Type", "application/json") + r.ServeHTTP(w, req) + + assert.Equal(t, http.StatusOK, w.Code) + var resp map[string]interface{} + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) + assert.Equal(t, "slack", resp["id"]) + assert.NotContains(t, resp, "success") + hooks := resp["hooks"].([]interface{}) + require.Len(t, hooks, 1) + hook := hooks[0].(map[string]interface{}) + assert.Equal(t, "slack", hook["app_id"]) + assert.Equal(t, accountID, uint(hook["account_id"].(float64))) + assert.Equal(t, false, hook["status"]) +} + +func TestSlackIntegration_Delete_NoTrailingSlash_ReturnsEmptyOK(t *testing.T) { + db, accountID := setupSlackIntegrationHandlerDB(t) + require.NoError(t, db.Create(&model.IntegrationHook{AccountID: accountID, AppID: "slack", HookType: model.HookTypeSlack}).Error) + svc := service.NewSlackIntegrationService(repository.NewIntegrationHookRepo(db)) + r := setupSlackIntegrationRouterWithService(svc) + + w := httptest.NewRecorder() + req, _ := http.NewRequest("DELETE", "/api/v1/accounts/1/integrations/slack", nil) + r.ServeHTTP(w, req) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Empty(t, w.Body.String()) +} + +func TestSlackIntegration_Update_PutNoTrailingSlash_BadAccountID(t *testing.T) { + r := setupSlackIntegrationRouter() + + w := httptest.NewRecorder() + req, _ := http.NewRequest("PUT", "/api/v1/accounts/abc/integrations/slack", nil) + r.ServeHTTP(w, req) + + assert.Equal(t, http.StatusBadRequest, w.Code) +} diff --git a/internal/service/slack_integration_service.go b/internal/service/slack_integration_service.go index a8b78867..644548a3 100644 --- a/internal/service/slack_integration_service.go +++ b/internal/service/slack_integration_service.go @@ -3,29 +3,41 @@ package service import ( "context" "encoding/json" + "errors" "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "time" "github.com/gochat/gochat/internal/model" "github.com/gochat/gochat/internal/repository" applogger "github.com/gochat/gochat/pkg/logger" ) +var ErrSlackInvalidChannel = errors.New("invalid slack channel") + // SlackIntegrationService implements Slack integration business logic. // Reference: Chatwoot Integrations::SlackController + SlackService // Slack integration sends conversation notifications to a Slack channel and // supports Slack slash commands for ticket creation. type SlackIntegrationService struct { hookRepo *repository.IntegrationHookRepo + client *slackAPIClient } // NewSlackIntegrationService creates a new SlackIntegrationService. func NewSlackIntegrationService(hookRepo *repository.IntegrationHookRepo) *SlackIntegrationService { - return &SlackIntegrationService{hookRepo: hookRepo} + return &SlackIntegrationService{hookRepo: hookRepo, client: newSlackAPIClientFromEnv()} } // CreateSlackRequest is the DTO for creating/updating a Slack integration. -// Reference: Chatwoot SlackController#create — params: {channel_id, channel_name, slack_token} +// Reference: Chatwoot SlackController#create — params: {code, inbox_id} type CreateSlackRequest struct { + Code string `json:"code,omitempty"` + InboxID *uint `json:"inbox_id,omitempty"` ChannelID string `json:"channel_id" validate:"required"` ChannelName string `json:"channel_name,omitempty"` SlackToken string `json:"slack_token,omitempty"` @@ -33,6 +45,7 @@ type CreateSlackRequest struct { // UpdateSlackRequest is the DTO for updating a Slack integration. type UpdateSlackRequest struct { + ReferenceID string `json:"reference_id,omitempty"` ChannelID string `json:"channel_id,omitempty"` ChannelName string `json:"channel_name,omitempty"` SlackToken string `json:"slack_token,omitempty"` @@ -40,56 +53,63 @@ type UpdateSlackRequest struct { // Create creates a Slack integration hook for an account. func (s *SlackIntegrationService) Create(ctx context.Context, accountID uint, req CreateSlackRequest) (*model.IntegrationHook, error) { - settings := model.SlackSettings{ - ChannelID: req.ChannelID, - ChannelName: req.ChannelName, - SlackToken: req.SlackToken, + accessToken := strings.TrimSpace(req.SlackToken) + if accessToken == "" { + var err error + accessToken, err = s.client.exchangeOAuthCode(ctx, accountID, req.Code) + if err != nil { + return nil, err + } } - settingsJSON, err := json.Marshal(settings) + settingsJSON, err := json.Marshal(slackSettingsFromCreate(req)) if err != nil { return nil, fmt.Errorf("failed to marshal Slack settings: %w", err) } hook := &model.IntegrationHook{ - AccountID: accountID, - HookType: model.HookTypeSlack, - Status: model.HookStatusActive, - Settings: settingsJSON, + AccountID: accountID, + AppID: "slack", + InboxID: req.InboxID, + HookType: model.HookTypeSlack, + Status: model.HookStatusInactive, + AccessToken: accessToken, + Settings: settingsJSON, } if err := s.hookRepo.Create(ctx, hook); err != nil { return nil, fmt.Errorf("failed to create Slack integration: %w", err) } - applogger.L().Infof("Slack integration created: account=%d, channel=%s", accountID, req.ChannelID) + applogger.L().Infof("Slack integration created: account=%d", accountID) return hook, nil } // Update updates a Slack integration hook. func (s *SlackIntegrationService) Update(ctx context.Context, accountID uint, req UpdateSlackRequest) (*model.IntegrationHook, error) { - hooks, err := s.hookRepo.FindByAccountAndType(ctx, accountID, model.HookTypeSlack) + hooks, err := s.findSlackHooks(ctx, accountID) if err != nil || len(hooks) == 0 { return nil, fmt.Errorf("Slack integration not found for account %d", accountID) } hook := &hooks[0] - - // Update settings - var settings model.SlackSettings - if hook.Settings != nil { - if err := json.Unmarshal(hook.Settings, &settings); err != nil { - return nil, fmt.Errorf("failed to unmarshal existing Slack settings: %w", err) + referenceID := firstNonBlank(req.ReferenceID, req.ChannelID) + channel, err := s.findChannel(ctx, *hook, referenceID) + if err != nil { + return nil, err + } + if channel == nil { + return nil, ErrSlackInvalidChannel + } + if !channel.IsPrivate { + if err := s.client.joinChannel(ctx, hook.AccessToken, channel.ID); err != nil { + return nil, err } } - if req.ChannelID != "" { - settings.ChannelID = req.ChannelID - } - if req.ChannelName != "" { - settings.ChannelName = req.ChannelName - } + settings := model.SlackSettings{ChannelName: channel.Name} if req.SlackToken != "" { + hook.AccessToken = req.SlackToken settings.SlackToken = req.SlackToken } @@ -98,6 +118,9 @@ func (s *SlackIntegrationService) Update(ctx context.Context, accountID uint, re return nil, fmt.Errorf("failed to marshal Slack settings: %w", err) } hook.Settings = settingsJSON + hook.AppID = "slack" + hook.ReferenceID = channel.ID + hook.Status = model.HookStatusActive if err := s.hookRepo.Update(ctx, hook); err != nil { return nil, fmt.Errorf("failed to update Slack integration: %w", err) @@ -109,7 +132,7 @@ func (s *SlackIntegrationService) Update(ctx context.Context, accountID uint, re // Delete removes a Slack integration hook for an account. func (s *SlackIntegrationService) Delete(ctx context.Context, accountID uint) error { - hooks, err := s.hookRepo.FindByAccountAndType(ctx, accountID, model.HookTypeSlack) + hooks, err := s.findSlackHooks(ctx, accountID) if err != nil || len(hooks) == 0 { return fmt.Errorf("Slack integration not found for account %d", accountID) } @@ -127,20 +150,222 @@ func (s *SlackIntegrationService) Delete(ctx context.Context, accountID uint) er // ListAllChannels returns available Slack channels (proxy to Slack API). // GET /api/v1/accounts/:account_id/integrations/slack/list_all_channels func (s *SlackIntegrationService) ListAllChannels(ctx context.Context, accountID uint) ([]map[string]interface{}, error) { - hooks, err := s.hookRepo.FindByAccountAndType(ctx, accountID, model.HookTypeSlack) + hooks, err := s.findSlackHooks(ctx, accountID) if err != nil || len(hooks) == 0 { return nil, fmt.Errorf("Slack integration not found for account %d", accountID) } - var settings model.SlackSettings - if err := json.Unmarshal(hooks[0].Settings, &settings); err != nil { - return nil, fmt.Errorf("failed to unmarshal Slack settings: %w", err) + channels, err := s.client.listChannels(ctx, hooks[0].AccessToken) + if err != nil { + return nil, err } - // In production, this would call the Slack API to list channels using settings.SlackToken. - // Production note: when Slack OAuth is wired, this returns real channel list from Slack API. applogger.L().Infof("Listing Slack channels for account=%d", accountID) - return []map[string]interface{}{ - {"id": settings.ChannelID, "name": settings.ChannelName}, - }, nil + return slackChannelsToMaps(channels), nil +} + +func (s *SlackIntegrationService) ListHooks(ctx context.Context, accountID uint) ([]model.IntegrationHook, error) { + return s.findSlackHooks(ctx, accountID) +} + +func (s *SlackIntegrationService) findSlackHooks(ctx context.Context, accountID uint) ([]model.IntegrationHook, error) { + hooks, err := s.hookRepo.FindByAccountAndApp(ctx, accountID, "slack") + if err != nil { + return nil, err + } + if len(hooks) > 0 { + return hooks, nil + } + return s.hookRepo.FindByAccountAndType(ctx, accountID, model.HookTypeSlack) +} + +func (s *SlackIntegrationService) findChannel(ctx context.Context, hook model.IntegrationHook, referenceID string) (*slackChannel, error) { + if referenceID == "" { + return nil, ErrSlackInvalidChannel + } + channels, err := s.client.listChannels(ctx, hook.AccessToken) + if err != nil { + return nil, err + } + for _, channel := range channels { + if channel.ID == referenceID { + return &channel, nil + } + } + return nil, nil +} + +func slackSettingsFromCreate(req CreateSlackRequest) model.SlackSettings { + return model.SlackSettings{ + ChannelID: req.ChannelID, + ChannelName: req.ChannelName, + SlackToken: req.SlackToken, + } +} + +func firstNonBlank(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} + +type slackAPIClient struct { + baseURL string + httpClient *http.Client +} + +type slackChannel struct { + ID string `json:"id"` + Name string `json:"name"` + IsPrivate bool `json:"is_private"` +} + +func newSlackAPIClientFromEnv() *slackAPIClient { + baseURL := strings.TrimRight(os.Getenv("SLACK_API_BASE"), "/") + if baseURL == "" { + baseURL = "https://slack.com/api" + } + return &slackAPIClient{baseURL: baseURL, httpClient: &http.Client{Timeout: 15 * time.Second}} +} + +func (c *slackAPIClient) exchangeOAuthCode(ctx context.Context, accountID uint, code string) (string, error) { + if strings.TrimSpace(code) == "" { + return "", fmt.Errorf("slack oauth code is required") + } + form := url.Values{} + form.Set("client_id", os.Getenv("SLACK_CLIENT_ID")) + form.Set("client_secret", os.Getenv("SLACK_CLIENT_SECRET")) + form.Set("code", code) + form.Set("redirect_uri", fmt.Sprintf("%s/app/accounts/%d/settings/integrations/slack", strings.TrimRight(os.Getenv("FRONTEND_URL"), "/"), accountID)) + + var payload struct { + OK bool `json:"ok"` + AccessToken string `json:"access_token"` + Error string `json:"error"` + } + if err := c.postForm(ctx, "/oauth.v2.access", "", form, &payload); err != nil { + return "", err + } + if !payload.OK || payload.AccessToken == "" { + return "", fmt.Errorf("slack oauth failed: %s", payload.Error) + } + return payload.AccessToken, nil +} + +func (c *slackAPIClient) listChannels(ctx context.Context, token string) ([]slackChannel, error) { + var channels []slackChannel + for _, channelType := range []string{"private_channel", "public_channel"} { + cursor := "" + for { + batch, nextCursor, err := c.listChannelsByType(ctx, token, channelType, cursor) + if err != nil { + return nil, err + } + channels = append(channels, batch...) + if nextCursor == "" { + break + } + cursor = nextCursor + } + } + return channels, nil +} + +func (c *slackAPIClient) listChannelsByType(ctx context.Context, token, channelType, cursor string) ([]slackChannel, string, error) { + query := url.Values{} + query.Set("types", channelType) + query.Set("exclude_archived", "true") + query.Set("limit", "1000") + if cursor != "" { + query.Set("cursor", cursor) + } + + var payload struct { + OK bool `json:"ok"` + Channels []slackChannel `json:"channels"` + Error string `json:"error"` + ResponseMetadata struct { + NextCursor string `json:"next_cursor"` + } `json:"response_metadata"` + } + if err := c.get(ctx, "/conversations.list?"+query.Encode(), token, &payload); err != nil { + return nil, "", err + } + if !payload.OK { + return nil, "", fmt.Errorf("slack conversations.list failed: %s", payload.Error) + } + return payload.Channels, payload.ResponseMetadata.NextCursor, nil +} + +func (c *slackAPIClient) joinChannel(ctx context.Context, token, channelID string) error { + form := url.Values{} + form.Set("channel", channelID) + var payload struct { + OK bool `json:"ok"` + Error string `json:"error"` + } + if err := c.postForm(ctx, "/conversations.join", token, form, &payload); err != nil { + return err + } + if !payload.OK { + return fmt.Errorf("slack conversations.join failed: %s", payload.Error) + } + return nil +} + +func (c *slackAPIClient) get(ctx context.Context, path, token string, out interface{}) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil) + if err != nil { + return err + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + return c.do(req, out) +} + +func (c *slackAPIClient) postForm(ctx context.Context, path, token string, form url.Values, out interface{}) error { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, strings.NewReader(form.Encode())) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + return c.do(req, out) +} + +func (c *slackAPIClient) do(req *http.Request, out interface{}) error { + resp, err := c.httpClient.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return err + } + if resp.StatusCode >= 400 { + return fmt.Errorf("slack api returned %d: %s", resp.StatusCode, strings.TrimSpace(string(body))) + } + if err := json.Unmarshal(body, out); err != nil { + return err + } + return nil +} + +func slackChannelsToMaps(channels []slackChannel) []map[string]interface{} { + items := make([]map[string]interface{}, 0, len(channels)) + for _, channel := range channels { + items = append(items, map[string]interface{}{ + "id": channel.ID, + "name": channel.Name, + "is_private": channel.IsPrivate, + }) + } + return items } diff --git a/internal/service/slack_integration_service_test.go b/internal/service/slack_integration_service_test.go index e311f953..97e60180 100644 --- a/internal/service/slack_integration_service_test.go +++ b/internal/service/slack_integration_service_test.go @@ -3,6 +3,9 @@ package service import ( "context" "encoding/json" + "io" + "net/http" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -45,6 +48,24 @@ func setupSlackIntegrationService(t *testing.T) (*SlackIntegrationService, *gorm return svc, db } +type slackRoundTripFunc func(*http.Request) (*http.Response, error) + +func (f slackRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +func slackJSONResponse(body string) *http.Response { + return &http.Response{ + StatusCode: http.StatusOK, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(body)), + } +} + +func setFakeSlackClient(svc *SlackIntegrationService, rt slackRoundTripFunc) { + svc.client = &slackAPIClient{baseURL: "https://slack.test/api", httpClient: &http.Client{Transport: rt}} +} + func seedSlackAccount(db *gorm.DB, t *testing.T) uint { t.Helper() account := &model.Account{Name: "Test Slack Account"} @@ -59,19 +80,31 @@ func seedSlackAccount(db *gorm.DB, t *testing.T) uint { func TestSlackIntegrationService_Create(t *testing.T) { svc, db := setupSlackIntegrationService(t) accountID := seedSlackAccount(db, t) + t.Setenv("SLACK_CLIENT_ID", "client-id") + t.Setenv("SLACK_CLIENT_SECRET", "client-secret") + t.Setenv("FRONTEND_URL", "https://gochat.test") + setFakeSlackClient(svc, func(req *http.Request) (*http.Response, error) { + assert.Equal(t, "/api/oauth.v2.access", req.URL.Path) + assert.Equal(t, http.MethodPost, req.Method) + body, _ := io.ReadAll(req.Body) + values := string(body) + assert.Contains(t, values, "code=oauth-code") + assert.Contains(t, values, "redirect_uri=https%3A%2F%2Fgochat.test%2Fapp%2Faccounts%2F1%2Fsettings%2Fintegrations%2Fslack") + return slackJSONResponse(`{"ok":true,"access_token":"xoxb-oauth-token"}`), nil + }) req := CreateSlackRequest{ - ChannelID: "C12345678", - ChannelName: "general", - SlackToken: "xoxb-test-token", + Code: "oauth-code", } hook, err := svc.Create(context.Background(), accountID, req) assert.NoError(t, err) assert.NotZero(t, hook.ID) + assert.Equal(t, "slack", hook.AppID) assert.Equal(t, model.HookTypeSlack, hook.HookType) - assert.Equal(t, model.HookStatusActive, hook.Status) + assert.Equal(t, model.HookStatusInactive, hook.Status) assert.Equal(t, accountID, hook.AccountID) + assert.Equal(t, "xoxb-oauth-token", hook.AccessToken) assert.NotNil(t, hook.Settings) } @@ -116,10 +149,22 @@ func TestSlackIntegrationService_Update(t *testing.T) { require.NoError(t, err) // Update + setFakeSlackClient(svc, func(req *http.Request) (*http.Response, error) { + switch req.URL.Path { + case "/api/conversations.list": + if req.URL.Query().Get("types") == "private_channel" { + return slackJSONResponse(`{"ok":true,"channels":[],"response_metadata":{"next_cursor":""}}`), nil + } + return slackJSONResponse(`{"ok":true,"channels":[{"id":"C20000002","name":"new-channel","is_private":false}],"response_metadata":{"next_cursor":""}}`), nil + case "/api/conversations.join": + return slackJSONResponse(`{"ok":true}`), nil + default: + t.Fatalf("unexpected Slack API path: %s", req.URL.Path) + } + return nil, nil + }) updateReq := UpdateSlackRequest{ - ChannelID: "C20000002", - ChannelName: "new-channel", - SlackToken: "xoxb-new-token", + ReferenceID: "C20000002", } updated, err := svc.Update(context.Background(), accountID, updateReq) @@ -129,9 +174,11 @@ func TestSlackIntegrationService_Update(t *testing.T) { var settings model.SlackSettings err = json.Unmarshal(updated.Settings, &settings) require.NoError(t, err) - assert.Equal(t, "C20000002", settings.ChannelID) + assert.Equal(t, "", settings.ChannelID) assert.Equal(t, "new-channel", settings.ChannelName) - assert.Equal(t, "xoxb-new-token", settings.SlackToken) + assert.Equal(t, "", settings.SlackToken) + assert.Equal(t, "C20000002", updated.ReferenceID) + assert.Equal(t, model.HookStatusActive, updated.Status) } func TestSlackIntegrationService_Update_NotFound(t *testing.T) { @@ -203,14 +250,25 @@ func TestSlackIntegrationService_ListAllChannels(t *testing.T) { } _, err := svc.Create(context.Background(), accountID, createReq) require.NoError(t, err) + setFakeSlackClient(svc, func(req *http.Request) (*http.Response, error) { + require.Equal(t, "/api/conversations.list", req.URL.Path) + require.Equal(t, "Bearer xoxb-list-token", req.Header.Get("Authorization")) + if req.URL.Query().Get("types") == "private_channel" { + return slackJSONResponse(`{"ok":true,"channels":[{"id":"G40000004","name":"private-room","is_private":true}],"response_metadata":{"next_cursor":""}}`), nil + } + return slackJSONResponse(`{"ok":true,"channels":[{"id":"C40000004","name":"list-channels","is_private":false}],"response_metadata":{"next_cursor":""}}`), nil + }) channels, err := svc.ListAllChannels(context.Background(), accountID) assert.NoError(t, err) - assert.Len(t, channels, 1) + assert.Len(t, channels, 2) - // The placeholder response contains the configured channel - assert.Equal(t, "C40000004", channels[0]["id"]) - assert.Equal(t, "list-channels", channels[0]["name"]) + assert.Equal(t, "G40000004", channels[0]["id"]) + assert.Equal(t, "private-room", channels[0]["name"]) + assert.Equal(t, true, channels[0]["is_private"]) + assert.Equal(t, "C40000004", channels[1]["id"]) + assert.Equal(t, "list-channels", channels[1]["name"]) + assert.Equal(t, false, channels[1]["is_private"]) } func TestSlackIntegrationService_ListAllChannels_NotFound(t *testing.T) { @@ -222,4 +280,4 @@ func TestSlackIntegrationService_ListAllChannels_NotFound(t *testing.T) { assert.Error(t, err) assert.Nil(t, channels) assert.Contains(t, err.Error(), "not found") -} \ No newline at end of file +}