feat(accounts): align onboarding update

This commit is contained in:
2026-06-06 21:18:38 +08:00
parent 3aa21996f6
commit 4736d67839
11 changed files with 254 additions and 22 deletions
+1
View File
@@ -50,6 +50,7 @@ var criticalRoutes = []route{
{Method: "POST", Path: "/api/v1/accounts/:account_id/update_active_at", Controller: "api/v1/accounts#update_active_at", Source: "routes.rb:49"},
{Method: "GET", Path: "/api/v1/accounts/:account_id/cache_keys", Controller: "api/v1/accounts#cache_keys", Source: "routes.rb:50"},
{Method: "POST", Path: "/api/v1/accounts/:account_id/actions/contact_merge", Controller: "api/v1/accounts/actions/contact_merges#create", Source: "routes.rb:55"},
{Method: "PATCH", Path: "/api/v1/accounts/:account_id/onboarding", Controller: "api/v1/accounts/onboardings#update", Source: "routes.rb:58"},
{Method: "GET", Path: "/api/v1/accounts/:account_id/agents", Controller: "api/v1/accounts/agents#index", Source: "routes.rb:59"},
{Method: "POST", Path: "/api/v1/accounts/:account_id/agents", Controller: "api/v1/accounts/agents#create", Source: "routes.rb:59"},
+10 -6
View File
@@ -49,16 +49,16 @@ Hermes task landing checklist:
## Current Baseline
- Current tracking checkpoint: 2026-06-06 account notification scoping hardening checkpoint, prepared as `feat(notifications): tighten chatwoot scoping`.
- Latest implementation checkpoint: this checkpoint, prepared as `feat(notifications): tighten chatwoot scoping`.
- Latest documentation/tooling checkpoint: this tracker update for P3.35 plus the landed parity tracker history; this document is the active follow-up plan and supersedes `.hermes/plans/*`.
- Current tracking checkpoint: 2026-06-06 account onboarding route/payload parity checkpoint, prepared as `feat(accounts): align onboarding update`.
- Latest implementation checkpoint: this checkpoint, prepared as `feat(accounts): align onboarding update`.
- Latest documentation/tooling checkpoint: this tracker update for P3.36 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: account notification mutation scoping from `reference/chatwoot/config/routes.rb:283-291`, `app/controllers/api/v1/accounts/notifications_controller.rb`, `app/finders/notification_finder.rb`, `app/views/api/v1/accounts/notifications/index.json.jbuilder`, and reused dashboard `api/notifications.js` is hardened. GoChat now fetches, updates, deletes, snoozes, marks unread, and counts notifications through the current user/current account scope; `snoozed_until` accepts Chatwoot Unix timestamp input and records `meta.last_snoozed_at`; missing snooze time is a scoped no-op that returns the current notification; destroy remains empty `200 OK`. API v2 year-in-review and WhatsApp calling toggle parity remain implemented from previous checkpoints. Live API/browser/enterprise smoke still needs the full PostgreSQL/Redis/Meilisearch/GoChat/Vite/Chrome stack.
- Worktree status at this implementation checkpoint: account onboarding update from `reference/chatwoot/config/routes.rb:58`, `app/controllers/api/v1/accounts/onboardings_controller.rb`, account update/model Jbuilder views, and reused dashboard onboarding/store clients is implemented. GoChat now registers administrator-gated `PATCH /api/v1/accounts/:account_id/onboarding`, accepts the frontend raw onboarding payload, persists permitted account fields plus account `custom_attributes`, clears `onboarding_step` when finalizing account details, and returns the raw Chatwoot account serializer shape. Account notification scoping, API v2 year-in-review, and WhatsApp calling toggle parity remain implemented from previous checkpoints. Live API/browser/enterprise smoke still needs the full PostgreSQL/Redis/Meilisearch/GoChat/Vite/Chrome stack.
- Next executable implementation checkpoint: continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke from fresh reference/smoke evidence.
- `go test ./...` passes when run outside the restricted socket sandbox; focused Notification handler/repository/service tests pass in the sandbox.
- Route dump succeeds with `951` registered routes after API v2 year-in-review route tracking.
- Route dump succeeds with `952` registered routes after account onboarding route tracking.
- Route parity artifacts now exist under `docs/parity/` and are generated by `cmd/route_parity`.
- Tracked frontend-critical route audit covers 414 Chatwoot routes: 401 exact, 0 method-compatible, 13 parameter-compatible, 0 missing. The 13 parameter-compatible routes are Gin-internal parameter-name differences for nested AgentCapacityPolicy users/inbox limits, dashboard app member `:id` names, plus the public article `.md`/`.png` suffixes served through the same external article route dispatcher.
- Tracked frontend-critical route audit covers 415 Chatwoot routes: 402 exact, 0 method-compatible, 13 parameter-compatible, 0 missing. The 13 parameter-compatible routes are Gin-internal parameter-name differences for nested AgentCapacityPolicy users/inbox limits, dashboard app member `:id` names, plus the public article `.md`/`.png` suffixes served through the same external article route dispatcher.
- `/api/v1/widget` stubs are burned down and public inbox/contact/conversation/message core flows are backed by real handlers.
- Handler test stability fixes are committed into the baseline before feature parity work continues.
- `.codegraph/` is generated indexing output and is not part of tracked product code.
@@ -140,6 +140,7 @@ This table is the shortest authoritative handoff view. If an older lower section
| Priority | Workstream | Current state | Next checkpoint | Commit close rule |
| --- | --- | --- | --- | --- |
| 0 | P3.36 account onboarding route/payload parity | Implemented for reused dashboard onboarding: `PATCH /api/v1/accounts/:account_id/onboarding` is registered and tracked from `routes.rb:58`, administrator-gated like Chatwoot `OnboardingsController#update`, accepts raw `name`, `locale`, `website`, `industry`, `company_size`, `timezone`, `referral_source`, and `user_role`, persists account `custom_attributes` through `accounts.custom_attributes`, clears `onboarding_step` when current account details are finalized, and returns the raw account serializer with selected custom-attribute fields. | Keep in Review; reopen only if live onboarding smoke exposes additional account serializer fields, empty-string/null strong-param drift, admin policy drift, or onboarding step behavior beyond the inspected controller/Jbuilder/frontend contract. | Focused Account handler/service tests, router/route-parity tests, route dump/parity regeneration (`952` routes; `402 exact`, `13 parameter-compatible`, `0 missing out of 415`), full `go test ./...`, and `git diff --check` must pass. |
| 0 | P3.35 account notification scoping hardening | Implemented for reused dashboard notification actions: account notifications now follow Chatwoot `fetch_notification` scope (`current_user.notifications.where(account_id: Current.account.id)`) for show, update/read, destroy, snooze, unread, and unread count. `snoozed_until` is parsed as Unix seconds like `DateRangeHelper`, snooze merges `meta.last_snoozed_at: null`, missing `snoozed_until` returns the scoped notification without mutation, destroy returns empty `200 OK`, and cross-user/cross-account mutations return `404`. | Keep in Review; reopen only if live notification-center smoke exposes list metadata, snooze timestamp, read/unread, destroy_all async, or notification serializer drift beyond the inspected controller/finder/Jbuilder/frontend contract. | Focused Notification handler/repository/service tests, full `go test ./...`, and `git diff --check` passed. No route artifacts change because only handler/repository/service behavior changed. |
| 0 | P3.34 API v2 year-in-review parity | Implemented for reused dashboard year-in-review client: `GET /api/v2/accounts/:account_id/year_in_review?year=YYYY` is registered and tracked from `routes.rb:505`, returns raw `{ year, total_conversations, busiest_day, support_personality }`, defaults missing `year` to `2025`, reads/writes the current user's `ui_settings` cache under `year_in_review_<account_id>_<year>`, counts conversations assigned to the current user during the selected year, formats the busiest assigned conversation day as `Mon DD`, and truncates the average `first_response` reporting-event value into seconds. | Keep in Review; reopen only if live reused-dashboard year-in-review smoke exposes timezone, cache-present, invalid-year, or payload-shape drift beyond the inspected controller/builder/frontend contract. | Focused YearInReview service/handler tests, router/route-parity tests, route dump/parity regeneration (`951` routes; `401 exact`, `13 parameter-compatible`, `0 missing out of 414`), full `go test ./...`, and `git diff --check` passed. |
| 0 | P3.33 WhatsApp calling toggle parity | Implemented for reused dashboard inbox voice settings: `POST /api/v1/accounts/:account_id/inboxes/:inbox_id/enable_whatsapp_calling` and `disable_whatsapp_calling` are registered and tracked from `routes.rb:266-267`, administrator-gated like `InboxPolicy`, scoped to WhatsApp Cloud API inboxes, enable requires account feature flag `channel_voice`, enable calls Meta phone-number `/settings` with `ENABLED`, webhook setup subscribes `messages/smb_message_echoes/calls`, provider config persists `calling_enabled: true`, disable persists `calling_enabled: false` without calling Meta settings, and webhook re-registration without `calls` is best-effort. Handlers return empty `200 OK` on success and `422 { error }` for unsupported inbox, missing feature flag, provider setup, or Meta update errors. | Keep in Review; reopen only if live WhatsApp calling settings smoke exposes Meta API version/base URL drift, webhook subscribed-field behavior drift, `voice_enabled` serializer drift, or frontend error/status drift beyond the inspected enterprise controller/model/provider/frontend contract. | Focused WhatsApp calling service/channel/handler tests, router/route-parity tests, route dump/parity regeneration (`950` routes; `400 exact`, `13 parameter-compatible`, `0 missing out of 413`), full `go test ./...`, and `git diff --check` passed. |
@@ -181,6 +182,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.36 account onboarding route/payload parity | `internal/model/account.go`, `internal/service/account_service.go`, `internal/handler/api/v1/account_handler.go`, `internal/router/router.go`, `cmd/route_parity/main.go`, `migrations/000033_add_accounts_custom_attributes.*`, account handler/service/router tests | `reference/chatwoot/config/routes.rb:58`, `reference/chatwoot/app/controllers/api/v1/accounts/onboardings_controller.rb`, `reference/chatwoot/app/views/api/v1/accounts/update.json.jbuilder`, `reference/chatwoot/app/views/api/v1/models/_account.json.jbuilder`, `reference/chatwoot/app/javascript/dashboard/api/onboarding.js`, `reference/chatwoot/app/javascript/dashboard/store/modules/accounts.js`, `reference/chatwoot/app/javascript/dashboard/routes/dashboard/onboarding/Index.vue` | Done. Account onboarding update now matches the reused dashboard path: `PATCH /api/v1/accounts/:account_id/onboarding` is tracked and registered with administrator authorization; the handler accepts the raw frontend onboarding payload; the service merges permitted onboarding attributes into persisted account `custom_attributes`, mirrors timezone for existing account consumers, clears `onboarding_step` only when finalizing account details, and the account serializer emits the Chatwoot selected custom-attribute fields while preserving subscription/deletion placeholders. | Review by `feat(accounts): align onboarding update`; focused account handler tests cover finalizing and non-finalizing onboarding merges plus raw account response shape; service/router/route-parity tests and route artifacts cover the new account route; full `go test ./...` and `git diff --check` must pass. |
| P3.35 account notification scoping hardening | `internal/repository/notification_repo.go`, `internal/service/notification_service.go`, `internal/handler/api/v1/notification_handler.go`, notification handler/repository/service tests | `reference/chatwoot/config/routes.rb:283-291`, `reference/chatwoot/app/controllers/api/v1/accounts/notifications_controller.rb`, `reference/chatwoot/app/finders/notification_finder.rb`, `reference/chatwoot/app/views/api/v1/accounts/notifications/index.json.jbuilder`, `reference/chatwoot/app/javascript/dashboard/api/notifications.js` | Done. Account notification show/update/destroy/snooze/unread/unread_count now use current-user/current-account scope; cross-account and cross-user rows do not leak; `snoozed_until` accepts Unix seconds; snooze merges `meta.last_snoozed_at`; absent `snoozed_until` is a scoped no-op; destroy keeps Chatwoot empty `200 OK`. | Review by `feat(notifications): tighten chatwoot scoping`; focused handler tests cover mutation scoping, account unread count, Unix snooze, no-body snooze, and destroy route coverage; repository/service notification tests cover scoped helpers; full `go test ./...` and `git diff --check` passed. No route artifacts change. |
| P3.34 API v2 year-in-review parity | `internal/service/year_in_review_service.go`, `internal/handler/api/v1/year_in_review_handler.go`, `internal/router/router.go`, `internal/app/bootstrap.go`, `cmd/route_parity/main.go`, YearInReview service/handler/router tests | `reference/chatwoot/config/routes.rb:505`, `reference/chatwoot/app/controllers/api/v2/accounts/year_in_reviews_controller.rb`, `reference/chatwoot/app/builders/year_in_review_builder.rb`, `reference/chatwoot/app/javascript/dashboard/api/yearInReview.js` | Done. API v2 year-in-review now matches the reused dashboard route and builder boundary: account-scoped `GET /api/v2/accounts/:account_id/year_in_review` is tracked and registered; response is raw JSON; missing `year` defaults to `2025`; the current user/account cache key is persisted in `ui_settings`; assigned yearly conversation totals, busiest day, and average first-response seconds are derived from persisted conversations/reporting events. | Review by `feat(reports): align year in review`; focused service tests cover aggregate payload, busiest day, average truncation, cache storage, cache reuse, and empty personality; handler tests cover raw response shape, auth, and invalid year; router/route-parity tests and route artifacts regenerate to `TOTAL: 951` and `401 exact, 13 parameter-compatible, 0 missing out of 414`; full `go test ./...` and `git diff --check` must pass. |
| P3.33 WhatsApp calling toggle parity | `internal/service/inbox_service.go`, `internal/channel/whatsapp/service.go`, `internal/handler/api/v1/inbox_handler.go`, `internal/router/router.go`, `cmd/route_parity/main.go`, WhatsApp calling service/channel/handler tests | `reference/chatwoot/config/routes.rb:266-267`, `reference/chatwoot/enterprise/app/controllers/enterprise/api/v1/accounts/inboxes_controller.rb`, `reference/chatwoot/app/models/channel/whatsapp.rb`, `reference/chatwoot/enterprise/app/services/enterprise/whatsapp/providers/whatsapp_cloud_service.rb`, `reference/chatwoot/app/services/whatsapp/webhook_setup_service.rb`, `reference/chatwoot/app/services/whatsapp/facebook_api_client.rb`, `reference/chatwoot/app/policies/inbox_policy.rb`, `reference/chatwoot/app/javascript/dashboard/api/inboxes.js` | Done. WhatsApp calling enable/disable now matches the reused dashboard and enterprise backend boundary: member routes are tracked and registered; administrator policy is enforced at the router; unsupported non-WhatsApp/non-Cloud inboxes return Chatwoot's `422` error; enable requires `channel_voice`, calls Meta `/settings` with status `ENABLED`, registers webhook fields including `calls`, and persists `calling_enabled`; disable persists `calling_enabled: false`, updates inbox `voice_enabled`, and best-effort re-registers only `messages/smb_message_echoes`. | Review by `feat(channels): align whatsapp calling toggles`; focused service tests cover enable persistence/webhook, unsupported/feature gates, and disable best-effort behavior; channel provider tests cover Meta settings request/error parsing; handler tests cover bad params and empty `200 OK`; route dump/parity regenerated to `TOTAL: 950` and `400 exact, 13 parameter-compatible, 0 missing out of 413`; full `go test ./...` and `git diff --check` must pass. |
@@ -254,6 +256,7 @@ This ledger records the committed parity checkpoints that future slices should b
| Commit | Scope | Verification summary | Follow-up state |
| --- | --- | --- | --- |
| `feat(accounts): align onboarding update` | Advances P3.36 account onboarding route/payload parity by matching Chatwoot `Api::V1::Accounts::OnboardingsController#update`, account update/model Jbuilder payloads, route `58`, and reused dashboard onboarding API/store/Vue flow. GoChat now persists `accounts.custom_attributes`, exposes administrator-gated `PATCH /api/v1/accounts/:account_id/onboarding`, accepts the raw onboarding payload, merges permitted custom attributes, clears `onboarding_step` when finalizing account details, and returns the raw account serializer shape. | `go test ./internal/handler/api/v1 -run AccountHandler -count=1`; `go test ./internal/service -run AccountService -count=1`; `go test ./cmd/route_parity ./internal/router -run 'RouteParity\|RegisterRoutes' -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: 952`; tracked route parity is `402 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 415`. | P3.36 moves to Review for current onboarding/account serializer evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. |
| `feat(notifications): tighten chatwoot scoping` | Advances P3.35 account notification scoping hardening by matching Chatwoot `NotificationsController#fetch_notification`, `NotificationFinder`, notification routes `283-291`, index Jbuilder behavior, and reused dashboard `notifications.js`. GoChat now scopes show, update/read, destroy, snooze, unread, and unread_count to the current user and account; parses snooze timestamps as Unix seconds; merges `meta.last_snoozed_at: null`; treats missing `snoozed_until` as a scoped no-op; and keeps destroy as empty `200 OK`. | `go test ./internal/handler/api/v1 -run Notification -count=1`; `go test ./internal/repository -run Notification -count=1`; `go test ./internal/service -run Notification -count=1`; full `go test ./...`; `git diff --check`. Route artifacts are unchanged. | P3.35 moves to Review for current notification action scoping evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. |
| `feat(reports): align year in review` | Advances P3.34 API v2 year-in-review parity by matching Chatwoot `Api::V2::Accounts::YearInReviewsController#show`, `YearInReviewBuilder`, route `505`, current-user `ui_settings` caching, and reused dashboard `api/yearInReview.js`. GoChat now exposes `GET /api/v2/accounts/:account_id/year_in_review`, returns raw `{ year, total_conversations, busiest_day, support_personality }`, defaults missing `year` to `2025`, stores cached data under `year_in_review_<account_id>_<year>`, counts current-user assigned conversations in the selected year, formats the busiest day as `Mon DD`, and truncates average `first_response` seconds. | `go test ./internal/service -run YearInReview -count=1`; `go test ./internal/handler/api/v1 -run YearInReview -count=1`; `go test ./internal/router ./cmd/route_parity -run 'RegisterRoutes\|RouteParity' -count=1`; `go run ./cmd/dump_routes > docs/parity/gochat_routes.txt`; `go run ./cmd/route_parity`; full `go test ./...`; `git diff --check`. Route dump is `TOTAL: 951`; tracked route parity is `401 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 414`. | P3.34 moves to Review for current API v2 year-in-review evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. |
| `feat(channels): align whatsapp calling toggles` | Advances P3.33 WhatsApp calling toggle parity by matching Chatwoot enterprise inbox member actions, WhatsApp channel model voice gates, Meta calling status provider call, webhook subscribed-field behavior, inbox policy, routes `266-267`, and reused dashboard `api/inboxes.js`. GoChat now exposes administrator-gated enable/disable member routes, supports only WhatsApp Cloud API inboxes, requires `channel_voice` for enable, calls Meta phone-number `/settings` with `ENABLED`, persists `provider_config.calling_enabled`, mirrors `voice_enabled` into the inbox serializer config, and best-effort removes the `calls` webhook field on disable. | `go test ./internal/service -run 'WhatsAppCalling\|WhatsAppAuthorization\|InboxService_(RegisterWebhook\|SyncTemplates)' -count=1`; `go test ./internal/channel/whatsapp -run 'UpdateCallingStatus\|FetchHealthStatus' -count=1`; `go test ./internal/handler/api/v1 -run 'InboxWhatsAppCalling\|Inbox(RegisterWebhook\|SyncTemplates)' -count=1`; `go test ./internal/router ./cmd/route_parity -run 'Router\|RouteParity' -count=1`; `go run ./cmd/dump_routes > docs/parity/gochat_routes.txt`; `go run ./cmd/route_parity`; full `go test ./...`; `git diff --check`. Route dump is `TOTAL: 950`; tracked route parity is `400 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 413`. | P3.33 moves to Review for current WhatsApp calling toggle evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. |
@@ -2270,6 +2273,7 @@ Verification milestone gates:
## Progress Log
- 2026-06-06: P3.36 account onboarding checkpoint prepared as `feat(accounts): align onboarding update`; audited Chatwoot account onboarding route `58`, `Api::V1::Accounts::OnboardingsController#update`, account update/model Jbuilder views, and reused dashboard `api/onboarding.js`, account store `finishOnboarding`, and onboarding Vue payload. GoChat now registers administrator-gated `PATCH /api/v1/accounts/:account_id/onboarding`, adds persisted `accounts.custom_attributes`, accepts the raw frontend payload, merges permitted onboarding custom attributes, clears `onboarding_step` when finalizing account details, and returns the raw account serializer with Chatwoot selected custom-attribute fields. Focused account handler/service tests, router/route-parity tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed; route dump is `TOTAL: 952` and tracked route parity is `402 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 415`.
- 2026-06-06: P3.35 account notification scoping checkpoint prepared as `feat(notifications): tighten chatwoot scoping`; audited Chatwoot notification routes `283-291`, `NotificationsController`, `NotificationFinder`, notification index Jbuilder, and reused dashboard `api/notifications.js`. Account notification show/update/destroy/snooze/unread/unread_count now use current-user/current-account scope, cross-account and cross-user rows return `404`, `snoozed_until` is parsed as Unix seconds, snooze merges `meta.last_snoozed_at: null`, absent `snoozed_until` is a scoped no-op returning the notification, and destroy returns empty `200 OK`. Focused notification handler/repository/service tests, full `go test ./...`, and `git diff --check` passed. No route artifacts changed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke.
- 2026-06-06: P3.13 dashboard apps checkpoint prepared as `feat(dashboard-apps): align chatwoot payloads`; audited Chatwoot `routes.rb:130`, `DashboardAppsController`, dashboard app Jbuilder views, `DashboardApp` content schema, reused dashboard `api/dashboardApps.js`, Vuex `dashboardApps` store, and DashboardApps modal/index components. Dashboard app routes are now tracked, create/update accept raw frontend bodies as well as `{ dashboard_app: ... }`, create returns raw `200 OK` payloads, list/show/create/update return only `id`, `title`, `content`, and `created_at`, show/update/delete are account-scoped, delete returns `204`, and content validation rejects empty arrays, non-frame widgets, and non-HTTP(S) URLs. Focused dashboard app handler/service tests, combined handler/service/repository/router/route-parity tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed; route dump remains `TOTAL: 907` and tracked route parity is `357 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 370`.
- 2026-06-06: P3.12 account Dyte integration checkpoint prepared as `feat(integrations): align dyte meeting routes`; audited Chatwoot `routes.rb:357-358`, `Api::V1::Accounts::Integrations::DyteController`, `Integrations::Dyte::ProcessorService`, `lib/dyte.rb`, reused dashboard `api/integrations/dyte.js`, `VideoCallButton.vue`, and the Dyte message bubble. Account Dyte create-meeting/add-participant routes are now registered and tracked, create-meeting resolves conversations by display ID, checks inbox access, loads account hook credentials, creates an outgoing `integrations` message with `content_attributes.type=dyte`, and returns the normal message serializer; add-participant rejects non-integration messages with the reference error and returns the Dyte participant token payload through a fakeable backend. Focused Dyte service/handler tests, combined handler/service/router/app/route-parity tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed; route dump is `TOTAL: 907` and tracked route parity is `355 exact, 0 method-compatible, 9 parameter-compatible, 0 missing out of 364`.
+2 -1
View File
@@ -541,6 +541,7 @@ PATCH /api/v1/accounts/:account_id/integrations/slack/
PATCH /api/v1/accounts/:account_id/notification_settings
PATCH /api/v1/accounts/:account_id/notification_settings/
PATCH /api/v1/accounts/:account_id/notifications/:notification_id
PATCH /api/v1/accounts/:account_id/onboarding
PATCH /api/v1/accounts/:account_id/portals/:portal_id
PATCH /api/v1/accounts/:account_id/portals/:portal_id/archive
PATCH /api/v1/accounts/:account_id/portals/:portal_id/articles/:article_id
@@ -949,4 +950,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: 951
TOTAL: 952
+2 -1
View File
@@ -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: 401 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 414 tracked critical routes.
Summary: 402 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 415 tracked critical routes.
## Missing Critical Routes
@@ -272,6 +272,7 @@ These routes exist with equivalent method and path shape but different parameter
| 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/onboarding` | `/api/v1/accounts/:account_id/onboarding` | `api/v1/accounts/onboardings#update` | `routes.rb:58` | 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 |
+83 -13
View File
@@ -154,6 +154,32 @@ func (h *AccountHandler) Update(c *gin.Context) {
c.JSON(http.StatusOK, serializeAccount(account))
}
// UpdateOnboarding updates account details from the dashboard onboarding flow.
// PATCH /api/v1/accounts/:account_id/onboarding
// Reference: Chatwoot Api::V1::Accounts::OnboardingsController#update.
func (h *AccountHandler) UpdateOnboarding(c *gin.Context) {
id := parseAccountIDParam(c)
if id == 0 {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account id")
return
}
var req service.UpdateAccountOnboardingRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
account, err := h.svc.UpdateOnboarding(c.Request.Context(), id, req)
if err != nil {
applogger.L().Errorf("Update onboarding account: %v", err)
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to update account onboarding")
return
}
c.JSON(http.StatusOK, serializeAccount(account))
}
// @Summary Delete an account
// @Description Soft-deletes an account by ID
// @Tags Accounts
@@ -361,23 +387,67 @@ func serializeAccount(account *model.Account) map[string]any {
if account == nil {
return map[string]any{}
}
customAttributes := serializeAccountCustomAttributes(account)
return map[string]any{
"settings": serializeAccountSettings(account),
"created_at": account.CreatedAt,
"domain": account.Domain,
"features": parseAccountFeatures(account.FeatureFlags),
"id": account.ID,
"locale": nonEmpty(account.Locale, "en"),
"name": account.Name,
"support_email": nil,
"status": nonEmpty(account.Status, "active"),
"cache_keys": map[string]string{"label": "0000000000", "inbox": "0000000000", "team": "0000000000"},
"custom_attributes": map[string]any{
"timezone": account.Timezone,
},
"settings": serializeAccountSettings(account),
"created_at": account.CreatedAt,
"domain": account.Domain,
"features": parseAccountFeatures(account.FeatureFlags),
"id": account.ID,
"locale": nonEmpty(account.Locale, "en"),
"name": account.Name,
"support_email": nil,
"status": nonEmpty(account.Status, "active"),
"cache_keys": map[string]string{"label": "0000000000", "inbox": "0000000000", "team": "0000000000"},
"custom_attributes": customAttributes,
}
}
func serializeAccountCustomAttributes(account *model.Account) map[string]any {
attrs := account.CustomAttributesMap()
out := map[string]any{
"plan_name": attrs["plan_name"],
"subscribed_quantity": attrs["subscribed_quantity"],
"subscription_status": attrs["subscription_status"],
"subscription_ends_on": attrs["subscription_ends_on"],
}
copyPresentAttribute(out, attrs, "website")
copyPresentAttribute(out, attrs, "industry")
copyPresentAttribute(out, attrs, "company_size")
copyPresentAttribute(out, attrs, "timezone")
copyPresentAttribute(out, attrs, "logo")
copyPresentAttribute(out, attrs, "referral_source")
copyPresentAttribute(out, attrs, "brand_info")
if account.OnboardingStep != "" {
out["onboarding_step"] = account.OnboardingStep
} else if isPresent(attrs["onboarding_step"]) {
out["onboarding_step"] = attrs["onboarding_step"]
}
copyPresentAttribute(out, attrs, "marked_for_deletion_at")
copyPresentAttribute(out, attrs, "marked_for_deletion_reason")
if _, ok := out["timezone"]; !ok && account.Timezone != "" {
out["timezone"] = account.Timezone
}
return out
}
func copyPresentAttribute(out map[string]any, attrs map[string]any, key string) {
if value, ok := attrs[key]; ok && isPresent(value) {
out[key] = value
}
}
func isPresent(value any) bool {
if value == nil {
return false
}
if s, ok := value.(string); ok {
return s != ""
}
return true
}
func serializeAccountSettings(account *model.Account) map[string]any {
settings := map[string]any{
"auto_resolve_after": account.AutoResolveDuration,
@@ -83,6 +83,7 @@ func (s *AccountHandlerTestSuite) SetupSuite() {
accountsGroup.GET("/:account_id", s.handler.Get)
accountsGroup.POST("", s.handler.Create)
accountsGroup.PUT("/:account_id", s.handler.Update)
accountsGroup.PATCH("/:account_id/onboarding", s.handler.UpdateOnboarding)
accountsGroup.DELETE("/:account_id", s.handler.Delete)
accountsGroup.PUT("/:account_id/settings", s.handler.UpdateSettings)
accountsGroup.GET("/:account_id/agents", s.handler.GetAgents)
@@ -272,6 +273,73 @@ func (s *AccountHandlerTestSuite) TestUpdate_Success() {
assert.Equal(s.T(), "After Update", resp["name"])
}
func (s *AccountHandlerTestSuite) TestUpdateOnboarding_FinalizesAccountDetails() {
acc := &model.Account{Name: "Before Onboarding", Active: true, Status: "active", OnboardingStep: "account_details"}
s.Require().NoError(acc.SetCustomAttributesMap(map[string]any{
"onboarding_step": "account_details",
"brand_info": map[string]any{"brand_name": "Before"},
}))
s.Require().NoError(s.db.Create(acc).Error)
body := `{"name":"After Onboarding","locale":"pt","website":"https://acme.test","industry":"software","company_size":"51-200","timezone":"Asia/Shanghai","referral_source":"friend","user_role":"founder"}`
w := httptest.NewRecorder()
req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/onboarding", acc.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
s.router.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
resp := s.unmarshalResponse(w)
assert.NotContains(s.T(), resp, "success")
assert.Equal(s.T(), "After Onboarding", resp["name"])
assert.Equal(s.T(), "pt", resp["locale"])
customAttrs := resp["custom_attributes"].(map[string]interface{})
assert.Equal(s.T(), "https://acme.test", customAttrs["website"])
assert.Equal(s.T(), "software", customAttrs["industry"])
assert.Equal(s.T(), "51-200", customAttrs["company_size"])
assert.Equal(s.T(), "Asia/Shanghai", customAttrs["timezone"])
assert.Equal(s.T(), "friend", customAttrs["referral_source"])
assert.Contains(s.T(), customAttrs, "brand_info")
assert.NotContains(s.T(), customAttrs, "onboarding_step")
assert.NotContains(s.T(), customAttrs, "user_role")
var stored model.Account
require.NoError(s.T(), s.db.First(&stored, acc.ID).Error)
assert.Empty(s.T(), stored.OnboardingStep)
storedAttrs := stored.CustomAttributesMap()
assert.NotContains(s.T(), storedAttrs, "onboarding_step")
assert.Equal(s.T(), "founder", storedAttrs["user_role"])
assert.Equal(s.T(), "Asia/Shanghai", stored.Timezone)
}
func (s *AccountHandlerTestSuite) TestUpdateOnboarding_PreservesNonFinalizingAttributes() {
acc := &model.Account{Name: "Onboarding Merge", Active: true, Status: "active"}
s.Require().NoError(acc.SetCustomAttributesMap(map[string]any{
"onboarding_step": "invite_team",
"logo": "logo-id",
}))
s.Require().NoError(s.db.Create(acc).Error)
body := `{"industry":"healthcare"}`
w := httptest.NewRecorder()
req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/onboarding", acc.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
s.router.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
resp := s.unmarshalResponse(w)
customAttrs := resp["custom_attributes"].(map[string]interface{})
assert.Equal(s.T(), "invite_team", customAttrs["onboarding_step"])
assert.Equal(s.T(), "logo-id", customAttrs["logo"])
assert.Equal(s.T(), "healthcare", customAttrs["industry"])
var stored model.Account
require.NoError(s.T(), s.db.First(&stored, acc.ID).Error)
storedAttrs := stored.CustomAttributesMap()
assert.Equal(s.T(), "invite_team", storedAttrs["onboarding_step"])
assert.Equal(s.T(), "logo-id", storedAttrs["logo"])
assert.Equal(s.T(), "healthcare", storedAttrs["industry"])
}
// ====== Delete Account ======
func (s *AccountHandlerTestSuite) TestDelete_Success() {
+26 -1
View File
@@ -1,6 +1,10 @@
package model
import "gorm.io/datatypes"
import (
"encoding/json"
"gorm.io/datatypes"
)
// Account represents a tenant/organization in the system.
type Account struct {
@@ -12,6 +16,7 @@ type Account struct {
Active bool `gorm:"default:true" json:"active"`
Status string `gorm:"size:50;default:active" json:"status"`
OnboardingStep string `gorm:"size:100" json:"onboarding_step,omitempty"`
CustomAttributes datatypes.JSON `gorm:"type:jsonb;default:'{}'" json:"custom_attributes,omitempty"`
FeatureFlags string `gorm:"type:text" json:"feature_flags,omitempty"` // JSON-encoded feature flags
AutoResolveDuration int `gorm:"default:0" json:"auto_resolve_duration,omitempty"` // days
AgentLimit int `gorm:"default:0" json:"agent_limit,omitempty"` // max agents allowed (0 = unlimited), Chatwoot usage_limits[:agents]
@@ -21,3 +26,23 @@ type Account struct {
}
func (Account) TableName() string { return "accounts" }
func (a *Account) CustomAttributesMap() map[string]any {
attrs := map[string]any{}
if len(a.CustomAttributes) > 0 {
_ = json.Unmarshal(a.CustomAttributes, &attrs)
}
return attrs
}
func (a *Account) SetCustomAttributesMap(attrs map[string]any) error {
if attrs == nil {
attrs = map[string]any{}
}
encoded, err := json.Marshal(attrs)
if err != nil {
return err
}
a.CustomAttributes = datatypes.JSON(encoded)
return nil
}
+2
View File
@@ -638,6 +638,8 @@ func registerV1Routes(g *gin.RouterGroup, h *Handlers) {
accounts.GET("/:account_id", h.Account.Get)
accounts.PUT("/:account_id", h.Account.Update)
accounts.DELETE("/:account_id", h.Account.Delete)
// Account onboarding update (ref: Chatwoot resource :onboarding, only: [:update])
accounts.PATCH("/:account_id/onboarding", middleware.RoleCheck("administrator"), h.Account.UpdateOnboarding)
// Account settings (ref: Chatwoot accounts#update settings subset)
accounts.PUT("/:account_id/settings", h.Account.UpdateSettings)
+58
View File
@@ -89,6 +89,19 @@ type UpdateAccountRequest struct {
AutoResolveLabel string `json:"auto_resolve_label,omitempty"`
}
// UpdateAccountOnboardingRequest matches Chatwoot's account onboarding payload.
// Reference: Api::V1::Accounts::OnboardingsController#update.
type UpdateAccountOnboardingRequest struct {
Name *string `json:"name,omitempty"`
Locale *string `json:"locale,omitempty"`
Industry *string `json:"industry,omitempty"`
CompanySize *string `json:"company_size,omitempty"`
Timezone *string `json:"timezone,omitempty"`
ReferralSource *string `json:"referral_source,omitempty"`
UserRole *string `json:"user_role,omitempty"`
Website *string `json:"website,omitempty"`
}
// Update modifies an existing account.
func (s *AccountService) Update(ctx context.Context, id uint, req UpdateAccountRequest) (*model.Account, error) {
if err := pkgvalidator.ValidateStruct(req); err != nil {
@@ -127,6 +140,51 @@ func (s *AccountService) Update(ctx context.Context, id uint, req UpdateAccountR
return account, nil
}
// UpdateOnboarding updates account details and onboarding custom attributes.
func (s *AccountService) UpdateOnboarding(ctx context.Context, id uint, req UpdateAccountOnboardingRequest) (*model.Account, error) {
account, err := s.repo.FindByID(ctx, id)
if err != nil {
return nil, err
}
attrs := account.CustomAttributesMap()
finalize := attrs["onboarding_step"] == "account_details" || account.OnboardingStep == "account_details"
if req.Name != nil {
account.Name = *req.Name
}
if req.Locale != nil {
account.Locale = *req.Locale
}
mergeStringAttribute(attrs, "industry", req.Industry)
mergeStringAttribute(attrs, "company_size", req.CompanySize)
mergeStringAttribute(attrs, "timezone", req.Timezone)
mergeStringAttribute(attrs, "referral_source", req.ReferralSource)
mergeStringAttribute(attrs, "user_role", req.UserRole)
mergeStringAttribute(attrs, "website", req.Website)
if req.Timezone != nil {
account.Timezone = *req.Timezone
}
if finalize {
delete(attrs, "onboarding_step")
account.OnboardingStep = ""
}
if err := account.SetCustomAttributesMap(attrs); err != nil {
return nil, err
}
if err := s.repo.Update(ctx, account); err != nil {
return nil, err
}
return account, nil
}
func mergeStringAttribute(attrs map[string]any, key string, value *string) {
if value != nil {
attrs[key] = *value
}
}
// Delete soft-deletes an account.
func (s *AccountService) Delete(ctx context.Context, id uint) error {
if s.repo == nil {
@@ -0,0 +1 @@
ALTER TABLE accounts DROP COLUMN IF EXISTS custom_attributes;
@@ -0,0 +1 @@
ALTER TABLE accounts ADD COLUMN IF NOT EXISTS custom_attributes JSONB NOT NULL DEFAULT '{}';