feat(agents): align delete scope

This commit is contained in:
2026-06-06 02:36:18 +08:00
parent 8b30cc78a0
commit ec1bb257dc
3 changed files with 34 additions and 6 deletions
+6 -4
View File
@@ -16,10 +16,10 @@ Build GoChat as a Go backend that can directly reuse the frontend from `referenc
## Current Baseline
- Current tracking checkpoint: 2026-06-06 after `dd2bdee feat(agents): align create name defaults`, with this implementation checkpoint prepared as `feat(agents): align duplicate create errors`.
- Latest implementation checkpoint: this checkpoint, prepared as `feat(agents): align duplicate create errors`.
- Current tracking checkpoint: 2026-06-06 after `8b30cc7 feat(agents): align duplicate create errors`, with this implementation checkpoint prepared as `feat(agents): align delete scope`.
- Latest implementation checkpoint: this checkpoint, prepared as `feat(agents): align delete scope`.
- Latest documentation-only checkpoint: `8b378c7 docs: refresh parity tracker baseline`; this document is now the active follow-up plan and supersedes `.hermes/plans/*`.
- Worktree status at this implementation checkpoint: Duplicate account agent creation now matches Chatwoot's `ActiveRecord::RecordInvalid` response shape: `422` with `{ message, attributes }` instead of a local `409` envelope. Agent creation already matches Chatwoot `AgentBuilder` name fallback: blank or omitted `agent[name]` no longer fails local validation and new users receive the email local-part as `name`. Account conversation/contact attachment list pagination already matches Chatwoot's fixed 100-row page size for `ConversationsController#attachments` and `Contacts::AttachmentsController#index`; reused frontend `per_page` query values no longer shrink shared attachment payloads below the reference page size. Profile account permission drift is closed for reused route guards and dashboard permission helpers: profile account entries now return Chatwoot `AccountUser#permissions` for ordinary roles (`["administrator"]` or `["agent"]`) and continue to return enterprise custom-role permissions plus `custom_role` when `custom_role_id` is present. The preceding platform account-user membership, agents list ordering, update-route/`auto_offline`, agents bulk invite, B10.3 CustomRole frontend update, and Phase 6 contacts pagination/active payload drifts are closed. Conversation transcript and custom-attribute response drifts are already closed. The fresh placeholder audit found remaining `chatwootParityStub` routes only in webhook handler-not-injected fallbacks, not in the reused dashboard account/contact/conversation/message/inbox critical path. P3.6 custom filters/custom attribute definitions and label CRUD are already in Review. B11.1a-B11.3e Captain/Copilot slices remain in Review; B12.1/B12.2/B12.3 smoke harnesses remain in Review; P5 durable job work through P5.13b is in Review. Next active implementation slice is the next named Phase 2/3 or Phase 6 drift from fresh reference/smoke evidence.
- Worktree status at this implementation checkpoint: Agent delete now matches Chatwoot's `agents.find(params[:id])` account scope: deleting a user who is not a member of the current account returns `404` and does not remove that user or any other account membership. Duplicate account agent creation already matches Chatwoot's `ActiveRecord::RecordInvalid` response shape: `422` with `{ message, attributes }` instead of a local `409` envelope. Agent creation already matches Chatwoot `AgentBuilder` name fallback: blank or omitted `agent[name]` no longer fails local validation and new users receive the email local-part as `name`. Account conversation/contact attachment list pagination already matches Chatwoot's fixed 100-row page size for `ConversationsController#attachments` and `Contacts::AttachmentsController#index`; reused frontend `per_page` query values no longer shrink shared attachment payloads below the reference page size. Profile account permission drift is closed for reused route guards and dashboard permission helpers: profile account entries now return Chatwoot `AccountUser#permissions` for ordinary roles (`["administrator"]` or `["agent"]`) and continue to return enterprise custom-role permissions plus `custom_role` when `custom_role_id` is present. The preceding platform account-user membership, agents list ordering, update-route/`auto_offline`, agents bulk invite, B10.3 CustomRole frontend update, and Phase 6 contacts pagination/active payload drifts are closed. Conversation transcript and custom-attribute response drifts are already closed. The fresh placeholder audit found remaining `chatwootParityStub` routes only in webhook handler-not-injected fallbacks, not in the reused dashboard account/contact/conversation/message/inbox critical path. P3.6 custom filters/custom attribute definitions and label CRUD are already in Review. B11.1a-B11.3e Captain/Copilot slices remain in Review; B12.1/B12.2/B12.3 smoke harnesses remain in Review; P5 durable job work through P5.13b is in Review. Next active implementation slice is the next named Phase 2/3 or Phase 6 drift from fresh reference/smoke evidence.
- `go test ./...` passes.
- Route dump succeeds with `TOTAL: 840` after adding the Chatwoot platform account-user collection destroy route.
- Route parity artifacts now exist under `docs/parity/` and are generated by `cmd/route_parity`.
@@ -87,7 +87,7 @@ This table is the shortest authoritative handoff view. If an older lower section
| Priority | Workstream | Current state | Next checkpoint | Commit close rule |
| --- | --- | --- | --- | --- |
| 1 | Phase 2/3 drift | Tracked route parity is 0 missing for the current critical set; notification list/action serializers, Devise password reset/confirmation payloads, CRM shared attachment payloads plus fixed 100-row attachment pagination, account/settings payloads, assignable-agent payloads, agent create defaults/errors, label CRUD payloads, custom filters, and custom attribute definitions now match the inspected Chatwoot frontend contract. | Continue Phase 6 placeholder audit, then open the next named serializer/controller drift slice from reference/smoke evidence. | Regenerate parity artifacts when routes change and add endpoint-family fixture tests. |
| 1 | Phase 2/3 drift | Tracked route parity is 0 missing for the current critical set; notification list/action serializers, Devise password reset/confirmation payloads, CRM shared attachment payloads plus fixed 100-row attachment pagination, account/settings payloads, assignable-agent payloads, agent create/delete defaults/errors/scope, label CRUD payloads, custom filters, and custom attribute definitions now match the inspected Chatwoot frontend contract. | Continue Phase 6 placeholder audit, then open the next named serializer/controller drift slice from reference/smoke evidence. | Regenerate parity artifacts when routes change and add endpoint-family fixture tests. |
| 2 | Phase 6 placeholder audit | Widget/public/webhook critical placeholders are burned down; inbox WhatsApp health/register-webhook and sync-template drift are closed; fresh `rg` audit shows only webhook nil-handler fallbacks still call `chatwootParityStub`; dashboard conversation transcript response drift is closed. | Continue targeted account/contact/conversation/message/inbox drift from reference/smoke evidence. | `rg` placeholder audit is recorded and no reused-frontend blocker is ownerless. |
| 3 | B12 optional live smoke | API/browser/enterprise smoke commands are checked in; live runs need PostgreSQL, Redis, Meilisearch, Vite, and Chrome. | Run full live smoke when environment is available and map failures to the board. | `docs/parity/frontend_smoke_report.md` records pass/fail and linked owners. |
| 4 | B9.3 delayed automation actions | Current reference exposes no delayed automation action params; scheduled-item work is already P5.12; `send_email_to_team` is durable and `add_sla` mutates conversation/applied SLA state. | Keep automation drift closed if future reference/smoke exposes delayed params or unsupported action shapes. | Automation worker/action fixtures verify queued team email replay, retry visibility through worker jobs, and SLA action idempotency. |
@@ -143,6 +143,7 @@ This ledger records the committed parity checkpoints that future slices should b
| Commit | Scope | Verification summary | Follow-up state |
| --- | --- | --- | --- |
| `feat(agents): align delete scope` | Advances P3.2 agents/settings parity by matching Chatwoot `AgentsController#fetch_agent` before `destroy`: deletes are scoped through current account membership and return `404` when the target user is not an agent in the account. The local delete path now looks up the `AccountUser` before deletion so cross-account/non-member users are not accidentally deleted. | `go test ./internal/handler/api/v1 -run 'TestAgentHandlerSuite/TestDeleteAgent' -count=1`; `go test ./internal/handler/api/v1 ./internal/service ./internal/repository -count=1`; `go test ./...`; `git diff --check`. No route changes; route dump remains `TOTAL: 840`. | Continue P3.2 agents/account-user drift or the next Phase 6 reference/smoke finding. |
| `feat(agents): align duplicate create errors` | Advances P3.2 agents/settings parity by matching Chatwoot's `ActiveRecord::RecordInvalid` handling for duplicate account memberships created through `AgentsController#create`. Re-inviting an existing account member now returns `422 { message: "User has already been taken", attributes: ["user_id"] }` instead of the local `409` conflict envelope, while bulk invite continues to skip duplicate failures like the reference controller. | `go test ./internal/handler/api/v1 -run 'TestAgentHandlerSuite/TestCreateAgentDuplicate' -count=1`; `go test ./internal/handler/api/v1 ./internal/service ./internal/repository -count=1`; `go test ./...`; `git diff --check`. No route changes; route dump remains `TOTAL: 840`. | Continue P3.2 agents/account-user drift or the next Phase 6 reference/smoke finding. |
| `feat(agents): align create name defaults` | Advances P3.2 agents/settings parity by matching Chatwoot `AgentsController#create` and `AgentBuilder`. Agent creation now accepts blank or omitted `agent[name]`; for newly created users, the name falls back to the email local-part exactly like `email.split('@').first`, while existing-user invitation behavior remains unchanged. | `go test ./internal/handler/api/v1 -run 'TestAgentHandlerSuite/TestCreateAgent' -count=1`; `go test ./internal/service ./internal/repository -run Agent -count=1`; `go test ./internal/handler/api/v1 ./internal/service ./internal/repository -count=1`; `go test ./...`; `git diff --check`. No route changes; route dump remains `TOTAL: 840`. | Continue P3.2 agents/account-user drift or the next Phase 6 reference/smoke finding. |
| `feat(attachments): align list pagination` | Advances Phase 6 dashboard/CRM attachment drift by matching Chatwoot `ConversationsController#attachments`, `Contacts::AttachmentsController#index`, and the shared attachment Jbuilder payloads. Conversation and contact attachment lists now page with the reference fixed 100-row limit from `ATTACHMENT_RESULTS_PER_PAGE`/`RESULTS_PER_PAGE` and ignore reused-frontend `per_page` query values, while retaining newest-first attachment ordering and `{ meta: { total_count }, payload }` responses. | `go test ./internal/handler/api/v1 -run 'Test(ConversationHandlerTestSuite|ContactHandlerCRUDTestSuite)/TestListAttachments' -count=1`; `go test ./internal/handler/api/v1 ./internal/service ./internal/repository -count=1`; `go test ./...`; `git diff --check`. No route changes; route dump remains `TOTAL: 840`. | Continue the next named Phase 2/3 or Phase 6 drift from reference/smoke evidence. |
@@ -2080,6 +2081,7 @@ Verification milestone gates:
## Progress Log
- 2026-06-06: P3.2 agent delete-scope checkpoint prepared as `feat(agents): align delete scope`; audited Chatwoot `AgentsController#destroy`, `fetch_agent`, and account-scoped `agents` relation. Agent delete now first resolves the current account membership and returns `404` for non-members, preserving users and memberships in other accounts instead of treating an unscoped delete as success. Focused delete tests, combined handler/service/repository tests, full `go test ./...`, and `git diff --check` passed; continue P3.2 agents/account-user drift or the next Phase 6 reference/smoke finding.
- 2026-06-06: P3.2 agent duplicate-create checkpoint prepared as `feat(agents): align duplicate create errors`; audited Chatwoot `AgentsController#create`, `AgentBuilder#create_account_user`, `AccountUser` uniqueness validation, and `RequestExceptionHandler#render_record_invalid`. Duplicate account membership creation through `/agents` now returns Chatwoot `422 { message, attributes }` instead of local `409`, while bulk invite duplicate skipping remains unchanged. Focused duplicate-create tests, combined handler/service/repository tests, full `go test ./...`, and `git diff --check` passed; continue P3.2 agents/account-user drift or the next Phase 6 reference/smoke finding.
- 2026-06-06: P3.2 agent create-default checkpoint prepared as `feat(agents): align create name defaults`; audited Chatwoot `AgentsController#create`, `AgentBuilder`, `AccountUser`, and the reused dashboard agents API. Agent creation now accepts blank/omitted `agent[name]`, derives new-user names from the email local-part like `email.split('@').first`, and keeps existing agent create role/availability/auto-offline behavior intact. Focused agent create tests, service/repository agent tests, combined handler/service/repository tests, full `go test ./...`, and `git diff --check` passed; continue P3.2 agents/account-user drift or the next Phase 6 reference/smoke finding.
- 2026-06-06: Phase 6 attachment pagination checkpoint prepared as `feat(attachments): align list pagination`; audited Chatwoot `ConversationsController#attachments`, `Contacts::AttachmentsController#index`, and the shared attachment Jbuilder partials. Conversation and contact shared attachment lists now use Chatwoot's fixed 100-row page size and ignore `per_page` query values, preserving `{ meta: { total_count }, payload }`, newest-first ordering, sender serialization, and contact attachment `conversation_id`. Focused attachment suite tests, combined handler/service/repository tests, full `go test ./...`, and `git diff --check` passed; continue the next Phase 2/3 or Phase 6 drift from reference/smoke evidence.
@@ -322,6 +322,27 @@ func (s *AgentHandlerTestSuite) TestDeleteAgent() {
assert.Equal(s.T(), http.StatusNotFound, w3.Code)
}
func (s *AgentHandlerTestSuite) TestDeleteAgentNotInAccountReturnsNotFound() {
otherAccount := &model.Account{Name: "Other Account", Locale: "en", Active: true}
s.Require().NoError(s.db.Create(otherAccount).Error)
otherUser := &model.User{Name: "Other Agent", Email: "other-agent@test.com", Provider: "email", Active: true}
s.Require().NoError(s.db.Create(otherUser).Error)
s.Require().NoError(s.db.Create(&model.AccountUser{AccountID: otherAccount.ID, UserID: otherUser.ID, Role: "agent", Availability: "offline", AutoOffline: true}).Error)
w, c := s.makeRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/agents/%d", s.account.ID, otherUser.ID), nil, s.account.ID, s.user.ID)
s.handler.Delete(c)
assert.Equal(s.T(), http.StatusNotFound, w.Code, w.Body.String())
var userCount int64
s.Require().NoError(s.db.Model(&model.User{}).Where("id = ?", otherUser.ID).Count(&userCount).Error)
assert.Equal(s.T(), int64(1), userCount)
var membershipCount int64
s.Require().NoError(s.db.Model(&model.AccountUser{}).Where("account_id = ? AND user_id = ?", otherAccount.ID, otherUser.ID).Count(&membershipCount).Error)
assert.Equal(s.T(), int64(1), membershipCount)
}
func (s *AgentHandlerTestSuite) TestBulkCreate() {
req := service.BulkCreateAgentRequest{
Emails: []string{"bulk1@test.com", "bulk2@test.com", "bulk3@test.com"},
+7 -2
View File
@@ -245,10 +245,15 @@ func (r *AgentRepo) UpdateAgent(ctx context.Context, userID, accountID uint, nam
// Reference: Chatwoot agents_controller.rb#destroy → current_account_user.destroy!
// If the user has no other account memberships, deletes the user record too.
func (r *AgentRepo) DeleteAgent(ctx context.Context, userID, accountID uint) error {
// Delete the AccountUser
var accountUser model.AccountUser
if err := r.db.WithContext(ctx).
Where("account_id = ? AND user_id = ?", accountID, userID).
Delete(&model.AccountUser{}).Error; err != nil {
First(&accountUser).Error; err != nil {
return err
}
// Delete the AccountUser after the scoped lookup succeeds.
if err := r.db.WithContext(ctx).Delete(&accountUser).Error; err != nil {
return err
}