feat(inboxes): enforce chatwoot inbox limits

This commit is contained in:
2026-06-05 11:35:38 +08:00
parent ec94fb1ab2
commit 4ddfaed845
20 changed files with 425 additions and 138 deletions
+34 -21
View File
@@ -16,9 +16,9 @@ Build GoChat as a Go backend that can directly reuse the frontend from `referenc
## Current Baseline
- Latest implementation checkpoint: `feat(custom-roles): align chatwoot permissions`.
- Latest documentation checkpoint: this checkpoint, recorded with the B10.4 account inbox-limit handoff contract.
- Worktree status at this implementation checkpoint: B10.3 aligns CustomRole API payloads, Chatwoot permission arrays, AccountUser custom-role resolution, delete nullification, and admin gates; next active slice is B10.4 InboxLimit/account-limit create-path enforcement.
- Latest implementation checkpoint: `feat(inboxes): enforce chatwoot inbox limits`.
- Latest documentation checkpoint: this checkpoint, recorded with the B10.4 account inbox-limit implementation.
- Worktree status at this implementation checkpoint: B10.4 enforces Chatwoot account-level `usage_limits[:inboxes]` during generic inbox and dedicated channel creation; next active slice is B11 Captain/Copilot persistence and feature gates.
- `go test ./...` passes.
- Route dump succeeds with `TOTAL: 830` after adding the Chatwoot-compatible applied-SLA index route.
- Route parity artifacts now exist under `docs/parity/` and are generated by `cmd/route_parity`.
@@ -44,9 +44,8 @@ Next ordered checkpoints:
| Order | Slice | Required outcome | Primary verification |
| --- | --- | --- | --- |
| 1 | B10.4 | Remaining InboxLimit/account-limit create-path behavior is aligned. | Inbox/channel create tests for over-limit behavior and frontend-readable errors. |
| 2 | B11 | Captain/Copilot enterprise screens have real persistence and safe LLM feature gates. | Captain/Copilot handler/service fixtures and disabled-state tests. |
| 3 | B12 | Reused Chatwoot frontend smoke runs repeatably against GoChat. | Checked smoke command plus gap report under `docs/parity/`. |
| 1 | B11 | Captain/Copilot enterprise screens have real persistence and safe LLM feature gates. | Captain/Copilot handler/service fixtures and disabled-state tests. |
| 2 | B12 | Reused Chatwoot frontend smoke runs repeatably against GoChat. | Checked smoke command plus gap report under `docs/parity/`. |
## Execution Snapshot
@@ -56,7 +55,7 @@ Next ordered checkpoints:
| Phase 1 | Meilisearch search engine | Review | B6 payload parity, optional live gate, and DB-fallback hardening are implemented; an actual live Meilisearch run is optional and environment-dependent |
| Phase 2 | Route and controller parity audit | Doing | Ruby/Bundler unavailable, so Chatwoot route extraction currently uses static `routes.rb` fallback |
| Phase 3 | Data and serializer parity | Doing | JSON fixture coverage is partial and still endpoint-family based |
| Phase 4 | Enterprise feature completion | Doing | B7, B8, B9, and B10.1-B10.3 are in Review; B10.4 remaining limits is the next active slice |
| Phase 4 | Enterprise feature completion | Doing | B7, B8, B9, and B10 are in Review; B11 Captain/Copilot is the next active enterprise slice |
| Phase 5 | Background jobs and integrations | Planned | durable worker choice and job parity are open |
| Phase 6 | Core placeholder burn-down | Doing | account/contact/conversation/message/inbox placeholder groups remain broad |
| Phase 7 | Verification harness | Planned | search live gate and reused-frontend smoke harness are not complete |
@@ -146,12 +145,13 @@ This ledger records the committed parity checkpoints that future slices should b
| `docs: land remaining parity tracker` | Converted the immediate remaining plan into executable tracking contracts: B10.3 now lists CustomRole reference files, permission-array migration, AccountUser role resolution, delete nullification, admin gates, and test exits; B10.4 records InboxLimit create-path enforcement; B11/B12 now have route/persistence/feature-gate and smoke-report landing rules. | Documentation-only checkpoint; `git diff --check` passed. | Start B10.3 implementation from the recorded CustomRole contract. |
| `feat(custom-roles): align chatwoot permissions` | Completed B10.3 CustomRole parity: custom roles now accept and serialize Chatwoot permission arrays, raw list/show/create/update/delete payloads match the enterprise Jbuilder views, admin gates are enforced, `AccountUser.role` stays `agent` while `custom_role_id` drives custom permissions, profile account payloads include `custom_role_id/custom_role/permissions`, and delete clears related account users. | `go test ./internal/handler/api/v1 -run CustomRole -count=1`; `go test ./internal/service -run 'CustomRole\|RBAC' -count=1`; `go test ./internal/model -run 'CustomRole\|AccountUser' -count=1`; `go test ./internal/middleware -run AccountScope -count=1`; handler/service/model packages passed; full verification recorded below. No route changes; route dump remains `TOTAL: 830`. | Continue B10.4 remaining InboxLimit/account-limit create-path enforcement. |
| `docs: land inbox limit handoff tracker` | Landed the B10.4 reference findings and implementation contract: Chatwoot account inbox limits come from `Current.account.usage_limits[:inboxes]`, over-limit create returns `402 { error: "Account limit exceeded. Upgrade to a higher plan" }`, and capacity-policy `InboxCapacityLimit` is explicitly separate assignment-capacity data. | Documentation-only checkpoint; `git diff --check` passed. | Start B10.4 implementation from the recorded guard, migration, handler, and test plan. |
| `feat(inboxes): enforce chatwoot inbox limits` | Completed B10.4 account-level inbox limit parity: `accounts.inbox_limit` now represents Chatwoot `usage_limits[:inboxes]`, `InboxService.EnsureCanCreateInbox` blocks over-limit creates before persistence, generic inbox and dedicated channel create paths return `402 { error: "Account limit exceeded. Upgrade to a higher plan" }`, and LINE/email/Twilio plus other channel handlers avoid orphan channel rows. | `go test ./internal/handler/api/v1 -run 'Inbox\|Channel\|Capacity\|Limit' -count=1`; `go test ./internal/service -run 'Inbox\|Channel\|Capacity\|Limit' -count=1`; handler and service packages passed; full verification recorded below. No route changes; route dump remains `TOTAL: 830`. | Continue B11 Captain/Copilot persistence, safe disabled states, and frontend payload parity. |
## Next Slice Contract
Completed implementation slice: B10.3 now aligns CustomRole permission arrays, serializers, account-user role resolution, delete nullification, and admin access.
Completed implementation slice: B10.4 now enforces account-level inbox create limits and frontend-readable over-limit errors.
Next implementation slice: continue B10.4 remaining InboxLimit create-path enforcement. B9.3 delayed/durable worker scheduling and B9.4 macro attachment depth remain named Phase 5 follow-ups.
Next implementation slice: start B11 Captain/Copilot persistence, safe LLM feature gates, and frontend payload parity. B9.3 delayed/durable worker scheduling and B9.4 macro attachment depth remain named Phase 5 follow-ups.
| Step | Required result | Reference source | Verification |
| --- | --- | --- | --- |
@@ -398,7 +398,7 @@ Upcoming enterprise task boards:
| B10 | B10.1 | Align audit log serializer, filters, pagination, actor/request metadata, and admin route behavior. | Chatwoot enterprise audit controllers/models. | Audit list tests plus representative mutation writer tests. | Done by `feat(audit): align chatwoot audit log payloads`; writer coverage continues in B10.2 |
| B10 | B10.2 | Add audit writer coverage for representative core and enterprise mutations: inbox, conversation assignment/status, SLA policy, capacity policy, custom role, automation, macro, CSAT review notes. | Chatwoot audit hooks and current Go service mutation points. | Mutation tests assert audit rows with actor, auditable type/id, account, IP/request metadata where available. | Done by `feat(audit): record enterprise mutations` and `feat(audit): cover operational mutations` |
| B10 | B10.3 | Align CustomRole permission keys, account-user role resolution, deletion nullification, and authorization failure payloads. | Chatwoot custom role controllers/policies and permission constants. | Permission matrix tests for admin/non-admin/custom-role access. | Done by `feat(custom-roles): align chatwoot permissions` |
| B10 | B10.4 | Review remaining InboxLimit/account-limit create-path enforcement outside capacity policies. | Chatwoot enterprise account/inbox limit policies. | Inbox/channel create tests for over-limit behavior and frontend-readable errors. | Todo |
| B10 | B10.4 | Review remaining InboxLimit/account-limit create-path enforcement outside capacity policies. | Chatwoot enterprise account/inbox limit policies. | Inbox/channel create tests for over-limit behavior and frontend-readable errors. | Done by `feat(inboxes): enforce chatwoot inbox limits` |
| B11 | B11.1 | Align Captain assistant CRUD, inbox bindings, responses, documents, scenarios, and custom tools payloads. | Captain controllers/services/frontend clients under `reference/chatwoot`. | Handler/service fixtures for every Captain dashboard client path. | Todo |
| B11 | B11.2 | Align Copilot threads, messages, tasks, preferences, playground/tool-call behavior, and disabled-state feature gates. | Copilot controllers/services/frontend clients under `reference/chatwoot`. | Copilot handler/service tests for persistence, disabled LLM state, and frontend payloads. | Todo |
| B11 | B11.3 | Add document sync/embedding/LLM job boundaries where external dependencies are required. | Captain/Copilot jobs and document services. | Worker tests or explicit feature-gated fallback tests. | Todo |
@@ -615,7 +615,7 @@ B10 admin and limits breakdown:
| B10.1 | Align audit list filters, serializer fields, and pagination before broadening writers. | Chatwoot enterprise audit controller/model. | Audit handler tests for account scope, action/auditable filters, actor metadata, and pagination. | Done by `feat(audit): align chatwoot audit log payloads` |
| B10.2 | Add audit writer coverage for representative core and enterprise mutations: inbox, conversation assignment/status, SLA policy, capacity policy, custom role, automation, macro, CSAT review notes. | Chatwoot audit hooks and current Go service mutation points. | Mutation tests assert audit rows with actor, auditable type/id, account, IP/request metadata where available. | Done by `feat(audit): record enterprise mutations` and `feat(audit): cover operational mutations` |
| B10.3 | Align custom role permission keys, serializers, delete-nullification behavior, and AccountUser permission resolution. | Chatwoot enterprise custom roles policy/model/controller. | Permission matrix tests and handler tests for admin/non-admin access. | Done by `feat(custom-roles): align chatwoot permissions` |
| B10.4 | Review legacy InboxLimit routes versus Chatwoot account-level limit behavior and enforce create limits in inbox/channel creation paths. | Chatwoot enterprise inbox limit behavior, existing capacity-limit implementation. | Inbox/channel creation tests cover under-limit and over-limit frontend-readable errors. | Todo |
| B10.4 | Review legacy InboxLimit routes versus Chatwoot account-level limit behavior and enforce create limits in inbox/channel creation paths. | Chatwoot enterprise inbox limit behavior, existing capacity-limit implementation. | Inbox/channel creation tests cover under-limit and over-limit frontend-readable errors. | Done by `feat(inboxes): enforce chatwoot inbox limits` |
B10.1 current checkpoint:
@@ -727,17 +727,29 @@ B10.4 InboxLimit landing contract:
| Area | Chatwoot reference contract | Current Go gap to close | Required landing work |
| --- | --- | --- | --- |
| Limit source of truth | `reference/chatwoot/app/controllers/api/v1/accounts/inboxes_controller.rb` calls `validate_limit` before `create`; `app/helpers/api/v1/inboxes_helper.rb` compares `Current.account.inboxes.count` with `Current.account.usage_limits[:inboxes]`; enterprise `account/plan_usage_and_limits.rb` resolves `limits['inboxes']`, `ACCOUNT_INBOXES_LIMIT`, then `ChatwootApp.max_limit`. Capacity-policy `InboxCapacityLimit` is separate assignment-capacity data. | Go has AgentCapacityPolicy/InboxCapacityLimit parity, but `model.Account` has only `AgentLimit` and create paths do not yet have an account-level inbox limit guard. | Add account-level inbox limit persistence, using local `0` as unlimited; do not reuse capacity-policy inbox limits for account create limits. |
| Generic inbox create | Over-limit create fails before persistence with HTTP `402` and body `{ "error": "Account limit exceeded. Upgrade to a higher plan" }`. | `InboxService.Create` creates generic/channel-backed inboxes without an account-limit check. | Add a shared service guard at the start of inbox creation, backed by `InboxRepo.CountByAccount`, and map the sentinel error to the exact Chatwoot `402` JSON body. |
| Dedicated channel create | Channel-specific create actions must not leave orphan channel rows when the account is already over limit. | Email/Twilio handlers roll back after service failure; LINE and other dedicated paths need pre-persistence enforcement reviewed. | Call the shared guard before channel row creation in dedicated channel handlers, then keep the service guard as a second boundary. |
| Schema and compatibility | Community Chatwoot defaults effectively allow a large maximum; enterprise can lower limits through account/global config. | Existing Go schema lacks an account inbox-limit column or JSON limits equivalent. | Add `accounts.inbox_limit` migration and `model.Account.InboxLimit`; preserve local compatibility with unlimited default. |
| Tests and docs | Under-limit and over-limit paths must be covered for generic inbox and at least one dedicated channel path, including no-persistence assertions. | No focused B10.4 tests yet. | Add service and handler tests for unlimited, under-limit, over-limit, exact error body, and no orphan channel/inbox rows; update this tracker and run full tests before commit. |
| Limit source of truth | `reference/chatwoot/app/controllers/api/v1/accounts/inboxes_controller.rb` calls `validate_limit` before `create`; `app/helpers/api/v1/inboxes_helper.rb` compares `Current.account.inboxes.count` with `Current.account.usage_limits[:inboxes]`; enterprise `account/plan_usage_and_limits.rb` resolves `limits['inboxes']`, `ACCOUNT_INBOXES_LIMIT`, then `ChatwootApp.max_limit`. Capacity-policy `InboxCapacityLimit` is separate assignment-capacity data. | B10.4 adds `model.Account.InboxLimit`; capacity-policy inbox limits remain separate. | Covered by `feat(inboxes): enforce chatwoot inbox limits`. |
| Generic inbox create | Over-limit create fails before persistence with HTTP `402` and body `{ "error": "Account limit exceeded. Upgrade to a higher plan" }`. | `InboxService.Create` now calls the account-limit guard before persistence. | Covered by service and handler tests. |
| Dedicated channel create | Channel-specific create actions must not leave orphan channel rows when the account is already over limit. | Dedicated handlers now precheck where channel rows are created first; service create methods also guard direct callers. | Covered by LINE no-orphan test plus shared error mapping/rollback paths. |
| Schema and compatibility | Community Chatwoot defaults effectively allow a large maximum; enterprise can lower limits through account/global config. | `accounts.inbox_limit` migration exists and defaults to `0` unlimited for local compatibility. | Covered by `000024_add_account_inbox_limit` and updated init schema. |
| Tests and docs | Under-limit and over-limit paths must be covered for generic inbox and at least one dedicated channel path, including no-persistence assertions. | Focused B10.4 tests are present. | Covered by inbox service tests, generic handler over-limit test, and LINE no-orphan channel test. |
B10.4 current checkpoint:
- `reference/chatwoot/app/controllers/api/v1/accounts/inboxes_controller.rb`, `app/helpers/api/v1/inboxes_helper.rb`, `app/controllers/concerns/request_exception_handler.rb`, `app/models/account.rb`, and `enterprise/app/models/enterprise/account/plan_usage_and_limits.rb` were used as the reference contract.
- `model.Account.InboxLimit` and migration `000024_add_account_inbox_limit` now represent Chatwoot `usage_limits[:inboxes]`; local `0` keeps the community/unlimited default behavior.
- `InboxService.EnsureCanCreateInbox` checks the current account and `InboxRepo.CountByAccount` before persistence; `ErrInboxLimitExceeded` carries the exact Chatwoot message `Account limit exceeded. Upgrade to a higher plan`.
- Generic inbox create maps the sentinel error to HTTP `402` with `{ "error": "Account limit exceeded. Upgrade to a higher plan" }` and does not create an inbox row.
- Dedicated channel create paths now precheck the same guard before channel persistence where handlers create channel rows first; service-level create methods keep the guard for web widget, Telegram, Instagram, Facebook, and direct service callers.
- LINE over-limit coverage proves no orphan `channel_line` row is left behind. Email, Twilio, TikTok, Twitter, Google, and Microsoft paths also roll back channel rows if the service boundary rejects after channel creation.
- Capacity-policy `InboxCapacityLimit` remains separate assignment-capacity data and is not used as the account create-limit source.
B10.4 exit commands:
```bash
env GOCACHE=/tmp/gochat-gocache GOMODCACHE=/tmp/gochat-gomodcache go test ./internal/handler/api/v1 -run 'Inbox|Channel|Capacity|Limit' -count=1
env GOCACHE=/tmp/gochat-gocache GOMODCACHE=/tmp/gochat-gomodcache go test ./internal/service -run 'Inbox|Channel|Capacity|Limit' -count=1
env GOCACHE=/tmp/gochat-gocache GOMODCACHE=/tmp/gochat-gomodcache go test ./internal/handler/api/v1 -count=1
env GOCACHE=/tmp/gochat-gocache GOMODCACHE=/tmp/gochat-gomodcache go test ./internal/service -count=1
env GOCACHE=/tmp/gochat-gocache GOMODCACHE=/tmp/gochat-gomodcache go test ./...
git diff --check
```
@@ -876,7 +888,7 @@ Work proceeds top-down unless a failing test or frontend blocker forces a narrow
| B7 | SLA and assignment capacity. | Chatwoot enterprise SLA and assignment policy behavior. | Unit/integration tests for SLA state, breach, assignment capacity, policy selection. | Review |
| B8 | CSAT account/public/send completion. | Chatwoot CSAT survey responses, reports, downloads, listeners. | Metrics/list/review/download/send idempotency tests. | Review |
| B9 | Automation/macros durable side effects. | Chatwoot automation/macro services and jobs. | Action execution, logs, webhook/email transcript retry tests. | Review |
| B10 | Audit, CustomRole, InboxLimit. | Chatwoot enterprise admin behavior and policies. | Authorization, audit emission, limits enforcement, admin payload fixtures. | Doing |
| B10 | Audit, CustomRole, InboxLimit. | Chatwoot enterprise admin behavior and policies. | Authorization, audit emission, limits enforcement, admin payload fixtures. | Review |
| B11 | Captain/Copilot deep behavior. | Chatwoot Captain/Copilot controllers, services, frontend clients. | Assistant/tool/document/scenario/copilot thread/task tests and feature gates. | Todo |
| B12 | Frontend smoke harness. | `reference/chatwoot` frontend. | Repeatable smoke command and checked gap report. | Todo |
@@ -888,7 +900,7 @@ Remaining slice landing plan:
| B7 | Done: assignment capacity enforcement, SLA policy CRUD payload parity, applied-SLA conversation persistence, idempotent SLA breach lifecycle, applied-SLA report/list payload parity, and SLA miss notification fan-out. | Capacity-aware assignment policy binding review and durable SLA job scheduling remain broader Phase 5/P4.9 follow-ups, not hidden SLA gaps. | Review after `d23f3f0`; move to Done only after assignment policy binding review is either implemented or split out of B7. |
| B8 | Done: account-side CSAT list/metrics/review-note payload parity, public submit/update idempotency, resolve-triggered generic survey message send, and CSV download filters/columns. | Channel-specific WhatsApp/Twilio template send hooks and durable queueing are tracked under Phase 5. | Review after `b36cf07`; move to Done only after channel-specific send hooks are either implemented or formally split as external integration scope. |
| B9 | Done: B9.1 automation rule CRUD/listener/log/external-action parity and B9.2 macro frontend CRUD/execute side effects. | Delayed actions, durable queued worker scheduling, and deeper macro attachment/file parity remain named B9.3/B9.4 follow-ups. | Review after `feat(macros): align chatwoot macro payloads`; move to Done only after durable worker/attachment gaps are implemented or formally split out. |
| B10 | Done: audit list payload, audit writer boundary for representative mutating core resources, CustomRole permission-key parity, AccountUser permission resolution, admin gates, and delete nullification. | InboxLimit enforcement in inbox/channel creation paths. | Done only after B10.4 create-limit tests prove over-limit behavior and frontend-readable errors match Chatwoot. |
| B10 | Done: audit list payload, audit writer boundary for representative mutating core resources, CustomRole permission-key parity, AccountUser permission resolution, admin gates, delete nullification, and account-level InboxLimit enforcement in inbox/channel creation paths. | Frontend smoke coverage for enterprise settings remains B12, not a hidden B10 blocker. | Review after B10.4; move to Done only after reused frontend smoke confirms audit/custom-role/limit settings flows or any smoke gaps are split into owned follow-ups. |
| B11 | Captain Assistant CRUD, inbox binding, responses, documents, and custom tools payload fixtures. | Copilot threads/messages/tasks, playground/tool-call behavior, document sync/embedding feature gates, streaming fallback. | Done only after LLM-dependent behavior is either implemented behind config or safely stubbed with frontend-compatible disabled states. |
| B12 | Boot reused Chatwoot frontend against GoChat auth/profile/inbox/conversation/contact flows. | Add smoke paths for widget init/message, public CSAT, reports, and enterprise screens as B7-B11 land. | Done only after the smoke command is repeatable and writes a checked gap report. |
@@ -1150,7 +1162,7 @@ Included checklist:
- [ ] Assignment policies and auto-assignment compatibility.
- [ ] Captain/Copilot assistant, custom tools, scenarios, documents, responses, and inbox bindings.
- [x] CSAT survey response flow, metrics, filters, and review notes.
- [ ] Inbox limits and account/inbox usage enforcement.
- [x] Inbox limits and account/inbox usage enforcement.
- [x] Automation rules, macros, execution logs, and action side effects.
Acceptance:
@@ -1166,7 +1178,7 @@ Enterprise tracking table:
| P4.2 | Audit logs | `internal/model/audit.go`, `internal/service/audit_service.go`, `internal/repository/audit_repo.go`, `internal/handler/api/v1/audit_handler.go` | Audit list payload, admin access, associated-account scoping, fixed pagination, shared audit writer boundary, and named representative writer coverage are implemented; deeper resource-specific `auditable.push_event_data` remains future serializer depth if frontend requires it. | Review |
| P4.3 | Custom roles/permissions | `internal/model/custom_role.go`, `internal/service/custom_role_service.go`, `internal/middleware/role_check.go`, `internal/handler/api/v1/custom_role_handler.go` | Permission arrays, raw admin payloads, administrator gates, account-user resolution, profile permissions, and delete nullification are implemented; keep in Review until frontend smoke covers enterprise settings. | Review |
| P4.4 | Agent capacity | `internal/model/agent_capacity_policy.go`, `internal/service/agent_capacity_policy_service.go`, `internal/handler/api/v1/agent_capacity_handler.go`, `internal/autoassignment/*` | First align AgentCapacityPolicy API, serializers, nested users, and `InboxCapacityLimit` data contracts; then enforce capacity in manual/auto assignment. | Review |
| P4.5 | Inbox limits | `internal/model/agent_capacity_policy.go` `InboxCapacityLimit`, plus legacy `internal/model/inbox_limit.go`, `internal/service/inbox_limit_service.go`, `internal/repository/inbox_limit_repo.go`, `internal/handler/api/v1/inbox_limit_handler.go` | Chatwoot enterprise nested `agent_capacity_policies/:policy_id/inbox_limits` and assignment-path enforcement are covered; B10.4 now owns account-level `usage_limits[:inboxes]` create-path enforcement. | Doing |
| P4.5 | Inbox limits | `internal/model/agent_capacity_policy.go` `InboxCapacityLimit`, plus legacy `internal/model/inbox_limit.go`, `internal/service/inbox_limit_service.go`, `internal/repository/inbox_limit_repo.go`, `internal/handler/api/v1/inbox_limit_handler.go` | Chatwoot enterprise nested `agent_capacity_policies/:policy_id/inbox_limits`, assignment-path enforcement, and account-level `usage_limits[:inboxes]` create-path enforcement are covered. | Review |
| P4.6 | Captain/Copilot | `internal/model/captain_models.go`, `internal/model/copilot_models.go`, `internal/service/captain_*`, `internal/service/copilot_*`, `internal/handler/api/v1/captain_*`, `internal/handler/api/v1/copilot_handler.go` | Complete assistant, tools, scenarios, documents, responses, inbox bindings, suggestions, and streaming compatibility. | Todo |
| P4.7 | CSAT | `internal/csat/*`, `internal/automation/csat_survey_*`, `internal/handler/api/v1/csat_*`, `internal/service/csat_metrics_service.go` | Account-side list/metrics/review-note payloads, public update depth, resolve-triggered generic survey send, and download CSV are aligned; channel-specific template send hooks remain Phase 5 integration work. | Review |
| P4.8 | Automation and macros | `internal/automation/*`, `internal/handler/api/v1/automation_rule_handler.go`, `internal/handler/api/v1/macro_handler.go` | Automation-rule CRUD/listener/log/external-action delivery and macro CRUD/display-ID execution parity are implemented; durable delayed actions and deeper macro attachment/file parity remain B9.3/B9.4 follow-ups. | Review |
@@ -1183,7 +1195,7 @@ Enterprise work package breakdown:
| Macros | Macro CRUD, availability by account/user, execute side effects, validation, audit/log output. | CRUD payloads, visibility/authorization, display-ID execution, labels/status/messages/private notes, and empty execute/delete responses are covered by `feat(macros): align chatwoot macro payloads`; deeper attachment files and durable queue remain follow-ups. | Review |
| Audit | Audit model parity, mutating action coverage, request metadata, filters/pagination, admin endpoint payloads. | List/admin payload parity is covered by `feat(audit): align chatwoot audit log payloads`; named representative writer coverage is covered by `feat(audit): record enterprise mutations` and `feat(audit): cover operational mutations`. | Review |
| Custom roles | Permission-key parity, account-user role resolution, policy middleware, create/update/delete behavior. | Permission arrays, raw admin payloads, admin gates, RBAC/account-scope/profile resolution, and delete nullification are covered by `feat(custom-roles): align chatwoot permissions`. | Review |
| Inbox limits | Account/inbox limit models, create/update enforcement, UI-readable limit responses, admin overrides. | Chatwoot nested capacity-limit API and assignment-path enforcement are covered; B10.4 account-level create limits are the active implementation slice. | Doing |
| Inbox limits | Account/inbox limit models, create/update enforcement, UI-readable limit responses, admin overrides. | Chatwoot nested capacity-limit API, assignment-path enforcement, and account-level create-limit `402` behavior are covered by B5/B7/B10.4. | Review |
| Captain/Copilot | Assistants, inbox bindings, scenarios, responses, documents, tools, copilot threads/messages, tasks, streaming/tool-call behavior. | Route fixtures, persistence tests, feature gates for external LLM dependencies, frontend smoke screens. | Todo |
Enterprise acceptance gates:
@@ -1418,3 +1430,4 @@ Verification milestone gates:
- 2026-06-05: Remaining parity tracker checkpoint prepared as `docs: land remaining parity tracker`; the document now carries executable landing contracts for B10.3 CustomRole permission arrays/account-user resolution/delete nullification, B10.4 account/inbox limit create-path enforcement, B11 Captain/Copilot persistence and feature gates, and B12 reused Chatwoot frontend smoke reporting. Documentation-only checkpoint; `git diff --check` passed.
- 2026-06-05: B10.3 CustomRole checkpoint prepared as `feat(custom-roles): align chatwoot permissions`; custom roles now accept/serialize Chatwoot permission arrays, return raw enterprise Jbuilder payloads, enforce administrator-only access, keep custom-role account users as `role=agent` with `custom_role_id`, load custom-role permissions through RBAC/AccountScope, expose profile account `custom_role_id/custom_role/permissions`, and nullify account users on role delete. Focused CustomRole/RBAC/model/AccountScope tests, handler/service/model package tests, and full verification were run before commit; sandboxed middleware package tests still require socket-capable execution for miniredis. Next slice is B10.4 InboxLimit create-path enforcement.
- 2026-06-05: B10.4 handoff tracker prepared as `docs: land inbox limit handoff tracker`; the active plan now records the exact Chatwoot account inbox-limit source (`usage_limits[:inboxes]`), the `402 { error: "Account limit exceeded. Upgrade to a higher plan" }` response contract, the separation from capacity-policy `InboxCapacityLimit`, the required account schema guard, dedicated-channel precheck, no-orphan persistence tests, and updated enterprise status rows. Documentation-only checkpoint; `git diff --check` passed.
- 2026-06-05: B10.4 InboxLimit checkpoint prepared as `feat(inboxes): enforce chatwoot inbox limits`; account-level `inbox_limit` now gates generic inbox and dedicated channel creation with Chatwoot's exact `402` error body, service and handler tests cover unlimited, below-limit, over-limit, and no-orphan LINE channel behavior, and B10 moves to Review. Focused inbox/channel/limit tests, handler/service package tests, escalated full `go test ./...`, and `git diff --check` passed. Next slice is B11 Captain/Copilot.
@@ -84,6 +84,13 @@ func (h *EmailChannelHandler) Create(c *gin.Context) {
}
ctx := c.Request.Context()
if err := h.inboxSvc.EnsureCanCreateInbox(ctx, accountID); err != nil {
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create inbox"})
return
}
// Create the channel record first (without InboxID)
ch := &channelmodel.ChannelEmail{
@@ -136,6 +143,9 @@ func (h *EmailChannelHandler) Create(c *gin.Context) {
if delErr := h.emailChannelSvc.Delete(ctx, ch.ID); delErr != nil {
applogger.L().Warnf("Failed to rollback Email channel after inbox creation failure: %v", delErr)
}
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create inbox"})
return
}
@@ -176,17 +176,20 @@ func (h *FacebookChannelHandler) CreateFacebookPage(c *gin.Context) {
inbox, err := h.inboxSvc.CreateFacebookInbox(ctx, uint(accountID), inboxReq, h.fbRepo)
if err != nil {
applogger.L().Errorf("Failed to create Facebook inbox: %v", err)
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create Facebook inbox", "details": err.Error()})
return
}
c.JSON(http.StatusCreated, gin.H{
"inbox": gin.H{
"id": inbox.ID,
"name": inbox.Name,
"channel_type": inbox.ChannelType,
"channel_id": inbox.ChannelID,
"enabled": inbox.Enabled,
"id": inbox.ID,
"name": inbox.Name,
"channel_type": inbox.ChannelType,
"channel_id": inbox.ChannelID,
"enabled": inbox.Enabled,
"enable_auto_assignment": inbox.EnableAutoAssignment,
},
})
@@ -225,12 +228,12 @@ func (h *FacebookChannelHandler) GetFacebookChannel(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{
"id": ch.ID,
"account_id": ch.AccountID,
"inbox_id": ch.InboxID,
"page_id": ch.PageID,
"page_name": ch.PageName,
"app_id": ch.AppID,
"id": ch.ID,
"account_id": ch.AccountID,
"inbox_id": ch.InboxID,
"page_id": ch.PageID,
"page_name": ch.PageName,
"app_id": ch.AppID,
"reauthorization_required": ch.ReauthorizationRequired,
})
}
@@ -257,12 +260,12 @@ func (h *FacebookChannelHandler) ListFacebookChannels(c *gin.Context) {
result := make([]gin.H, 0, len(channels))
for _, ch := range channels {
result = append(result, gin.H{
"id": ch.ID,
"account_id": ch.AccountID,
"inbox_id": ch.InboxID,
"page_id": ch.PageID,
"page_name": ch.PageName,
"app_id": ch.AppID,
"id": ch.ID,
"account_id": ch.AccountID,
"inbox_id": ch.InboxID,
"page_id": ch.PageID,
"page_name": ch.PageName,
"app_id": ch.AppID,
"reauthorization_required": ch.ReauthorizationRequired,
})
}
@@ -405,8 +408,8 @@ func (h *FacebookChannelHandler) UpdateFacebookPage(c *gin.Context) {
}
var req struct {
PageName *string `json:"page_name"`
ReauthorizationRequired *bool `json:"reauthorization_required"`
PageName *string `json:"page_name"`
ReauthorizationRequired *bool `json:"reauthorization_required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body", "details": err.Error()})
@@ -414,7 +417,7 @@ func (h *FacebookChannelHandler) UpdateFacebookPage(c *gin.Context) {
}
updateReq := service.UpdateFacebookChannelRequest{
PageName: req.PageName,
PageName: req.PageName,
ReauthorizationRequired: req.ReauthorizationRequired,
}
@@ -426,12 +429,11 @@ func (h *FacebookChannelHandler) UpdateFacebookPage(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{
"id": updated.ID,
"account_id": updated.AccountID,
"inbox_id": updated.InboxID,
"page_id": updated.PageID,
"page_name": updated.PageName,
"id": updated.ID,
"account_id": updated.AccountID,
"inbox_id": updated.InboxID,
"page_id": updated.PageID,
"page_name": updated.PageName,
"reauthorization_required": updated.ReauthorizationRequired,
})
}
@@ -107,6 +107,13 @@ func (h *GoogleChannelHandler) OAuthCallback(c *gin.Context) {
}
ctx := c.Request.Context()
if err := h.inboxSvc.EnsureCanCreateInbox(ctx, uint(accountID)); err != nil {
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create google inbox"})
return
}
// Exchange the code for tokens
tokenResult, err := h.goProvider.ExchangeToken(ctx, req.Code, req.RedirectURL)
@@ -146,6 +153,12 @@ func (h *GoogleChannelHandler) OAuthCallback(c *gin.Context) {
inbox, err := h.inboxSvc.Create(ctx, uint(accountID), inboxReq)
if err != nil {
applogger.L().Errorf("Failed to create Google inbox: %v", err)
if delErr := h.goService.Delete(ctx, goChannel.ID); delErr != nil {
applogger.L().Warnf("Failed to rollback Google channel after inbox creation failure: %v", delErr)
}
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create google inbox"})
return
}
+11
View File
@@ -134,6 +134,9 @@ func (h *InboxHandler) Create(c *gin.Context) {
inbox, svcErr := h.svc.Create(c.Request.Context(), accountID, req)
if svcErr != nil {
if renderInboxLimitExceeded(c, svcErr) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create inbox"})
return
}
@@ -239,6 +242,14 @@ func (h *InboxHandler) Delete(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Your inbox deletion request will be processed in some time."})
}
func renderInboxLimitExceeded(c *gin.Context, err error) bool {
if !service.IsInboxLimitExceeded(err) {
return false
}
c.JSON(http.StatusPaymentRequired, gin.H{"error": service.InboxLimitExceededMessage})
return true
}
func bindCreateInboxRequest(c *gin.Context, req *service.CreateInboxRequest) error {
if strings.Contains(c.ContentType(), "json") {
return bindCreateInboxJSON(c, req)
@@ -243,6 +243,40 @@ func TestInboxHandler_ChatwootCreateUpdateRequestBinding(t *testing.T) {
require.Len(t, inboxParityObject(t, showUpdated)["working_hours"].([]any), 7)
}
func TestInboxHandler_ChatwootCreateRejectsAccountInboxLimit(t *testing.T) {
gin.SetMode(gin.TestMode)
db, err := gorm.Open(sqlite.Open("file:inbox_handler_limit?mode=memory&cache=shared"), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
require.NoError(t, err)
t.Cleanup(func() {
sqlDB, dbErr := db.DB()
if dbErr == nil {
_ = sqlDB.Close()
}
})
require.NoError(t, db.AutoMigrate(&model.Account{}, &model.Inbox{}, &model.WorkingHour{}))
account := &model.Account{Name: "Inbox Limit", Locale: "en", Active: true, InboxLimit: 1}
require.NoError(t, db.Create(account).Error)
require.NoError(t, db.Create(&model.Inbox{AccountID: account.ID, Name: "Existing", ChannelType: "api"}).Error)
router := setupInboxParityRouter(db)
response := inboxParityRequest(t, router, http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/inboxes/", account.ID), map[string]any{
"name": "Blocked API",
"channel": map[string]any{
"type": "api",
},
})
require.Equal(t, http.StatusPaymentRequired, response.Code, response.Body.String())
require.Equal(t, service.InboxLimitExceededMessage, inboxParityObject(t, response)["error"])
var count int64
require.NoError(t, db.Model(&model.Inbox{}).Where("account_id = ?", account.ID).Count(&count).Error)
require.Equal(t, int64(1), count)
}
func TestInboxHandler_ChatwootChannelSpecificConfigDepth(t *testing.T) {
gin.SetMode(gin.TestMode)
@@ -35,10 +35,10 @@ import (
// InstagramChannelHandler handles Instagram DM channel management.
type InstagramChannelHandler struct {
igService *service.ChannelInstagramService
igProvider *facebookchannel.InstagramProvider
inboxSvc *service.InboxService
igRepo *repository.ChannelInstagramRepo
igService *service.ChannelInstagramService
igProvider *facebookchannel.InstagramProvider
inboxSvc *service.InboxService
igRepo *repository.ChannelInstagramRepo
}
// NewInstagramChannelHandler creates a new Instagram channel handler.
@@ -203,13 +203,13 @@ func (h *InstagramChannelHandler) OAuthCallbackGET(c *gin.Context) {
// After OAuth, the frontend calls this endpoint with the page_access_token and
// IG account details to create the inbox and link the channel.
type CreateInstagramChannelRequest struct {
Name string `json:"name" validate:"required,min=2"`
InstagramAccountID string `json:"instagram_account_id" validate:"required"`
PageAccessToken string `json:"page_access_token" validate:"required"`
ConnectedFBPageID string `json:"connected_fb_page_id" validate:"required"`
Name string `json:"name" validate:"required,min=2"`
InstagramAccountID string `json:"instagram_account_id" validate:"required"`
PageAccessToken string `json:"page_access_token" validate:"required"`
ConnectedFBPageID string `json:"connected_fb_page_id" validate:"required"`
InstagramBusinessAccountID string `json:"instagram_business_account_id,omitempty"`
InstagramAccountName string `json:"instagram_account_name,omitempty"`
EnableAutoAssignment bool `json:"enable_auto_assignment,omitempty"`
InstagramAccountName string `json:"instagram_account_name,omitempty"`
EnableAutoAssignment bool `json:"enable_auto_assignment,omitempty"`
}
// === Webhook Registration (G10) ===
@@ -307,18 +307,21 @@ func (h *InstagramChannelHandler) CreateInstagramChannel(c *gin.Context) {
// Delegate to InboxService.CreateInstagramInbox (which creates both Inbox + ChannelInstagram)
inboxReq := service.CreateInstagramInboxRequest{
Name: req.Name,
InstagramAccountID: req.InstagramAccountID,
PageAccessToken: req.PageAccessToken,
ConnectedFBPageID: req.ConnectedFBPageID,
Name: req.Name,
InstagramAccountID: req.InstagramAccountID,
PageAccessToken: req.PageAccessToken,
ConnectedFBPageID: req.ConnectedFBPageID,
InstagramBusinessAccountID: req.InstagramBusinessAccountID,
InstagramAccountName: req.InstagramAccountName,
EnableAutoAssignment: req.EnableAutoAssignment,
InstagramAccountName: req.InstagramAccountName,
EnableAutoAssignment: req.EnableAutoAssignment,
}
inbox, err := h.inboxSvc.CreateInstagramInbox(ctx, uint(accountID), inboxReq, h.igRepo)
if err != nil {
applogger.L().Errorf("Failed to create Instagram inbox: %v", err)
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create instagram channel"})
return
}
@@ -330,11 +333,11 @@ func (h *InstagramChannelHandler) CreateInstagramChannel(c *gin.Context) {
// Still return success — inbox was created, just couldn't fetch IG record
c.JSON(http.StatusCreated, gin.H{
"inbox": gin.H{
"id": inbox.ID,
"name": inbox.Name,
"channel_type": inbox.ChannelType,
"channel_id": inbox.ChannelID,
"enabled": inbox.Enabled,
"id": inbox.ID,
"name": inbox.Name,
"channel_type": inbox.ChannelType,
"channel_id": inbox.ChannelID,
"enabled": inbox.Enabled,
"enable_auto_assignment": inbox.EnableAutoAssignment,
},
})
@@ -343,19 +346,19 @@ func (h *InstagramChannelHandler) CreateInstagramChannel(c *gin.Context) {
c.JSON(http.StatusCreated, gin.H{
"inbox": gin.H{
"id": inbox.ID,
"name": inbox.Name,
"channel_type": inbox.ChannelType,
"channel_id": inbox.ChannelID,
"enabled": inbox.Enabled,
"id": inbox.ID,
"name": inbox.Name,
"channel_type": inbox.ChannelType,
"channel_id": inbox.ChannelID,
"enabled": inbox.Enabled,
"enable_auto_assignment": inbox.EnableAutoAssignment,
},
"instagram_channel": gin.H{
"id": igChannel.ID,
"instagram_account_id": igChannel.InstagramAccountID,
"id": igChannel.ID,
"instagram_account_id": igChannel.InstagramAccountID,
"instagram_business_account_id": igChannel.InstagramBusinessAccountID,
"connected_fb_page_id": igChannel.ConnectedFBPageID,
"instagram_account_name": igChannel.InstagramAccountName,
"connected_fb_page_id": igChannel.ConnectedFBPageID,
"instagram_account_name": igChannel.InstagramAccountName,
},
})
}
@@ -478,8 +481,8 @@ func (h *InstagramChannelHandler) Reauthorize(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{
"message": "instagram channels reauthorized successfully",
"updated_count": updatedCount,
"message": "instagram channels reauthorized successfully",
"updated_count": updatedCount,
})
}
@@ -524,14 +527,14 @@ func (h *InstagramChannelHandler) GetInstagramChannel(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"instagram_channel": gin.H{
"id": igChannel.ID,
"account_id": igChannel.AccountID,
"inbox_id": igChannel.InboxID,
"instagram_account_id": igChannel.InstagramAccountID,
"id": igChannel.ID,
"account_id": igChannel.AccountID,
"inbox_id": igChannel.InboxID,
"instagram_account_id": igChannel.InstagramAccountID,
"instagram_business_account_id": igChannel.InstagramBusinessAccountID,
"connected_fb_page_id": igChannel.ConnectedFBPageID,
"instagram_account_name": igChannel.InstagramAccountName,
"reauthorization_required": igChannel.ReauthorizationRequired,
"connected_fb_page_id": igChannel.ConnectedFBPageID,
"instagram_account_name": igChannel.InstagramAccountName,
"reauthorization_required": igChannel.ReauthorizationRequired,
},
})
}
@@ -560,13 +563,13 @@ func (h *InstagramChannelHandler) ListInstagramChannels(c *gin.Context) {
result := make([]gin.H, 0, len(channels))
for _, ch := range channels {
result = append(result, gin.H{
"id": ch.ID,
"inbox_id": ch.InboxID,
"instagram_account_id": ch.InstagramAccountID,
"id": ch.ID,
"inbox_id": ch.InboxID,
"instagram_account_id": ch.InstagramAccountID,
"instagram_business_account_id": ch.InstagramBusinessAccountID,
"connected_fb_page_id": ch.ConnectedFBPageID,
"instagram_account_name": ch.InstagramAccountName,
"reauthorization_required": ch.ReauthorizationRequired,
"connected_fb_page_id": ch.ConnectedFBPageID,
"instagram_account_name": ch.InstagramAccountName,
"reauthorization_required": ch.ReauthorizationRequired,
})
}
@@ -909,12 +912,12 @@ func (h *InstagramChannelHandler) UpdateInstagramChannel(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{
"id": updated.ID,
"account_id": updated.AccountID,
"inbox_id": updated.InboxID,
"instagram_account_id": updated.InstagramAccountID,
"instagram_account_name": updated.InstagramAccountName,
"connected_fb_page_id": updated.ConnectedFBPageID,
"id": updated.ID,
"account_id": updated.AccountID,
"inbox_id": updated.InboxID,
"instagram_account_id": updated.InstagramAccountID,
"instagram_account_name": updated.InstagramAccountName,
"connected_fb_page_id": updated.ConnectedFBPageID,
"reauthorization_required": updated.ReauthorizationRequired,
})
}
}
@@ -80,6 +80,13 @@ func (h *LINEChannelHandler) Create(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return
}
if err := h.inboxSvc.EnsureCanCreateInbox(c.Request.Context(), accountID); err != nil {
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create inbox"})
return
}
ch := &channelmodel.ChannelLINE{
AccountID: accountID,
@@ -103,6 +110,12 @@ func (h *LINEChannelHandler) Create(c *gin.Context) {
inbox, err := h.inboxSvc.Create(c.Request.Context(), accountID, inboxReq)
if err != nil {
applogger.L().Errorf("Failed to create inbox for LINE channel: %v", err)
if delErr := h.lineChannelSvc.Delete(c.Request.Context(), ch.ID); delErr != nil {
applogger.L().Warnf("Failed to rollback LINE channel after inbox creation failure: %v", delErr)
}
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create inbox"})
return
}
@@ -121,6 +121,38 @@ func TestLINEChannel_Create_Success(t *testing.T) {
require.NotContains(t, resp, "inbox")
}
func TestLINEChannel_CreateRejectsAccountInboxLimitWithoutChannelOrphan(t *testing.T) {
handler, db := setupLINEHandlerTest(t)
router := setupLINETestRouter(handler)
accountID := lineAccountIDUint(db)
require.NoError(t, db.Model(&model.Account{}).Where("id = ?", accountID).Update("inbox_limit", 1).Error)
require.NoError(t, db.Create(&model.Inbox{AccountID: accountID, Name: "Existing", ChannelType: "api"}).Error)
body := CreateLINEChannelRequest{
ChannelID: "line_limit_123",
Name: "Blocked LINE",
ChannelAccessToken: "access_token_secret",
ChannelSecret: "secret_value",
}
b, _ := json.Marshal(body)
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodPost, "/api/v1/accounts/"+strconv.FormatUint(uint64(accountID), 10)+"/line_channel", bytes.NewReader(b))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
require.Equal(t, http.StatusPaymentRequired, w.Code, w.Body.String())
var resp map[string]interface{}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
require.Equal(t, service.InboxLimitExceededMessage, resp["error"])
var inboxCount int64
require.NoError(t, db.Model(&model.Inbox{}).Where("account_id = ?", accountID).Count(&inboxCount).Error)
require.Equal(t, int64(1), inboxCount)
var channelCount int64
require.NoError(t, db.Model(&channelmodel.ChannelLINE{}).Where("account_id = ?", accountID).Count(&channelCount).Error)
require.Equal(t, int64(0), channelCount)
}
func TestLINEChannel_Create_InvalidAccountID(t *testing.T) {
handler, _ := setupLINEHandlerTest(t)
router := setupLINETestRouter(handler)
@@ -108,6 +108,13 @@ func (h *MicrosoftChannelHandler) OAuthCallback(c *gin.Context) {
}
ctx := c.Request.Context()
if err := h.inboxSvc.EnsureCanCreateInbox(ctx, uint(accountID)); err != nil {
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create microsoft inbox"})
return
}
// Exchange the code for tokens
tokenResult, err := h.msProvider.ExchangeToken(ctx, req.Code, req.RedirectURL)
@@ -148,6 +155,12 @@ func (h *MicrosoftChannelHandler) OAuthCallback(c *gin.Context) {
inbox, err := h.inboxSvc.Create(ctx, uint(accountID), inboxReq)
if err != nil {
applogger.L().Errorf("Failed to create Microsoft inbox: %v", err)
if delErr := h.msService.Delete(ctx, msChannel.ID); delErr != nil {
applogger.L().Warnf("Failed to rollback Microsoft channel after inbox creation failure: %v", delErr)
}
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create microsoft inbox"})
return
}
@@ -165,8 +178,8 @@ func (h *MicrosoftChannelHandler) OAuthCallback(c *gin.Context) {
"channel_type": inbox.ChannelType,
},
"microsoft_channel": gin.H{
"id": msChannel.ID,
"tenant_id": msChannel.TenantID,
"id": msChannel.ID,
"tenant_id": msChannel.TenantID,
},
})
}
@@ -80,12 +80,19 @@ func (h *TikTokChannelHandler) CreateTikTokChannel(c *gin.Context) {
}
ctx := c.Request.Context()
if err := h.inboxSvc.EnsureCanCreateInbox(ctx, uint(accountID)); err != nil {
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create TikTok inbox", "details": err.Error()})
return
}
// 1. Create ChannelTikTok record
channelRecord := &channelmodel.ChannelTikTok{
AccountID: uint(accountID),
AccountID: uint(accountID),
TikTokBusinessID: req.TikTokBusinessID,
AccessToken: req.AccessToken,
AccessToken: req.AccessToken,
}
if err := h.ttChannelSvc.Create(ctx, channelRecord); err != nil {
@@ -107,11 +114,17 @@ func (h *TikTokChannelHandler) CreateTikTokChannel(c *gin.Context) {
})
if err != nil {
applogger.L().Errorf("Failed to create TikTok inbox: %v", err)
if delErr := h.ttChannelSvc.Delete(ctx, channelRecord.ID); delErr != nil {
applogger.L().Warnf("Failed to rollback TikTok channel after inbox creation failure: %v", delErr)
}
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create TikTok inbox", "details": err.Error()})
return
}
// 3. Link ChannelTikTok.InboxID = createdInbox.ID
// 3. Link ChannelTikTok.InboxID = createdInbox.ID
channelRecord.InboxID = createdInbox.ID
if err := h.ttChannelSvc.Update(ctx, channelRecord); err != nil {
applogger.L().Errorf("Failed to update TikTok channel inbox_id: %v", err)
@@ -140,17 +153,17 @@ func (h *TikTokChannelHandler) CreateTikTokChannel(c *gin.Context) {
c.JSON(http.StatusCreated, gin.H{
"channel": gin.H{
"id": channelRecord.ID,
"account_id": channelRecord.AccountID,
"inbox_id": channelRecord.InboxID,
"tiktok_business_id": channelRecord.TikTokBusinessID,
"id": channelRecord.ID,
"account_id": channelRecord.AccountID,
"inbox_id": channelRecord.InboxID,
"tiktok_business_id": channelRecord.TikTokBusinessID,
},
"inbox": gin.H{
"id": createdInbox.ID,
"name": createdInbox.Name,
"channel_type": createdInbox.ChannelType,
"channel_id": createdInbox.ChannelID,
"enabled": createdInbox.Enabled,
"id": createdInbox.ID,
"name": createdInbox.Name,
"channel_type": createdInbox.ChannelType,
"channel_id": createdInbox.ChannelID,
"enabled": createdInbox.Enabled,
"enable_auto_assignment": createdInbox.EnableAutoAssignment,
},
})
@@ -189,20 +202,20 @@ func (h *TikTokChannelHandler) GetTikTokChannel(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{
"id": ch.ID,
"account_id": ch.AccountID,
"inbox_id": ch.InboxID,
"tiktok_business_id": ch.TikTokBusinessID,
"id": ch.ID,
"account_id": ch.AccountID,
"inbox_id": ch.InboxID,
"tiktok_business_id": ch.TikTokBusinessID,
"reauthorization_required": ch.ReauthorizationRequired,
})
}
// UpdateTikTokChannelRequest is the DTO for updating a TikTok channel.
type UpdateTikTokChannelRequest struct {
Name string `json:"name,omitempty"`
AccessToken string `json:"access_token,omitempty"`
InboxName string `json:"inbox_name,omitempty"`
EnableAutoAssignment *bool `json:"enable_auto_assignment,omitempty"`
Name string `json:"name,omitempty"`
AccessToken string `json:"access_token,omitempty"`
InboxName string `json:"inbox_name,omitempty"`
EnableAutoAssignment *bool `json:"enable_auto_assignment,omitempty"`
}
// UpdateTikTokChannel updates a TikTok channel configuration.
@@ -346,10 +359,10 @@ func (h *TikTokChannelHandler) ListTikTokChannels(c *gin.Context) {
result := make([]gin.H, 0, len(channels))
for _, ch := range channels {
result = append(result, gin.H{
"id": ch.ID,
"account_id": ch.AccountID,
"inbox_id": ch.InboxID,
"tiktok_business_id": ch.TikTokBusinessID,
"id": ch.ID,
"account_id": ch.AccountID,
"inbox_id": ch.InboxID,
"tiktok_business_id": ch.TikTokBusinessID,
"reauthorization_required": ch.ReauthorizationRequired,
})
}
@@ -358,4 +371,4 @@ func (h *TikTokChannelHandler) ListTikTokChannels(c *gin.Context) {
"channels": result,
"count": len(result),
})
}
}
@@ -81,6 +81,13 @@ func (h *TwilioChannelHandler) Create(c *gin.Context) {
}
ctx := c.Request.Context()
if err := h.inboxSvc.EnsureCanCreateInbox(ctx, accountID); err != nil {
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create inbox"})
return
}
medium := firstNonEmptyString(req.Medium, "sms")
phoneNumber := twilioPhoneNumberForMedium(req.PhoneNumber, medium)
@@ -127,6 +134,9 @@ func (h *TwilioChannelHandler) Create(c *gin.Context) {
if delErr := h.twChannelSvc.Delete(ctx, ch.ID); delErr != nil {
applogger.L().Warnf("Failed to rollback Twilio SMS channel after inbox creation failure: %v", delErr)
}
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create inbox"})
return
}
@@ -123,6 +123,13 @@ func (h *TwitterChannelHandler) OAuthCallback(c *gin.Context) {
}
ctx := c.Request.Context()
if err := h.inboxSvc.EnsureCanCreateInbox(ctx, uint(accountID)); err != nil {
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create twitter inbox"})
return
}
// Exchange the code for tokens (PKCE verifier stored in state)
// For now, use empty verifier since state-based verifier retrieval requires session storage
@@ -144,10 +151,10 @@ func (h *TwitterChannelHandler) OAuthCallback(c *gin.Context) {
// Create the Twitter channel record
twChannel := &channelmodel.ChannelTwitter{
AccountID: uint(accountID),
AccessToken: tokenResult.AccessToken,
RefreshToken: tokenResult.RefreshToken,
WebhookEnv: h.twProvider.GetWebhookEnv(),
AccountID: uint(accountID),
AccessToken: tokenResult.AccessToken,
RefreshToken: tokenResult.RefreshToken,
WebhookEnv: h.twProvider.GetWebhookEnv(),
}
if err := h.twService.Create(ctx, twChannel); err != nil {
@@ -158,13 +165,19 @@ func (h *TwitterChannelHandler) OAuthCallback(c *gin.Context) {
// Create the inbox
inboxReq := service.CreateInboxRequest{
Name: req.Name,
ChannelType: string(model.InboxChannelTypeTwitter),
Name: req.Name,
ChannelType: string(model.InboxChannelTypeTwitter),
}
inbox, err := h.inboxSvc.Create(ctx, uint(accountID), inboxReq)
if err != nil {
applogger.L().Errorf("Failed to create Twitter inbox: %v", err)
if delErr := h.twService.Delete(ctx, twChannel.ID); delErr != nil {
applogger.L().Warnf("Failed to rollback Twitter channel after inbox creation failure: %v", delErr)
}
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to create twitter inbox"})
return
}
@@ -400,9 +413,9 @@ func (h *TwitterChannelHandler) OAuthCallbackGET(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{
"channel_id": twChannel.ID,
"access_token": twChannel.AccessToken,
"webhook_env": twChannel.WebhookEnv,
"state": state,
"channel_id": twChannel.ID,
"access_token": twChannel.AccessToken,
"webhook_env": twChannel.WebhookEnv,
"state": state,
})
}
+4 -1
View File
@@ -47,6 +47,9 @@ func (h *WebWidgetHandler) CreateWebWidgetInbox(c *gin.Context) {
inbox, err := h.inboxSvc.CreateWebWidgetInbox(c.Request.Context(), uint(accountID), req)
if err != nil {
applogger.L().Errorf("Failed to create web_widget inbox: %v", err)
if renderInboxLimitExceeded(c, err) {
return
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
return
}
@@ -157,4 +160,4 @@ func (h *WebWidgetHandler) DeleteWebWidgetInbox(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"id": inboxID, "deleted": true})
}
}
+1
View File
@@ -13,6 +13,7 @@ type Account struct {
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]
InboxLimit int `gorm:"default:0" json:"inbox_limit,omitempty"` // max inboxes allowed (0 = unlimited), Chatwoot usage_limits[:inboxes]
}
func (Account) TableName() string { return "accounts" }
+46
View File
@@ -18,6 +18,10 @@ import (
pkgvalidator "github.com/gochat/gochat/pkg/validator"
)
const InboxLimitExceededMessage = "Account limit exceeded. Upgrade to a higher plan"
var ErrInboxLimitExceeded = errors.New(InboxLimitExceededMessage)
// InboxService implements business logic for Inbox operations.
// Reference: Chatwoot app/controllers/api/v1/inboxes_controller.rb
type InboxService struct {
@@ -71,6 +75,33 @@ func (s *InboxService) GetByAccountAndID(ctx context.Context, accountID, id uint
return s.repo.FindByAccountAndID(ctx, accountID, id)
}
// EnsureCanCreateInbox enforces Chatwoot's account usage_limits[:inboxes]
// guard before any inbox or dedicated channel records are persisted.
func (s *InboxService) EnsureCanCreateInbox(ctx context.Context, accountID uint) error {
if s == nil || s.repo == nil {
return nil
}
var account model.Account
if err := s.repo.DB().WithContext(ctx).First(&account, accountID).Error; err != nil {
return fmt.Errorf("get account: %w", err)
}
if account.InboxLimit <= 0 {
return nil
}
count, err := s.repo.CountByAccount(ctx, accountID)
if err != nil {
return fmt.Errorf("count inboxes: %w", err)
}
if count >= int64(account.InboxLimit) {
return ErrInboxLimitExceeded
}
return nil
}
func IsInboxLimitExceeded(err error) bool {
return errors.Is(err, ErrInboxLimitExceeded)
}
// CreateInboxRequest is the DTO for creating an inbox.
type CreateInboxRequest struct {
Name string `json:"name" validate:"omitempty,min=2"`
@@ -96,6 +127,9 @@ type CreateInboxRequest struct {
// Create creates a new inbox.
func (s *InboxService) Create(ctx context.Context, accountID uint, req CreateInboxRequest) (*model.Inbox, error) {
if err := s.EnsureCanCreateInbox(ctx, accountID); err != nil {
return nil, err
}
if err := pkgvalidator.ValidateStruct(req); err != nil {
return nil, err
}
@@ -701,6 +735,9 @@ type UpdateWebWidgetConfigRequest struct {
// and auto-generates website_token and hmac_token.
// Reference: Chatwoot Inbox#create_web_widget — generates tokens on creation
func (s *InboxService) CreateWebWidgetInbox(ctx context.Context, accountID uint, req CreateWebWidgetInboxRequest) (*model.Inbox, error) {
if err := s.EnsureCanCreateInbox(ctx, accountID); err != nil {
return nil, err
}
if err := pkgvalidator.ValidateStruct(req); err != nil {
return nil, err
}
@@ -894,6 +931,9 @@ type UpdateTelegramInboxRequest struct {
// The TelegramService handles bot token validation and webhook setup.
// The InboxService handles the Inbox creation and links it to the ChannelTelegram.
func (s *InboxService) CreateTelegramInbox(ctx context.Context, accountID uint, req CreateTelegramInboxRequest) (*model.Inbox, error) {
if err := s.EnsureCanCreateInbox(ctx, accountID); err != nil {
return nil, err
}
if err := pkgvalidator.ValidateStruct(req); err != nil {
return nil, err
}
@@ -1163,6 +1203,9 @@ type UpdateInstagramInboxRequest struct {
// Instagram DMs require a connected Facebook Page. The inbox wraps both the
// ChannelInstagram record (for IG-specific fields) and the Inbox record.
func (s *InboxService) CreateInstagramInbox(ctx context.Context, accountID uint, req CreateInstagramInboxRequest, igRepo *repository.ChannelInstagramRepo) (*model.Inbox, error) {
if err := s.EnsureCanCreateInbox(ctx, accountID); err != nil {
return nil, err
}
if err := pkgvalidator.ValidateStruct(req); err != nil {
return nil, err
}
@@ -1367,6 +1410,9 @@ type CreateFacebookInboxRequest struct {
// Reference: Chatwoot accounts/channels/facebook_pages_controller#create
// Flow: generate verify token → create ChannelFacebook → create Inbox → link
func (s *InboxService) CreateFacebookInbox(ctx context.Context, accountID uint, req CreateFacebookInboxRequest, fbRepo *repository.ChannelFacebookRepo) (*model.Inbox, error) {
if err := s.EnsureCanCreateInbox(ctx, accountID); err != nil {
return nil, err
}
if err := pkgvalidator.ValidateStruct(req); err != nil {
return nil, err
}
+51 -1
View File
@@ -85,6 +85,56 @@ func createTestAgentBot(t *testing.T, db *gorm.DB, accountID uint, suffix string
return bot
}
func TestInboxService_Create_AllowsUnlimitedInboxLimit(t *testing.T) {
svc, db := setupInboxServiceTest(t)
account := &model.Account{Name: "Unlimited Inboxes", Locale: "en", Active: true, InboxLimit: 0}
require.NoError(t, db.Create(account).Error)
require.NoError(t, db.Create(&model.Inbox{AccountID: account.ID, Name: "Existing", ChannelType: "api"}).Error)
inbox, err := svc.Create(context.Background(), account.ID, CreateInboxRequest{
Name: "New API",
ChannelType: "api",
})
require.NoError(t, err)
require.NotZero(t, inbox.ID)
}
func TestInboxService_CreateRejectsAtAccountInboxLimit(t *testing.T) {
svc, db := setupInboxServiceTest(t)
account := &model.Account{Name: "Limited Inboxes", Locale: "en", Active: true, InboxLimit: 1}
require.NoError(t, db.Create(account).Error)
require.NoError(t, db.Create(&model.Inbox{AccountID: account.ID, Name: "Existing", ChannelType: "api"}).Error)
inbox, err := svc.Create(context.Background(), account.ID, CreateInboxRequest{
Name: "Blocked API",
ChannelType: "api",
})
require.ErrorIs(t, err, ErrInboxLimitExceeded)
require.Nil(t, inbox)
var count int64
require.NoError(t, db.Model(&model.Inbox{}).Where("account_id = ?", account.ID).Count(&count).Error)
assert.Equal(t, int64(1), count)
}
func TestInboxService_CreateAllowsBelowAccountInboxLimit(t *testing.T) {
svc, db := setupInboxServiceTest(t)
account := &model.Account{Name: "Below Limit", Locale: "en", Active: true, InboxLimit: 2}
require.NoError(t, db.Create(account).Error)
require.NoError(t, db.Create(&model.Inbox{AccountID: account.ID, Name: "Existing", ChannelType: "api"}).Error)
inbox, err := svc.Create(context.Background(), account.ID, CreateInboxRequest{
Name: "Allowed API",
ChannelType: "api",
})
require.NoError(t, err)
require.NotZero(t, inbox.ID)
var count int64
require.NoError(t, db.Model(&model.Inbox{}).Where("account_id = ?", account.ID).Count(&count).Error)
assert.Equal(t, int64(2), count)
}
// ========================================
// SetAgentBot service tests
// ========================================
@@ -415,4 +465,4 @@ func TestInboxService_RegisterWebhook_WhatsAppInbox_NoWaService(t *testing.T) {
})
// Will fail because whatsapp service/repo are nil
assert.Error(t, err)
}
}
+1
View File
@@ -13,6 +13,7 @@ CREATE TABLE IF NOT EXISTS accounts (
status VARCHAR(50) DEFAULT 'active',
active BOOLEAN DEFAULT TRUE,
auto_resolve_duration INTEGER DEFAULT 0,
inbox_limit INTEGER DEFAULT 0,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
deleted_at TIMESTAMP WITH TIME ZONE
@@ -0,0 +1,3 @@
ALTER TABLE accounts
DROP COLUMN IF EXISTS inbox_limit;
@@ -0,0 +1,3 @@
ALTER TABLE accounts
ADD COLUMN IF NOT EXISTS inbox_limit INTEGER DEFAULT 0;