feat(integrations): align dyte meeting routes
This commit is contained in:
@@ -206,6 +206,8 @@ 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/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"},
|
||||
|
||||
{Method: "GET", Path: "/api/v1/accounts/:account_id/notifications/", Controller: "api/v1/accounts/notifications#index", Source: "routes.rb:283"},
|
||||
{Method: "PUT", Path: "/api/v1/accounts/:account_id/notifications/:notification_id", Controller: "api/v1/accounts/notifications#update", Source: "routes.rb:283"},
|
||||
|
||||
@@ -49,14 +49,14 @@ Hermes task landing checklist:
|
||||
|
||||
## Current Baseline
|
||||
|
||||
- Current tracking checkpoint: 2026-06-06 documentation/tooling checkpoint, prepared as `docs: land active parity follow-up`.
|
||||
- Latest implementation checkpoint: this checkpoint, prepared as `feat(profile): send confirmation invitations`.
|
||||
- Current tracking checkpoint: 2026-06-06 account Dyte integration checkpoint, prepared as `feat(integrations): align dyte meeting routes`.
|
||||
- Latest implementation checkpoint: this checkpoint, prepared as `feat(integrations): align dyte meeting routes`.
|
||||
- Latest documentation/tooling checkpoint: this checkpoint, prepared as `docs: land active parity follow-up`; this document is the active follow-up plan and supersedes `.hermes/plans/*`.
|
||||
- Worktree status at this documentation checkpoint: P3.2a invitation/confirmation mail parity is implemented and committed in `682d0ab feat(profile): send confirmation invitations`. A fresh Phase 6 placeholder audit still finds `chatwootParityStub` only in public webhook nil-handler guards, not in reused dashboard/widget/public/enterprise critical API paths. `scripts/parity_frontend_smoke.sh --check` passed and refreshed `docs/parity/frontend_smoke_report.md`; live API/browser/enterprise smoke still needs the full PostgreSQL/Redis/Meilisearch/GoChat/Vite/Chrome stack. The next active slice is Phase 2/3 drift audit, B12 live smoke, or a fresh reference/smoke finding.
|
||||
- Worktree status at this implementation checkpoint: account-scoped Dyte meeting routes from `reference/chatwoot/config/routes.rb:357-358` are implemented for the reused dashboard Dyte client. `POST /api/v1/accounts/:account_id/integrations/dyte/create_a_meeting` creates a Chatwoot `integrations` message with Dyte meeting content attributes, and `POST /api/v1/accounts/:account_id/integrations/dyte/add_participant_to_meeting` returns the Dyte participant token payload while rejecting non-integration messages with the reference error. Live API/browser/enterprise smoke still needs the full PostgreSQL/Redis/Meilisearch/GoChat/Vite/Chrome stack. The next active slice remains Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or a fresh reference/smoke finding.
|
||||
- `go test ./...` passes.
|
||||
- Route dump succeeds with `TOTAL: 905` after removing the non-Chatwoot `GET /platform/api/v1/users/:id/token` route and keeping the Chatwoot `GET /platform/api/v1/users/:id/login` route.
|
||||
- Route dump succeeds with `TOTAL: 907` after adding the two account Dyte integration routes.
|
||||
- Route parity artifacts now exist under `docs/parity/` and are generated by `cmd/route_parity`.
|
||||
- Tracked frontend-critical route audit covers 362 Chatwoot routes: 353 exact, 0 method-compatible, 9 parameter-compatible, 0 missing. The 9 parameter-compatible routes are Gin-internal parameter-name differences for nested AgentCapacityPolicy users/inbox limits plus the public article `.md`/`.png` suffixes served through the same external article route dispatcher.
|
||||
- Tracked frontend-critical route audit covers 364 Chatwoot routes: 355 exact, 0 method-compatible, 9 parameter-compatible, 0 missing. The 9 parameter-compatible routes are Gin-internal parameter-name differences for nested AgentCapacityPolicy users/inbox limits 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.
|
||||
@@ -116,7 +116,7 @@ Open work after the current checkpoint:
|
||||
| Phase 5 jobs | Keep B9.3 in Review and open only evidence-backed drift slices for new async gaps. | `Phase 5: Background Jobs And Integrations` | Automation tests prove remaining action side effects and reference inspection proves no delayed action params remain. |
|
||||
| B12 smoke | Run optional live API/browser/enterprise smoke in a full PostgreSQL/Redis/Meilisearch/Vite environment and convert failures into named slices. | `B12 reused frontend verification breakdown` | `docs/parity/frontend_smoke_report.md` records checked pass/fail results and maps failures to slices. |
|
||||
| P3.7 help center | Portal, category, article route/payload parity, and enterprise article bulk translation are in Review for the inspected dashboard client paths. | `Open Checkpoint Contracts`, `Phase 3` | Reused Chatwoot help-center dashboard clients can call portal/category/article APIs and bulk article translation without adapters. |
|
||||
| Phase 2/3 drift | Help-center portal/category/article routes from `routes.rb:385-404` are now in the tracked critical set; expand the next route/serializer fixtures only from B12 failures or fresh reference/frontend inspection. | `Phase 2`, `Phase 3`, `docs/parity/` | Route parity remains 0 missing for tracked frontend routes; serializers have reference fixtures. |
|
||||
| Phase 2/3 drift | Help-center portal/category/article routes from `routes.rb:385-404` and account Dyte integration routes from `routes.rb:357-358` are now in the tracked critical set; expand the next route/serializer fixtures only from B12 failures or fresh reference/frontend inspection. | `Phase 2`, `Phase 3`, `docs/parity/` | Route parity remains 0 missing for tracked frontend routes; serializers have reference fixtures. |
|
||||
| Phase 6 placeholders | Re-run placeholder audit and burn down any frontend-reachable stub. | `Phase 6: Core Product Placeholder Burn-down` | Stub list has no reused-frontend critical path without a named owner. |
|
||||
|
||||
## Execution Snapshot
|
||||
@@ -139,15 +139,16 @@ This table is the shortest authoritative handoff view. If an older lower section
|
||||
| Priority | Workstream | Current state | Next checkpoint | Commit close rule |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 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 362-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`, and account integration app/hook routes from `routes.rb:345-348` 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, 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.2a 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 364-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`, and account Dyte routes from `routes.rb:357-358` 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, 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 Dyte 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. |
|
||||
| 6 | P3.11 account integrations apps/hooks API | Implemented for reused dashboard integrations settings with `{ payload: [...] }` app index, raw app/show and hook mutation payloads, raw or nested create/update bodies, account-scoped hook show/update/delete, persisted `app_id/reference_id`, reference app catalog seed additions, app hook/settings schema serializers, hook boolean `status`, account/inbox `hook_type`, and empty `200 OK` delete. | Keep in Review; reopen if live settings smoke exposes app feature-flag activation, app-specific credential validation, or provider setup side effects beyond this generic hooks boundary. | Focused integration hook handler/service tests, migration/router/route-parity tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. |
|
||||
| 7 | P6.8 contact outbound voice call | Implemented for the reused dashboard route with Twilio voice-enabled inbox validation, assigned-inbox check, open-conversation reuse, ContactInbox/conversation/call/message persistence, and Chatwoot response shape. | Keep in Review; reopen only if live smoke exposes provider initiation/status-update drift beyond the fakeable persisted boundary. | Focused contact call tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. |
|
||||
| 8 | B12 optional live smoke | API/browser/enterprise smoke commands are checked in; live runs need PostgreSQL, Redis, Meilisearch, Vite, and Chrome. | Run full live smoke when environment is available and map failures to the board. | `docs/parity/frontend_smoke_report.md` records pass/fail and linked owners. |
|
||||
| 9 | B9.3 delayed automation actions | Current reference exposes no delayed automation action params; scheduled-item work is already P5.12; `send_email_to_team` is durable and `add_sla` mutates conversation/applied SLA state. | Keep automation drift closed if future reference/smoke exposes delayed params or unsupported action shapes. | Automation worker/action fixtures verify queued team email replay, retry visibility through worker jobs, and SLA action idempotency. |
|
||||
| 10 | P5.13 reports/analytics | P5.13a derives visible report aggregates from persisted rows; P5.13b adds lazy rollup freshness, durable day rollup jobs, and `/reports` metric timeseries. | Keep report drift closed as frontend smoke or reference inspection exposes additional metrics. | Report fixtures verify timeseries values, cache/freshness behavior, and no hidden placeholder JSON. |
|
||||
| 7 | P3.12 account Dyte integration API | Implemented for the reused dashboard VideoCallButton/Dyte flow: account-scoped create meeting and add-participant routes are registered, route parity tracks `routes.rb:357-358`, Dyte credentials are loaded from account integration hooks, `create_a_meeting` creates a Chatwoot `integrations` outgoing message with meeting content attributes, and add-participant returns Dyte token payloads while rejecting non-integration messages with the reference error. | Keep in Review; reopen if live smoke exposes provider payload/status-code drift or frontend message serializer gaps beyond the fakeable Dyte boundary. | Focused Dyte service and handler tests, combined handler/service/router/app/route-parity tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. |
|
||||
| 8 | P6.8 contact outbound voice call | Implemented for the reused dashboard route with Twilio voice-enabled inbox validation, assigned-inbox check, open-conversation reuse, ContactInbox/conversation/call/message persistence, and Chatwoot response shape. | Keep in Review; reopen only if live smoke exposes provider initiation/status-update drift beyond the fakeable persisted boundary. | Focused contact call tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. |
|
||||
| 9 | B12 optional live smoke | API/browser/enterprise smoke commands are checked in; live runs need PostgreSQL, Redis, Meilisearch, Vite, and Chrome. | Run full live smoke when environment is available and map failures to the board. | `docs/parity/frontend_smoke_report.md` records pass/fail and linked owners. |
|
||||
| 10 | B9.3 delayed automation actions | Current reference exposes no delayed automation action params; scheduled-item work is already P5.12; `send_email_to_team` is durable and `add_sla` mutates conversation/applied SLA state. | Keep automation drift closed if future reference/smoke exposes delayed params or unsupported action shapes. | Automation worker/action fixtures verify queued team email replay, retry visibility through worker jobs, and SLA action idempotency. |
|
||||
| 11 | P5.13 reports/analytics | P5.13a derives visible report aggregates from persisted rows; P5.13b adds lazy rollup freshness, durable day rollup jobs, and `/reports` metric timeseries. | Keep report drift closed as frontend smoke or reference inspection exposes additional metrics. | Report fixtures verify timeseries values, cache/freshness behavior, and no hidden placeholder JSON. |
|
||||
|
||||
## Open Checkpoint Contracts
|
||||
|
||||
@@ -170,6 +171,7 @@ These rows are the executable development plan from this point forward. A checkp
|
||||
| P3.9 account agent-bot API parity | `internal/router/router.go`, `internal/handler/api/v1/agent_bot_handler.go`, `internal/service/agent_bot_service.go`, `internal/repository/agent_bot_repo.go`, agent bot handler tests | `reference/chatwoot/config/routes.rb:94-97`, `reference/chatwoot/app/controllers/api/v1/accounts/agent_bots_controller.rb`, `app/views/api/v1/accounts/agent_bots/*.json.jbuilder`, `app/views/api/v1/models/_agent_bot.json.jbuilder`, `app/models/agent_bot.rb`, `app/presenters/agent_bot_presenter.rb`, dashboard `api/agentBots.js`, `store/modules/agentBots.js`, settings `agentBots` route/components | Account agent-bot APIs now expose frontend no-trailing-slash GET/POST and PATCH update routes, track the full Chatwoot account agent-bot route set, return raw Jbuilder-style arrays/objects with `thumbnail`, `bot_config`, `system_bot`, account-scoped `access_token`/`secret`, accept JSON or multipart form bodies, preserve explicit empty update fields, scope create/update/delete/reset/avatar mutations to current-account bots, allow show/index of system bots through `accessible_to`, return empty `200 OK` delete, and return full bot payloads after reset-access-token/reset-secret/avatar deletion. | Review by `feat(agent-bots): align account payloads`; focused AgentBot handler tests, `go test ./internal/handler/api/v1 ./internal/service ./internal/router -run 'AgentBot\|Router' -count=1`, route dump/parity regenerated to `TOTAL: 864` and `308 exact, 7 parameter-compatible, 0 missing out of 315`, full `go test ./...`, and `git diff --check` passed. |
|
||||
| P3.10 account webhook API parity | `internal/router/router.go`, `internal/handler/api/v1/webhook_subscription_handler.go`, `internal/service/webhook_subscription_service.go`, `internal/repository/webhook_subscription_repo.go`, `internal/model/webhook_subscription.go`, webhook handler/service tests, migrations | `reference/chatwoot/config/routes.rb:342`, `reference/chatwoot/app/controllers/api/v1/accounts/webhooks_controller.rb`, `app/views/api/v1/accounts/webhooks/*.json.jbuilder`, `app/models/webhook.rb`, dashboard `api/webhooks.js`, `store/modules/webhooks.js`, settings `integrations/Webhooks/*` components | Account webhook APIs now match the reused dashboard settings flow: index returns `{ payload: { webhooks } }`, create/update return `{ payload: { webhook } }`, delete returns empty `200 OK`, frontend `PATCH` update is registered, nested `{ webhook: ... }` request bodies are accepted, `name/url/subscriptions/inbox_id/secret` serialize like Jbuilder, mutations are scoped through current account, URL/subscription validation follows the reference allowed event set, and outgoing delivery filtering keeps using the same persisted subscription rows. | Review by `feat(webhooks): align account payloads`; focused webhook handler/service tests, router focused test, `go test ./cmd/migrate -count=1`, route dump/parity regenerated to `TOTAL: 865` and `313 exact, 7 parameter-compatible, 0 missing out of 320`, full `go test ./...`, and `git diff --check` passed. |
|
||||
| P3.11 account integration apps/hooks API parity | `internal/router/router.go`, `internal/handler/api/v1/integration_hook_handler.go`, `internal/service/integration_hook_service.go`, `internal/repository/integration_hook_repo.go`, `internal/model/integration_hook.go`, integration hook handler/service tests, migrations, `cmd/route_parity` | `reference/chatwoot/config/routes.rb:345-348`, `reference/chatwoot/app/controllers/api/v1/accounts/integrations/apps_controller.rb`, `app/controllers/api/v1/accounts/integrations/hooks_controller.rb`, `app/views/api/v1/accounts/integrations/apps/*.jbuilder`, `app/views/api/v1/accounts/integrations/hooks/*.jbuilder`, `app/views/api/v1/models/_app.json.jbuilder`, `app/views/api/v1/models/_hook.json.jbuilder`, `app/models/integrations/app.rb`, `app/models/integrations/hook.rb`, `config/integration/apps.yml`, dashboard `api/integrations.js`, `store/modules/integrations.js`, settings integrations components | Account integration apps/hooks now match the reused dashboard integration settings contract: app index returns `{ payload: [...] }`; app show returns a raw app object; hooks create/show/update return raw hook objects; delete returns empty `200 OK`; frontend no-trailing-slash app/hook routes and hook `PATCH` update are registered and tracked; raw frontend hook bodies and nested `{ hook: ... }` are accepted; hooks persist `app_id`/`reference_id`; show/update/delete are account-scoped; hook serializers expose `app_id`, boolean `status`, `account_id`, account/inbox `hook_type`, `settings`, `reference_id`, and optional inbox; app serializers expose `hooks`, `action`, `button`, `allow_multiple_hooks`, `settings_form_schema`, and `visible_properties`; migration `000030` seeds the additional reference app catalog rows. | Review by `feat(integrations): align app hook payloads`; focused integration hook handler/service tests, `go test ./cmd/migrate -count=1`, `go test ./cmd/route_parity -count=1`, router focused test, route dump/parity regenerated to `TOTAL: 869` and `321 exact, 7 parameter-compatible, 0 missing out of 328`, full `go test ./...`, and `git diff --check` passed. |
|
||||
| P3.12 account Dyte integration API parity | `internal/router/router.go`, `internal/handler/api/v1/dyte_integration_handler.go`, `internal/service/dyte_integration_service.go`, `internal/service/message_service.go`, Dyte handler/service tests, `cmd/route_parity` | `reference/chatwoot/config/routes.rb:357-358`, `reference/chatwoot/app/controllers/api/v1/accounts/integrations/dyte_controller.rb`, `reference/chatwoot/lib/integrations/dyte/processor_service.rb`, `reference/chatwoot/lib/dyte.rb`, `reference/chatwoot/app/javascript/dashboard/api/integrations/dyte.js`, `reference/chatwoot/app/javascript/dashboard/components/widgets/VideoCallButton.vue`, `reference/chatwoot/app/javascript/dashboard/components-next/message/bubbles/Dyte.vue` | Account Dyte APIs now match the reused dashboard video-call boundary: `POST /integrations/dyte/create_a_meeting` and `POST /integrations/dyte/add_participant_to_meeting` are registered under account integrations and tracked in route parity; create resolves conversations by account display ID, enforces inbox access, loads account Dyte hook credentials, calls a fakeable Dyte backend, persists an outgoing `integrations` message with `content_attributes.type=dyte` and `data.meeting_id`, and returns the normal Chatwoot message serializer; add-participant resolves account-scoped messages, rejects non-`integrations` messages with `422 { error: { error: "Invalid message type. Action not permitted" } }`, and returns the Dyte participant token payload. | Review by `feat(integrations): align dyte meeting routes`; focused Dyte service tests, focused Dyte handler tests, combined handler/service/router/app/route-parity tests, route dump/parity regenerated to `TOTAL: 907` and `355 exact, 9 parameter-compatible, 0 missing out of 364`, 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 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. |
|
||||
@@ -211,6 +213,7 @@ This ledger records the committed parity checkpoints that future slices should b
|
||||
|
||||
| Commit | Scope | Verification summary | Follow-up state |
|
||||
| --- | --- | --- | --- |
|
||||
| `feat(integrations): align dyte meeting routes` | Advances P3.12 account Dyte integration parity by matching Chatwoot `Api::V1::Accounts::Integrations::DyteController`, `Integrations::Dyte::ProcessorService`, Dyte API wrapper behavior, and reused dashboard `api/integrations/dyte.js`/video-call components. GoChat now registers the account-scoped create-meeting and add-participant routes, tracks them in route parity, loads Dyte credentials from account integration hooks, creates outgoing `integrations` messages with Dyte meeting attributes, accepts `integrations` as a valid message content type, and returns participant token payloads through a fakeable Dyte backend. | `go test ./internal/service -run Dyte -count=1`; `go test ./internal/handler/api/v1 -run Dyte -count=1`; `go test ./internal/handler/api/v1 ./internal/service ./internal/router ./cmd/route_parity ./internal/app -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: 907`; tracked route parity is `355 exact, 0 method-compatible, 9 parameter-compatible, 0 missing out of 364`. | P3.12 moves to Review for current dashboard Dyte evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. |
|
||||
| `feat(profile): send confirmation invitations` | Advances P3.2a invitation/confirmation mail parity by matching Chatwoot `AgentBuilder`, Devise confirmation instructions view/specs, and profile resend controller behavior for non-SSO flows. GoChat now has a fakeable/environment SMTP confirmation mail boundary; profile resend persists confirmation or reset-password tokens and sends normal confirmation or workspace invitation payloads; confirmed resends remain no-op; newly created invited agents send invitation mail; `users.unconfirmed_email` is modeled for email-update branch routing; and bootstrap wires the account agent handler plus confirmation mailers. | `go test ./internal/handler/api/v1 -run 'ProfileHandlerSuite/TestResendConfirmation\|AgentHandlerSuite/TestCreateAgent' -count=1`; `go test ./internal/service ./internal/repository ./cmd/migrate ./internal/app -run 'Profile\|Agent\|App\|Migrate' -count=1`; `go test ./internal/handler/api/v1 ./internal/service ./internal/repository ./internal/router ./cmd/migrate ./internal/app -count=1`; full `go test ./...`; `git diff --check`. No route artifacts changed. | P3.2a moves to Review for current non-SSO reference evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. |
|
||||
| `docs: land active parity follow-up` | Documentation/tooling checkpoint requested before continuing implementation. It records the committed `682d0ab feat(profile): send confirmation invitations` baseline, refreshes the Phase 6 placeholder and B12 readiness evidence, and keeps the next executable queue limited to Phase 2/3 drift audit, optional B12 live smoke, or fresh reference/smoke findings. | `bash -n scripts/parity_frontend_smoke.sh`; `scripts/parity_frontend_smoke.sh --check`; `rg -n "TODO\|placeholder\|chatwootParityStub\|stub\|not implemented\|unsupported" internal/handler internal/service internal/router -g'*.go'`; `go run ./cmd/dump_routes`; `go run ./cmd/route_parity`; `git diff --check`. No route artifacts changed; route dump remains `TOTAL: 905`. | Continue Phase 2/3 drift audit first unless the full B12 live stack is available. Keep Phase 6 in Review and reopen only from fresh frontend-reachable placeholder evidence. |
|
||||
| `docs: land invitation parity tracker` | Documentation-only checkpoint requested before continuing implementation. It records the clean `2acd938 feat(account-users): align inviter id` baseline, promotes P3.2a invitation/confirmation mail parity to the top active slice, maps the inspected Chatwoot Devise/AgentBuilder references into an executable row, and keeps SSO/SAML/LDAP/OIDC mail variants excluded. | `git diff --check`. No Go code changed and no route artifacts changed. | Start `feat(profile): send confirmation invitations`, then continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke from concrete reference/smoke evidence. |
|
||||
@@ -2204,6 +2207,7 @@ Verification milestone gates:
|
||||
|
||||
## Progress Log
|
||||
|
||||
- 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.
|
||||
- 2026-06-06: P3.1 profile HMAC checkpoint prepared as `feat(profile): expose hmac identifier`; audited Chatwoot `app/views/api/v1/models/_user.json.jbuilder`, `UserAttributeHelpers#hmac_identifier`, `spec/models/user_spec.rb`, and reused frontend `scriptHelpers.js`. Profile responses now omit `hmac_identifier` when `CHATWOOT_INBOX_HMAC_KEY` is absent and expose `OpenSSL::HMAC.hexdigest('sha256', key, email)` compatible values when the installation config exists, letting the reused widget script helper send `identifier_hash` without adapter code. Focused profile handler tests, service compile test, full `go test ./...`, and `git diff --check` passed. Continue remaining P3.2 invitations drift or B12 live smoke.
|
||||
- 2026-06-06: P3.2 platform user checkpoint prepared as `feat(platform): align user payloads`; audited Chatwoot `Platform::Api::V1::UsersController`, `platform/api/v1/models/_user.json.jbuilder`, `users/token.json.jbuilder`, and platform user routes. Platform user show/create/update now return raw Chatwoot user payloads, create reuses existing users by email and creates the platform-app permissible idempotently, access tokens are generated/reused for user payloads, `GET /users/:id/login` returns a Chatwoot-shaped URL payload, `POST /users/:id/token` returns `{ access_token, expiry, user }`, update merges `custom_attributes`, and destroy returns empty `200 OK`. The stale non-reference `GET /platform/api/v1/users/:id/token` route was removed from the dump, leaving route dump `TOTAL: 905` and tracked route parity at `353 exact, 0 method-compatible, 9 parameter-compatible, 0 missing out of 362`. Focused platform handler/service/router tests, route parity test/generation, full `go test ./...`, and `git diff --check` passed; continue remaining P3.2 invitations drift or B12 live smoke.
|
||||
|
||||
@@ -675,6 +675,8 @@ POST /api/v1/accounts/:account_id/inboxes/:inbox_id/sync_templates
|
||||
POST /api/v1/accounts/:account_id/inboxes/web_widget
|
||||
POST /api/v1/accounts/:account_id/instagram/webhooks
|
||||
POST /api/v1/accounts/:account_id/instagram_channels/
|
||||
POST /api/v1/accounts/:account_id/integrations/dyte/add_participant_to_meeting
|
||||
POST /api/v1/accounts/:account_id/integrations/dyte/create_a_meeting
|
||||
POST /api/v1/accounts/:account_id/integrations/hooks
|
||||
POST /api/v1/accounts/:account_id/integrations/hooks/
|
||||
POST /api/v1/accounts/:account_id/integrations/hooks/:id/process_event
|
||||
@@ -903,4 +905,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: 905
|
||||
TOTAL: 907
|
||||
|
||||
@@ -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: 353 exact, 0 method-compatible, 9 parameter-compatible, 0 missing out of 362 tracked critical routes.
|
||||
Summary: 355 exact, 0 method-compatible, 9 parameter-compatible, 0 missing out of 364 tracked critical routes.
|
||||
|
||||
## Missing Critical Routes
|
||||
|
||||
@@ -314,6 +314,8 @@ These routes exist with equivalent method and path shape but different parameter
|
||||
| POST | `/api/v1/accounts/:account_id/inboxes/:inbox_id/reset_secret` | `/api/v1/accounts/:account_id/inboxes/:inbox_id/reset_secret` | `api/v1/accounts/inboxes#reset_secret` | `routes.rb:262` | exact |
|
||||
| POST | `/api/v1/accounts/:account_id/inboxes/:inbox_id/set_agent_bot` | `/api/v1/accounts/:account_id/inboxes/:inbox_id/set_agent_bot` | `api/v1/accounts/inboxes#set_agent_bot` | `routes.rb:256` | exact |
|
||||
| POST | `/api/v1/accounts/:account_id/inboxes/:inbox_id/sync_templates` | `/api/v1/accounts/:account_id/inboxes/:inbox_id/sync_templates` | `api/v1/accounts/inboxes#sync_templates` | `routes.rb:258` | exact |
|
||||
| POST | `/api/v1/accounts/:account_id/integrations/dyte/add_participant_to_meeting` | `/api/v1/accounts/:account_id/integrations/dyte/add_participant_to_meeting` | `api/v1/accounts/integrations/dyte#add_participant_to_meeting` | `routes.rb:358` | exact |
|
||||
| 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/labels/` | `/api/v1/accounts/:account_id/labels/` | `api/v1/accounts/labels#create` | `routes.rb:281` | exact |
|
||||
|
||||
@@ -326,6 +326,7 @@ func Bootstrap(env string) (*App, error) {
|
||||
shopifyIntegrationService := service.NewShopifyIntegrationService(integrationHookRepo)
|
||||
linearIntegrationService := service.NewLinearIntegrationService(integrationHookRepo)
|
||||
notionIntegrationService := service.NewNotionIntegrationService(integrationHookRepo)
|
||||
dyteIntegrationService := service.NewDyteIntegrationService(integrationHookRepo, messageRepo)
|
||||
|
||||
// Create channel dispatcher for event-driven architecture (ref: Chatwoot Dispatcher)
|
||||
channelDispatcher := channel.NewDispatcher(workerPool)
|
||||
@@ -836,6 +837,7 @@ func Bootstrap(env string) (*App, error) {
|
||||
ShopifyIntegration: v1.NewShopifyIntegrationHandler(shopifyIntegrationService),
|
||||
LinearIntegration: v1.NewLinearIntegrationHandler(linearIntegrationService),
|
||||
NotionIntegration: v1.NewNotionIntegrationHandler(notionIntegrationService),
|
||||
DyteIntegration: v1.NewDyteIntegrationHandler(dyteIntegrationService),
|
||||
PlatformUserSSO: v1.NewPlatformUserSSOHandler(),
|
||||
// Platform API AccessToken-authenticated handlers
|
||||
PlatformUser: v1.NewPlatformUserHandler(platformUserService),
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
"github.com/gochat/gochat/pkg/response"
|
||||
)
|
||||
|
||||
type DyteIntegrationHandler struct {
|
||||
svc *service.DyteIntegrationService
|
||||
}
|
||||
|
||||
func NewDyteIntegrationHandler(svc *service.DyteIntegrationService) *DyteIntegrationHandler {
|
||||
return &DyteIntegrationHandler{svc: svc}
|
||||
}
|
||||
|
||||
type dyteCreateMeetingRequest struct {
|
||||
ConversationID uint `json:"conversation_id"`
|
||||
}
|
||||
|
||||
type dyteAddParticipantRequest struct {
|
||||
MessageID uint `json:"message_id"`
|
||||
}
|
||||
|
||||
// CreateMeeting starts a Dyte meeting and creates the Chatwoot integration message.
|
||||
// Reference: Api::V1::Accounts::Integrations::DyteController#create_a_meeting.
|
||||
func (h *DyteIntegrationHandler) CreateMeeting(c *gin.Context) {
|
||||
accountID, err := parseUintParam(c, "account_id")
|
||||
if err != nil || accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
var req dyteCreateMeetingRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil || req.ConversationID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "conversation_id is required")
|
||||
return
|
||||
}
|
||||
message, conversation, apiErr, svcErr := h.svc.CreateMeeting(c.Request.Context(), accountID, getUserID(c), req.ConversationID, getRole(c))
|
||||
if svcErr != nil {
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
if apiErr != nil {
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": apiErr.Payload, "error_code": apiErr.Status})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, serializeMessage(c.Request.Context(), h.svc.DB(), message, conversation))
|
||||
}
|
||||
|
||||
// AddParticipant adds the current user as a participant to an existing Dyte meeting.
|
||||
// Reference: Api::V1::Accounts::Integrations::DyteController#add_participant_to_meeting.
|
||||
func (h *DyteIntegrationHandler) AddParticipant(c *gin.Context) {
|
||||
accountID, err := parseUintParam(c, "account_id")
|
||||
if err != nil || accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
var req dyteAddParticipantRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil || req.MessageID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "message_id is required")
|
||||
return
|
||||
}
|
||||
payload, apiErr, svcErr := h.svc.AddParticipant(c.Request.Context(), accountID, getUserID(c), req.MessageID, getRole(c))
|
||||
if svcErr != nil {
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
if apiErr != nil {
|
||||
status := http.StatusUnprocessableEntity
|
||||
body := gin.H{"error": apiErr.Payload}
|
||||
if apiErr.Status != http.StatusUnprocessableEntity {
|
||||
body["error_code"] = apiErr.Status
|
||||
}
|
||||
c.JSON(status, body)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, payload)
|
||||
}
|
||||
|
||||
func RegisterDyteIntegrationRoutes(g *gin.RouterGroup, h *DyteIntegrationHandler) {
|
||||
dyte := g.Group("/dyte")
|
||||
{
|
||||
dyte.POST("/create_a_meeting", h.CreateMeeting)
|
||||
dyte.POST("/add_participant_to_meeting", h.AddParticipant)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/datatypes"
|
||||
"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"
|
||||
)
|
||||
|
||||
type dyteHandlerFakeBackend struct{}
|
||||
|
||||
func (dyteHandlerFakeBackend) CreateMeeting(_ context.Context, _ service.DyteCredentials, _ string) (map[string]any, *service.DyteAPIError, error) {
|
||||
return map[string]any{"id": "meeting_id"}, nil, nil
|
||||
}
|
||||
|
||||
func (dyteHandlerFakeBackend) AddParticipant(_ context.Context, _ service.DyteCredentials, _ string, _ service.DyteParticipant) (map[string]any, *service.DyteAPIError, error) {
|
||||
return map[string]any{"id": "participant_id", "auth_token": "json-web-token"}, nil, nil
|
||||
}
|
||||
|
||||
func TestDyteIntegrationHandlerCreateMeetingReturnsMessagePayload(t *testing.T) {
|
||||
router, _, account, user, conversation, _ := setupDyteIntegrationHandler(t)
|
||||
body := bytes.NewBufferString(fmt.Sprintf(`{"conversation_id":%d}`, *conversation.DisplayID))
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/integrations/dyte/create_a_meeting", account.ID), body)
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
payload := decodeDyteHandlerBody(t, rec)
|
||||
require.NotZero(t, payload["id"])
|
||||
require.Equal(t, float64(*conversation.DisplayID), payload["conversation_id"])
|
||||
require.Equal(t, "integrations", payload["content_type"])
|
||||
require.Equal(t, "Dyte Agent has started a meeting", payload["content"])
|
||||
attrs := payload["content_attributes"].(map[string]any)
|
||||
require.Equal(t, "dyte", attrs["type"])
|
||||
require.Equal(t, "meeting_id", attrs["data"].(map[string]any)["meeting_id"])
|
||||
require.Equal(t, float64(user.ID), payload["sender"].(map[string]any)["id"])
|
||||
}
|
||||
|
||||
func TestDyteIntegrationHandlerAddParticipantReturnsAuthToken(t *testing.T) {
|
||||
router, _, account, _, _, message := setupDyteIntegrationHandler(t)
|
||||
body := bytes.NewBufferString(fmt.Sprintf(`{"message_id":%d}`, message.ID))
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/integrations/dyte/add_participant_to_meeting", account.ID), body)
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
payload := decodeDyteHandlerBody(t, rec)
|
||||
require.Equal(t, "participant_id", payload["id"])
|
||||
require.Equal(t, "json-web-token", payload["auth_token"])
|
||||
}
|
||||
|
||||
func TestDyteIntegrationHandlerAddParticipantRejectsNonIntegrationMessage(t *testing.T) {
|
||||
router, db, account, _, conversation, _ := setupDyteIntegrationHandler(t)
|
||||
message := &model.Message{AccountID: account.ID, InboxID: conversation.InboxID, ConversationID: conversation.ID, MessageType: "outgoing", ContentType: "text", Content: "plain", Status: "sent"}
|
||||
require.NoError(t, db.Create(message).Error)
|
||||
body := bytes.NewBufferString(fmt.Sprintf(`{"message_id":%d}`, message.ID))
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/integrations/dyte/add_participant_to_meeting", account.ID), body)
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
require.Equal(t, http.StatusUnprocessableEntity, rec.Code)
|
||||
payload := decodeDyteHandlerBody(t, rec)
|
||||
require.Equal(t, "Invalid message type. Action not permitted", payload["error"].(map[string]any)["error"])
|
||||
}
|
||||
|
||||
func setupDyteIntegrationHandler(t *testing.T) (*gin.Engine, *gorm.DB, *model.Account, *model.User, *model.Conversation, *model.Message) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&model.Account{}, &model.User{}, &model.Inbox{}, &model.Contact{}, &model.Conversation{}, &model.Message{}, &model.InboxMember{}, &model.IntegrationHook{}))
|
||||
t.Cleanup(func() { sqlDB, _ := db.DB(); _ = sqlDB.Close() })
|
||||
|
||||
account := &model.Account{Name: "Dyte Account", Locale: "en", Status: "active"}
|
||||
require.NoError(t, db.Create(account).Error)
|
||||
user := &model.User{AccountID: account.ID, Name: "Dyte Agent", Email: "dyte-agent@example.test", Password: "secret", Role: "agent"}
|
||||
require.NoError(t, db.Create(user).Error)
|
||||
inbox := &model.Inbox{AccountID: account.ID, Name: "Website", ChannelType: "web_widget", Enabled: true}
|
||||
require.NoError(t, db.Create(inbox).Error)
|
||||
require.NoError(t, db.Create(&model.InboxMember{InboxID: inbox.ID, UserID: user.ID, Role: "agent"}).Error)
|
||||
contact := &model.Contact{AccountID: account.ID, Name: "Visitor"}
|
||||
require.NoError(t, db.Create(contact).Error)
|
||||
displayID := uint(11)
|
||||
conversation := &model.Conversation{AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, DisplayID: &displayID, Status: "pending", ChannelType: "web_widget", Channel: "web_widget"}
|
||||
require.NoError(t, db.Create(conversation).Error)
|
||||
settings, _ := json.Marshal(map[string]any{"organization_id": "org", "api_key": "key"})
|
||||
require.NoError(t, db.Create(&model.IntegrationHook{AccountID: account.ID, AppID: "dyte", HookType: model.HookType("dyte"), Settings: datatypes.JSON(settings)}).Error)
|
||||
attrs, _ := json.Marshal(map[string]any{"type": "dyte", "data": map[string]any{"meeting_id": "m_id"}})
|
||||
message := &model.Message{AccountID: account.ID, InboxID: inbox.ID, ConversationID: conversation.ID, SenderID: &user.ID, SenderType: "user", MessageType: "outgoing", ContentType: "integrations", Content: "Join", Status: "sent", ContentAttributes: datatypes.JSON(attrs)}
|
||||
require.NoError(t, db.Create(message).Error)
|
||||
|
||||
svc := service.NewDyteIntegrationService(repository.NewIntegrationHookRepo(db), repository.NewMessageRepo(db))
|
||||
svc.SetBackend(dyteHandlerFakeBackend{})
|
||||
handler := NewDyteIntegrationHandler(svc)
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
c.Set("user_id", user.ID)
|
||||
c.Set("role", "agent")
|
||||
c.Next()
|
||||
})
|
||||
integrations := router.Group("/api/v1/accounts/:account_id/integrations")
|
||||
RegisterDyteIntegrationRoutes(integrations, handler)
|
||||
return router, db, account, user, conversation, message
|
||||
}
|
||||
|
||||
func decodeDyteHandlerBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
|
||||
t.Helper()
|
||||
var payload map[string]any
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload))
|
||||
return payload
|
||||
}
|
||||
@@ -149,6 +149,7 @@ type Handlers struct {
|
||||
ShopifyIntegration *v1.ShopifyIntegrationHandler
|
||||
LinearIntegration *v1.LinearIntegrationHandler
|
||||
NotionIntegration *v1.NotionIntegrationHandler
|
||||
DyteIntegration *v1.DyteIntegrationHandler
|
||||
PlatformUserSSO *v1.PlatformUserSSOHandler
|
||||
// Platform API AccessToken-authenticated handlers (distinct from SuperAdmin routes)
|
||||
PlatformUser *v1.PlatformUserHandler
|
||||
@@ -1570,6 +1571,8 @@ func registerV1Routes(g *gin.RouterGroup, h *Handlers) {
|
||||
v1.RegisterLinearIntegrationRoutes(integrations, h.LinearIntegration)
|
||||
// Notion integration
|
||||
v1.RegisterNotionIntegrationRoutes(integrations, h.NotionIntegration)
|
||||
// Dyte video meeting integration
|
||||
v1.RegisterDyteIntegrationRoutes(integrations, h.DyteIntegration)
|
||||
}
|
||||
|
||||
// CSAT Survey Responses — list, metrics, review notes
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const dyteBaseURL = "https://api.dyte.io/v2"
|
||||
|
||||
type DyteIntegrationService struct {
|
||||
hookRepo *repository.IntegrationHookRepo
|
||||
messageRepo *repository.MessageRepo
|
||||
backend DyteBackend
|
||||
frontendURL string
|
||||
}
|
||||
|
||||
type DyteCredentials struct {
|
||||
OrganizationID string
|
||||
APIKey string
|
||||
}
|
||||
|
||||
type DyteParticipant struct {
|
||||
ID uint
|
||||
Name string
|
||||
AvatarURL string
|
||||
}
|
||||
|
||||
type DyteAPIError struct {
|
||||
Payload map[string]any
|
||||
Status int
|
||||
}
|
||||
|
||||
type DyteBackend interface {
|
||||
CreateMeeting(ctx context.Context, credentials DyteCredentials, title string) (map[string]any, *DyteAPIError, error)
|
||||
AddParticipant(ctx context.Context, credentials DyteCredentials, meetingID string, participant DyteParticipant) (map[string]any, *DyteAPIError, error)
|
||||
}
|
||||
|
||||
type HTTPDyteBackend struct {
|
||||
baseURL string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewHTTPDyteBackend() *HTTPDyteBackend {
|
||||
return &HTTPDyteBackend{
|
||||
baseURL: dyteBaseURL,
|
||||
client: &http.Client{Timeout: 10 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func NewDyteIntegrationService(hookRepo *repository.IntegrationHookRepo, messageRepo *repository.MessageRepo) *DyteIntegrationService {
|
||||
return &DyteIntegrationService{
|
||||
hookRepo: hookRepo,
|
||||
messageRepo: messageRepo,
|
||||
backend: NewHTTPDyteBackend(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *DyteIntegrationService) SetBackend(backend DyteBackend) {
|
||||
if backend != nil {
|
||||
s.backend = backend
|
||||
}
|
||||
}
|
||||
|
||||
func (s *DyteIntegrationService) SetFrontendURL(frontendURL string) {
|
||||
s.frontendURL = strings.TrimRight(frontendURL, "/")
|
||||
}
|
||||
|
||||
func (s *DyteIntegrationService) DB() *gorm.DB {
|
||||
if s == nil || s.messageRepo == nil {
|
||||
return nil
|
||||
}
|
||||
return s.messageRepo.DB()
|
||||
}
|
||||
|
||||
func (s *DyteIntegrationService) CreateMeeting(ctx context.Context, accountID, userID, conversationDisplayID uint, role string) (*model.Message, *model.Conversation, *DyteAPIError, error) {
|
||||
conversation, err := s.findConversation(ctx, accountID, conversationDisplayID)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
if !s.canAccessConversation(ctx, accountID, conversation.InboxID, userID, role) {
|
||||
return nil, nil, nil, fmt.Errorf("forbidden")
|
||||
}
|
||||
user, err := s.findUser(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
credentials, err := s.credentials(ctx, accountID)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
|
||||
title := fmt.Sprintf("%s has started a meeting", availableUserName(user))
|
||||
meeting, apiErr, err := s.backend.CreateMeeting(ctx, credentials, title)
|
||||
if err != nil || apiErr != nil {
|
||||
return nil, conversation, apiErr, err
|
||||
}
|
||||
meetingID, _ := meeting["id"].(string)
|
||||
if strings.TrimSpace(meetingID) == "" {
|
||||
return nil, conversation, nil, fmt.Errorf("dyte meeting id missing")
|
||||
}
|
||||
|
||||
attrs := map[string]any{"type": "dyte", "data": map[string]any{"meeting_id": meetingID}}
|
||||
attrsJSON, _ := json.Marshal(attrs)
|
||||
message := &model.Message{
|
||||
AccountID: accountID,
|
||||
InboxID: conversation.InboxID,
|
||||
ConversationID: conversation.ID,
|
||||
SenderID: &user.ID,
|
||||
SenderType: "user",
|
||||
MessageType: string(model.MessageTypeOutgoing),
|
||||
ContentType: "integrations",
|
||||
Content: title,
|
||||
Status: "sent",
|
||||
ContentAttributes: datatypes.JSON(attrsJSON),
|
||||
}
|
||||
if err := s.messageRepo.Create(ctx, message); err != nil {
|
||||
return nil, conversation, nil, err
|
||||
}
|
||||
return message, conversation, nil, nil
|
||||
}
|
||||
|
||||
func (s *DyteIntegrationService) AddParticipant(ctx context.Context, accountID, userID, messageID uint, role string) (map[string]any, *DyteAPIError, error) {
|
||||
message, err := s.messageRepo.FindByAccountAndID(ctx, accountID, messageID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var conversation model.Conversation
|
||||
if err := s.DB().WithContext(ctx).Where("account_id = ? AND id = ?", accountID, message.ConversationID).First(&conversation).Error; err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !s.canAccessConversation(ctx, accountID, conversation.InboxID, userID, role) {
|
||||
return nil, nil, fmt.Errorf("forbidden")
|
||||
}
|
||||
if message.ContentType != "integrations" {
|
||||
return nil, &DyteAPIError{Payload: map[string]any{"error": "Invalid message type. Action not permitted"}, Status: http.StatusUnprocessableEntity}, nil
|
||||
}
|
||||
meetingID := dyteMeetingID(message.ContentAttributes)
|
||||
if meetingID == "" {
|
||||
return nil, nil, fmt.Errorf("meeting_id is required")
|
||||
}
|
||||
user, err := s.findUser(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
credentials, err := s.credentials(ctx, accountID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
payload, apiErr, err := s.backend.AddParticipant(ctx, credentials, meetingID, DyteParticipant{ID: user.ID, Name: availableUserName(user), AvatarURL: s.avatarURL(user)})
|
||||
if err != nil || apiErr != nil {
|
||||
return nil, apiErr, err
|
||||
}
|
||||
return payload, nil, nil
|
||||
}
|
||||
|
||||
func (s *DyteIntegrationService) findConversation(ctx context.Context, accountID, displayID uint) (*model.Conversation, error) {
|
||||
var conversation model.Conversation
|
||||
db := s.DB().WithContext(ctx)
|
||||
if err := db.Where("account_id = ? AND display_id = ?", accountID, displayID).First(&conversation).Error; err == nil {
|
||||
return &conversation, nil
|
||||
}
|
||||
if err := db.Where("account_id = ? AND id = ?", accountID, displayID).First(&conversation).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &conversation, nil
|
||||
}
|
||||
|
||||
func (s *DyteIntegrationService) findUser(ctx context.Context, userID uint) (*model.User, error) {
|
||||
if userID == 0 {
|
||||
return nil, fmt.Errorf("user not authenticated")
|
||||
}
|
||||
var user model.User
|
||||
if err := s.DB().WithContext(ctx).First(&user, userID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *DyteIntegrationService) canAccessConversation(ctx context.Context, accountID, inboxID, userID uint, role string) bool {
|
||||
if userID == 0 {
|
||||
return false
|
||||
}
|
||||
switch strings.ToLower(role) {
|
||||
case "administrator", "admin", "super_admin":
|
||||
return true
|
||||
}
|
||||
var member model.InboxMember
|
||||
return s.DB().WithContext(ctx).
|
||||
Joins("JOIN inboxes ON inboxes.id = inbox_members.inbox_id").
|
||||
Where("inbox_members.inbox_id = ? AND inbox_members.user_id = ? AND inboxes.account_id = ?", inboxID, userID, accountID).
|
||||
First(&member).Error == nil
|
||||
}
|
||||
|
||||
func (s *DyteIntegrationService) credentials(ctx context.Context, accountID uint) (DyteCredentials, error) {
|
||||
hooks, err := s.hookRepo.FindByAccountAndApp(ctx, accountID, "dyte")
|
||||
if err != nil {
|
||||
return DyteCredentials{}, err
|
||||
}
|
||||
if len(hooks) == 0 {
|
||||
return DyteCredentials{}, fmt.Errorf("dyte integration not found")
|
||||
}
|
||||
var settings map[string]any
|
||||
if err := json.Unmarshal(hooks[0].Settings, &settings); err != nil {
|
||||
return DyteCredentials{}, err
|
||||
}
|
||||
credentials := DyteCredentials{
|
||||
OrganizationID: stringMapValue(settings, "organization_id"),
|
||||
APIKey: stringMapValue(settings, "api_key"),
|
||||
}
|
||||
if credentials.OrganizationID == "" || credentials.APIKey == "" {
|
||||
return DyteCredentials{}, fmt.Errorf("dyte credentials are required")
|
||||
}
|
||||
return credentials, nil
|
||||
}
|
||||
|
||||
func (s *DyteIntegrationService) avatarURL(user *model.User) string {
|
||||
if user.AvatarURL != "" {
|
||||
return user.AvatarURL
|
||||
}
|
||||
base := s.frontendURL
|
||||
if base == "" {
|
||||
base = strings.TrimRight(os.Getenv("FRONTEND_URL"), "/")
|
||||
}
|
||||
if base == "" {
|
||||
base = "http://localhost:3000"
|
||||
}
|
||||
return base + "/integrations/slack/user.png"
|
||||
}
|
||||
|
||||
func dyteMeetingID(attrs datatypes.JSON) string {
|
||||
var raw map[string]any
|
||||
if err := json.Unmarshal(attrs, &raw); err != nil {
|
||||
return ""
|
||||
}
|
||||
data, _ := raw["data"].(map[string]any)
|
||||
return stringMapValue(data, "meeting_id")
|
||||
}
|
||||
|
||||
func availableUserName(user *model.User) string {
|
||||
if user == nil {
|
||||
return ""
|
||||
}
|
||||
if strings.TrimSpace(user.DisplayName) != "" {
|
||||
return strings.TrimSpace(user.DisplayName)
|
||||
}
|
||||
return strings.TrimSpace(user.Name)
|
||||
}
|
||||
|
||||
func stringMapValue(values map[string]any, key string) string {
|
||||
if values == nil {
|
||||
return ""
|
||||
}
|
||||
switch value := values[key].(type) {
|
||||
case string:
|
||||
return strings.TrimSpace(value)
|
||||
case fmt.Stringer:
|
||||
return strings.TrimSpace(value.String())
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (b *HTTPDyteBackend) CreateMeeting(ctx context.Context, credentials DyteCredentials, title string) (map[string]any, *DyteAPIError, error) {
|
||||
return b.post(ctx, credentials, "meetings", map[string]any{"title": title})
|
||||
}
|
||||
|
||||
func (b *HTTPDyteBackend) AddParticipant(ctx context.Context, credentials DyteCredentials, meetingID string, participant DyteParticipant) (map[string]any, *DyteAPIError, error) {
|
||||
if meetingID == "" || participant.ID == 0 || strings.TrimSpace(participant.Name) == "" || strings.TrimSpace(participant.AvatarURL) == "" {
|
||||
return nil, nil, errors.New("missing information")
|
||||
}
|
||||
payload := map[string]any{
|
||||
"custom_participant_id": fmt.Sprintf("%d", participant.ID),
|
||||
"name": participant.Name,
|
||||
"picture": participant.AvatarURL,
|
||||
"preset_name": "group_call_host",
|
||||
}
|
||||
return b.post(ctx, credentials, "meetings/"+meetingID+"/participants", payload)
|
||||
}
|
||||
|
||||
func (b *HTTPDyteBackend) post(ctx context.Context, credentials DyteCredentials, path string, payload map[string]any) (map[string]any, *DyteAPIError, error) {
|
||||
if credentials.OrganizationID == "" || credentials.APIKey == "" {
|
||||
return nil, nil, errors.New("missing credentials")
|
||||
}
|
||||
body, _ := json.Marshal(payload)
|
||||
baseURL := strings.TrimRight(b.baseURL, "/")
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+"/"+strings.TrimLeft(path, "/"), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
auth := base64.StdEncoding.EncodeToString([]byte(credentials.OrganizationID + ":" + credentials.APIKey))
|
||||
req.Header.Set("Authorization", "Basic "+auth)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := b.client
|
||||
if client == nil {
|
||||
client = http.DefaultClient
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var decoded map[string]any
|
||||
if err := json.NewDecoder(resp.Body).Decode(&decoded); err != nil {
|
||||
decoded = map[string]any{"message": err.Error()}
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, &DyteAPIError{Payload: decoded, Status: resp.StatusCode}, nil
|
||||
}
|
||||
if data, ok := decoded["data"].(map[string]any); ok {
|
||||
return data, nil, nil
|
||||
}
|
||||
return decoded, nil, nil
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
)
|
||||
|
||||
type fakeDyteBackend struct {
|
||||
createPayload map[string]any
|
||||
createError *DyteAPIError
|
||||
joinPayload map[string]any
|
||||
joinError *DyteAPIError
|
||||
lastTitle string
|
||||
lastMeetingID string
|
||||
}
|
||||
|
||||
func (f *fakeDyteBackend) CreateMeeting(_ context.Context, _ DyteCredentials, title string) (map[string]any, *DyteAPIError, error) {
|
||||
f.lastTitle = title
|
||||
return f.createPayload, f.createError, nil
|
||||
}
|
||||
|
||||
func (f *fakeDyteBackend) AddParticipant(_ context.Context, _ DyteCredentials, meetingID string, _ DyteParticipant) (map[string]any, *DyteAPIError, error) {
|
||||
f.lastMeetingID = meetingID
|
||||
return f.joinPayload, f.joinError, nil
|
||||
}
|
||||
|
||||
func TestDyteIntegrationServiceCreateMeetingCreatesIntegrationMessage(t *testing.T) {
|
||||
db := setupServiceTestDB(t)
|
||||
require.NoError(t, db.AutoMigrate(&model.IntegrationHook{}))
|
||||
account := createTestAccount(t, db)
|
||||
user := createTestUser(t, db, account.ID)
|
||||
user.Name = "Ada Agent"
|
||||
require.NoError(t, db.Save(user).Error)
|
||||
inbox := &model.Inbox{AccountID: account.ID, Name: "Website", ChannelType: "web_widget", Enabled: true}
|
||||
require.NoError(t, db.Create(inbox).Error)
|
||||
require.NoError(t, db.Create(&model.InboxMember{InboxID: inbox.ID, UserID: user.ID, Role: "agent"}).Error)
|
||||
contact := &model.Contact{AccountID: account.ID, Name: "Visitor"}
|
||||
require.NoError(t, db.Create(contact).Error)
|
||||
displayID := uint(42)
|
||||
conversation := &model.Conversation{AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, DisplayID: &displayID, Status: "pending", ChannelType: "web_widget", Channel: "web_widget"}
|
||||
require.NoError(t, db.Create(conversation).Error)
|
||||
settings, _ := json.Marshal(map[string]any{"organization_id": "org", "api_key": "key"})
|
||||
require.NoError(t, db.Create(&model.IntegrationHook{AccountID: account.ID, AppID: "dyte", HookType: model.HookType("dyte"), Settings: datatypes.JSON(settings)}).Error)
|
||||
|
||||
backend := &fakeDyteBackend{createPayload: map[string]any{"id": "meeting_id"}}
|
||||
svc := NewDyteIntegrationService(repository.NewIntegrationHookRepo(db), repository.NewMessageRepo(db))
|
||||
svc.SetBackend(backend)
|
||||
|
||||
message, resolvedConversation, apiErr, err := svc.CreateMeeting(context.Background(), account.ID, user.ID, displayID, "agent")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, apiErr)
|
||||
require.Equal(t, conversation.ID, resolvedConversation.ID)
|
||||
require.Equal(t, "Ada Agent has started a meeting", backend.lastTitle)
|
||||
require.Equal(t, "integrations", message.ContentType)
|
||||
require.Equal(t, "outgoing", message.MessageType)
|
||||
require.Equal(t, "Ada Agent has started a meeting", message.Content)
|
||||
require.Equal(t, user.ID, *message.SenderID)
|
||||
require.Equal(t, "meeting_id", dyteMeetingID(message.ContentAttributes))
|
||||
}
|
||||
|
||||
func TestDyteIntegrationServiceCreateMeetingPropagatesDyteErrors(t *testing.T) {
|
||||
db, account, user, displayID := setupDyteServiceFixture(t)
|
||||
backend := &fakeDyteBackend{createError: &DyteAPIError{Payload: map[string]any{"success": false, "data": map[string]any{"message": "Title is required"}}, Status: http.StatusUnprocessableEntity}}
|
||||
svc := NewDyteIntegrationService(repository.NewIntegrationHookRepo(db), repository.NewMessageRepo(db))
|
||||
svc.SetBackend(backend)
|
||||
|
||||
message, _, apiErr, err := svc.CreateMeeting(context.Background(), account.ID, user.ID, displayID, "agent")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, message)
|
||||
require.NotNil(t, apiErr)
|
||||
require.Equal(t, http.StatusUnprocessableEntity, apiErr.Status)
|
||||
var count int64
|
||||
require.NoError(t, db.Model(&model.Message{}).Count(&count).Error)
|
||||
require.Zero(t, count)
|
||||
}
|
||||
|
||||
func TestDyteIntegrationServiceAddParticipant(t *testing.T) {
|
||||
db, account, user, _ := setupDyteServiceFixture(t)
|
||||
message := createDyteIntegrationMessage(t, db, account.ID, user.ID)
|
||||
backend := &fakeDyteBackend{joinPayload: map[string]any{"id": "participant", "auth_token": "jwt"}}
|
||||
svc := NewDyteIntegrationService(repository.NewIntegrationHookRepo(db), repository.NewMessageRepo(db))
|
||||
svc.SetBackend(backend)
|
||||
|
||||
payload, apiErr, err := svc.AddParticipant(context.Background(), account.ID, user.ID, message.ID, "agent")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, apiErr)
|
||||
require.Equal(t, "m_id", backend.lastMeetingID)
|
||||
require.Equal(t, "jwt", payload["auth_token"])
|
||||
}
|
||||
|
||||
func setupDyteServiceFixture(t *testing.T) (*gorm.DB, *model.Account, *model.User, uint) {
|
||||
t.Helper()
|
||||
db := setupServiceTestDB(t)
|
||||
require.NoError(t, db.AutoMigrate(&model.IntegrationHook{}))
|
||||
account := createTestAccount(t, db)
|
||||
user := createTestUser(t, db, account.ID)
|
||||
inbox := &model.Inbox{AccountID: account.ID, Name: "Website", ChannelType: "web_widget", Enabled: true}
|
||||
require.NoError(t, db.Create(inbox).Error)
|
||||
require.NoError(t, db.Create(&model.InboxMember{InboxID: inbox.ID, UserID: user.ID, Role: "agent"}).Error)
|
||||
contact := &model.Contact{AccountID: account.ID, Name: "Visitor"}
|
||||
require.NoError(t, db.Create(contact).Error)
|
||||
displayID := uint(7)
|
||||
conversation := &model.Conversation{AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, DisplayID: &displayID, Status: "pending", ChannelType: "web_widget", Channel: "web_widget"}
|
||||
require.NoError(t, db.Create(conversation).Error)
|
||||
settings, _ := json.Marshal(map[string]any{"organization_id": "org", "api_key": "key"})
|
||||
require.NoError(t, db.Create(&model.IntegrationHook{AccountID: account.ID, AppID: "dyte", HookType: model.HookType("dyte"), Settings: datatypes.JSON(settings)}).Error)
|
||||
return db, account, user, displayID
|
||||
}
|
||||
|
||||
func createDyteIntegrationMessage(t *testing.T, db *gorm.DB, accountID, userID uint) *model.Message {
|
||||
t.Helper()
|
||||
var conversation model.Conversation
|
||||
require.NoError(t, db.Where("account_id = ?", accountID).First(&conversation).Error)
|
||||
attrs, _ := json.Marshal(map[string]any{"type": "dyte", "data": map[string]any{"meeting_id": "m_id"}})
|
||||
message := &model.Message{AccountID: accountID, InboxID: conversation.InboxID, ConversationID: conversation.ID, SenderID: &userID, SenderType: "user", MessageType: "outgoing", ContentType: "integrations", Content: "Join", Status: "sent", ContentAttributes: datatypes.JSON(attrs)}
|
||||
require.NoError(t, db.Create(message).Error)
|
||||
return message
|
||||
}
|
||||
@@ -258,7 +258,7 @@ func validMessageType(value string) bool {
|
||||
|
||||
func validContentType(value string) bool {
|
||||
switch value {
|
||||
case "text", "input_text", "input_email", "input_phone", "select", "card", "private_note", "input_csat", "file", "image", "audio", "video", "voice_call":
|
||||
case "text", "input_text", "input_email", "input_phone", "select", "card", "private_note", "input_csat", "file", "image", "audio", "video", "voice_call", "integrations":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
|
||||
Reference in New Issue
Block a user