Restructure the monorepo into clear top-level directories: - backend/: Go module root (cmd, internal, pkg, configs, migrations, docs/swagger, scripts, tests, go.mod, Makefile, .air.toml) - deploy/: Docker (Dockerfile, docker-compose*), quickstart, fluentd - docs/: project documentation + reports/ (moved from repo root) - AGENTS.md: new AI coding-agent guide at repo root Update all references to the new layout: - Dockerfile: COPY backend/go.mod, COPY backend/ (context = repo root) - docker-compose files: context ../.., dockerfile deploy/docker/Dockerfile, env_file ../../.env, volume mounts ../../backend:/app - deploy/quickstart/compose.yaml: dockerfile deploy/docker/Dockerfile - CI: working-directory: backend for go commands, file deploy/docker/Dockerfile, coverage path backend/coverage.out, health_check backend/scripts/ - backend/Makefile: docker target uses -f ../deploy/docker/Dockerfile ../ - README: architecture tree, quickstart, config paths updated Move root stray scripts (rename_models.*, run_m11_tests.sh, verify_build.sh, gorm_bool_main.go) to backend/scripts/legacy/. All moves via git mv to preserve history. Build, vet, SQLite tests, and docker compose config verified.
358 lines
15 KiB
Go
358 lines
15 KiB
Go
package v1
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/gochat/gochat/internal/model"
|
|
"github.com/gochat/gochat/internal/repository"
|
|
"github.com/gochat/gochat/internal/service"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/suite"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
)
|
|
|
|
type AgentCapacityHandlerTestSuite struct {
|
|
suite.Suite
|
|
db *gorm.DB
|
|
handler *AgentCapacityHandler
|
|
|
|
account *model.Account
|
|
}
|
|
|
|
func assertErrorEnvelope(t *testing.T, body []byte, code string, messageContains string) {
|
|
t.Helper()
|
|
var payload map[string]any
|
|
assert.NoError(t, json.Unmarshal(body, &payload))
|
|
assert.Equal(t, false, payload["success"])
|
|
errorPayload, ok := payload["error"].(map[string]any)
|
|
if !assert.True(t, ok, "expected error envelope in %s", string(body)) {
|
|
return
|
|
}
|
|
assert.Equal(t, code, errorPayload["code"])
|
|
message, _ := errorPayload["message"].(string)
|
|
assert.True(t, strings.Contains(message, messageContains), "expected message %q to contain %q", message, messageContains)
|
|
}
|
|
|
|
func (s *AgentCapacityHandlerTestSuite) SetupSuite() {
|
|
gin.SetMode(gin.TestMode)
|
|
db, err := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{
|
|
Logger: logger.Default.LogMode(logger.Silent),
|
|
})
|
|
s.Require().NoError(err)
|
|
s.Require().NoError(db.AutoMigrate(&model.Account{}, &model.User{}, &model.AccountUser{}, &model.Inbox{}, &model.AgentCapacityPolicy{}, &model.InboxCapacityLimit{}, &model.Audit{}))
|
|
s.db = db
|
|
|
|
repo := repository.NewAgentCapacityPolicyRepo(db)
|
|
svc := service.NewAgentCapacityPolicyService(repo)
|
|
auditSvc := service.NewAuditService(repository.NewAuditRepo(db))
|
|
s.handler = NewAgentCapacityHandler(svc).WithAuditService(auditSvc)
|
|
|
|
s.account = &model.Account{Name: "test-capacity-account"}
|
|
s.Require().NoError(db.Create(s.account).Error)
|
|
}
|
|
|
|
func (s *AgentCapacityHandlerTestSuite) TearDownSuite() {
|
|
if s.db != nil {
|
|
sqlDB, _ := s.db.DB()
|
|
sqlDB.Close()
|
|
}
|
|
}
|
|
|
|
func TestAgentCapacityHandlerSuite(t *testing.T) {
|
|
suite.Run(t, new(AgentCapacityHandlerTestSuite))
|
|
}
|
|
|
|
func (s *AgentCapacityHandlerTestSuite) SetupTest() {
|
|
s.Require().NoError(s.db.Exec("DELETE FROM audits").Error)
|
|
}
|
|
|
|
func (s *AgentCapacityHandlerTestSuite) TestList_Success() {
|
|
r := gin.New()
|
|
r.GET("/api/v1/accounts/:account_id/agent_capacity_policies", s.handler.List)
|
|
|
|
w := httptest.NewRecorder()
|
|
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies", s.account.ID), nil)
|
|
r.ServeHTTP(w, req)
|
|
|
|
assert.Equal(s.T(), http.StatusOK, w.Code)
|
|
}
|
|
|
|
func (s *AgentCapacityHandlerTestSuite) TestList_BadRequest_InvalidAccountID() {
|
|
r := gin.New()
|
|
r.GET("/api/v1/accounts/:account_id/agent_capacity_policies", s.handler.List)
|
|
|
|
w := httptest.NewRecorder()
|
|
req, _ := http.NewRequest("GET", "/api/v1/accounts/abc/agent_capacity_policies", nil)
|
|
r.ServeHTTP(w, req)
|
|
|
|
assert.Equal(s.T(), http.StatusUnauthorized, w.Code)
|
|
}
|
|
|
|
func (s *AgentCapacityHandlerTestSuite) TestCreate_BadRequest_EmptyBody() {
|
|
r := gin.New()
|
|
r.POST("/api/v1/accounts/:account_id/agent_capacity_policies", s.handler.Create)
|
|
|
|
w := httptest.NewRecorder()
|
|
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies", s.account.ID), nil)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
|
|
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
|
|
}
|
|
|
|
func (s *AgentCapacityHandlerTestSuite) TestGet_BadRequest_InvalidID() {
|
|
r := gin.New()
|
|
r.GET("/api/v1/accounts/:account_id/agent_capacity_policies/:id", s.handler.Get)
|
|
|
|
w := httptest.NewRecorder()
|
|
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/abc", s.account.ID), nil)
|
|
r.ServeHTTP(w, req)
|
|
|
|
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
|
|
}
|
|
|
|
func (s *AgentCapacityHandlerTestSuite) TestGet_NotFound() {
|
|
r := gin.New()
|
|
r.GET("/api/v1/accounts/:account_id/agent_capacity_policies/:id", s.handler.Get)
|
|
|
|
w := httptest.NewRecorder()
|
|
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/99999", s.account.ID), nil)
|
|
r.ServeHTTP(w, req)
|
|
|
|
assert.Equal(s.T(), http.StatusNotFound, w.Code)
|
|
}
|
|
|
|
func (s *AgentCapacityHandlerTestSuite) TestUpdate_BadRequest_InvalidID() {
|
|
r := gin.New()
|
|
r.PUT("/api/v1/accounts/:account_id/agent_capacity_policies/:id", s.handler.Update)
|
|
|
|
w := httptest.NewRecorder()
|
|
req, _ := http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/abc", s.account.ID), nil)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
|
|
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
|
|
}
|
|
|
|
func (s *AgentCapacityHandlerTestSuite) TestDelete_BadRequest_InvalidID() {
|
|
r := gin.New()
|
|
r.DELETE("/api/v1/accounts/:account_id/agent_capacity_policies/:id", s.handler.Delete)
|
|
|
|
w := httptest.NewRecorder()
|
|
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/abc", s.account.ID), nil)
|
|
r.ServeHTTP(w, req)
|
|
|
|
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
|
|
}
|
|
|
|
func (s *AgentCapacityHandlerTestSuite) TestChatwootPolicyInboxLimitAndUserFlow() {
|
|
r := gin.New()
|
|
api := r.Group("/api/v1/accounts/:account_id")
|
|
RegisterAgentCapacityRoutes(api, s.handler)
|
|
|
|
inbox := &model.Inbox{AccountID: s.account.ID, Name: "Priority", ChannelType: "web_widget"}
|
|
s.Require().NoError(s.db.Create(inbox).Error)
|
|
user := &model.User{AccountID: s.account.ID, Name: "Capacity Agent", Email: "capacity-agent@example.com", Password: "secret", Role: "agent"}
|
|
s.Require().NoError(s.db.Create(user).Error)
|
|
s.Require().NoError(s.db.Create(&model.AccountUser{AccountID: s.account.ID, UserID: user.ID, Role: "agent"}).Error)
|
|
|
|
w := httptest.NewRecorder()
|
|
body := `{"agent_capacity_policy":{"name":"Priority policy","description":"VIP","exclusion_rules":{"exclude_older_than_hours":24,"excluded_labels":["spam"]}}}`
|
|
req, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/", s.account.ID), bytes.NewBufferString(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusOK, w.Code)
|
|
var policy map[string]any
|
|
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &policy))
|
|
s.Require().NotContains(policy, "success")
|
|
s.Require().Equal("Priority policy", policy["name"])
|
|
s.Require().Equal(float64(0), policy["assigned_agent_count"])
|
|
policyID := uint(policy["id"].(float64))
|
|
|
|
w = httptest.NewRecorder()
|
|
body = fmt.Sprintf(`{"inbox_id":%d,"conversation_limit":7}`, inbox.ID)
|
|
req, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d/inbox_limits", s.account.ID, policyID), bytes.NewBufferString(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusOK, w.Code)
|
|
var limit map[string]any
|
|
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &limit))
|
|
s.Require().Equal(float64(inbox.ID), limit["inbox_id"])
|
|
s.Require().Equal(float64(7), limit["conversation_limit"])
|
|
limitID := uint(limit["id"].(float64))
|
|
|
|
w = httptest.NewRecorder()
|
|
req, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d/inbox_limits", s.account.ID, policyID), bytes.NewBufferString(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusUnprocessableEntity, w.Code)
|
|
|
|
w = httptest.NewRecorder()
|
|
req, _ = http.NewRequest(http.MethodPut, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d/inbox_limits/%d", s.account.ID, policyID, limitID), bytes.NewBufferString(`{"conversation_limit":11}`))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusOK, w.Code)
|
|
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &limit))
|
|
s.Require().Equal(float64(11), limit["conversation_limit"])
|
|
s.Require().Equal("Priority", limit["inbox_name"])
|
|
|
|
w = httptest.NewRecorder()
|
|
req, _ = http.NewRequest(http.MethodPatch, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d/inbox_limits/%d", s.account.ID, policyID, limitID), bytes.NewBufferString(`{"conversation_limit":13}`))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusOK, w.Code)
|
|
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &limit))
|
|
s.Require().Equal(float64(13), limit["conversation_limit"])
|
|
|
|
w = httptest.NewRecorder()
|
|
body = fmt.Sprintf(`{"user_id":%d}`, user.ID)
|
|
req, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d/users", s.account.ID, policyID), bytes.NewBufferString(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusOK, w.Code)
|
|
var assigned map[string]any
|
|
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &assigned))
|
|
s.Require().Equal(float64(user.ID), assigned["id"])
|
|
|
|
w = httptest.NewRecorder()
|
|
req, _ = http.NewRequest(http.MethodGet, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d/users", s.account.ID, policyID), nil)
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusOK, w.Code)
|
|
var assignedUsers []map[string]any
|
|
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &assignedUsers))
|
|
s.Require().Len(assignedUsers, 1)
|
|
s.Require().Equal(float64(user.ID), assignedUsers[0]["id"])
|
|
|
|
w = httptest.NewRecorder()
|
|
req, _ = http.NewRequest(http.MethodGet, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d", s.account.ID, policyID), nil)
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusOK, w.Code)
|
|
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &policy))
|
|
s.Require().Equal(float64(1), policy["assigned_agent_count"])
|
|
s.Require().Len(policy["inbox_capacity_limits"].([]any), 1)
|
|
|
|
w = httptest.NewRecorder()
|
|
req, _ = http.NewRequest(http.MethodDelete, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d/inbox_limits/%d", s.account.ID, policyID, limitID), nil)
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusNoContent, w.Code)
|
|
|
|
w = httptest.NewRecorder()
|
|
req, _ = http.NewRequest(http.MethodDelete, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d/users/%d", s.account.ID, policyID, user.ID), nil)
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusOK, w.Code)
|
|
|
|
w = httptest.NewRecorder()
|
|
req, _ = http.NewRequest(http.MethodGet, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d/users", s.account.ID, policyID), nil)
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusOK, w.Code)
|
|
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &assignedUsers))
|
|
s.Require().Empty(assignedUsers)
|
|
}
|
|
|
|
func (s *AgentCapacityHandlerTestSuite) TestChatwootPolicyInboxLimitAndUserValidationErrors() {
|
|
r := gin.New()
|
|
api := r.Group("/api/v1/accounts/:account_id")
|
|
RegisterAgentCapacityRoutes(api, s.handler)
|
|
|
|
inbox := &model.Inbox{AccountID: s.account.ID, Name: "Validation", ChannelType: "web_widget"}
|
|
s.Require().NoError(s.db.Create(inbox).Error)
|
|
|
|
w := httptest.NewRecorder()
|
|
body := `{"agent_capacity_policy":{"name":"Validation policy"}}`
|
|
req, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies", s.account.ID), bytes.NewBufferString(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusOK, w.Code, w.Body.String())
|
|
var policy map[string]any
|
|
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &policy))
|
|
policyID := uint(policy["id"].(float64))
|
|
|
|
w = httptest.NewRecorder()
|
|
body = fmt.Sprintf(`{"inbox_id":%d,"conversation_limit":-1}`, inbox.ID)
|
|
req, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d/inbox_limits", s.account.ID, policyID), bytes.NewBufferString(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusUnprocessableEntity, w.Code, w.Body.String())
|
|
assertErrorEnvelope(s.T(), w.Body.Bytes(), "VALIDATION_ERROR", "conversation_limit must be greater than or equal")
|
|
|
|
w = httptest.NewRecorder()
|
|
req, _ = http.NewRequest(http.MethodPatch, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d/inbox_limits/999999", s.account.ID, policyID), bytes.NewBufferString(`{"conversation_limit":5}`))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusNotFound, w.Code, w.Body.String())
|
|
assertErrorEnvelope(s.T(), w.Body.Bytes(), "NOT_FOUND", "inbox capacity limit not found")
|
|
|
|
w = httptest.NewRecorder()
|
|
req, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d/users", s.account.ID, policyID), bytes.NewBufferString(`{"user_id":0}`))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusBadRequest, w.Code, w.Body.String())
|
|
assertErrorEnvelope(s.T(), w.Body.Bytes(), "VALIDATION_ERROR", "user_id is required")
|
|
|
|
w = httptest.NewRecorder()
|
|
req, _ = http.NewRequest(http.MethodDelete, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d/users/999999", s.account.ID, policyID), nil)
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusNotFound, w.Code, w.Body.String())
|
|
assertErrorEnvelope(s.T(), w.Body.Bytes(), "NOT_FOUND", "account user not found")
|
|
}
|
|
|
|
func (s *AgentCapacityHandlerTestSuite) TestMutations_WriteAuditEntries() {
|
|
r := gin.New()
|
|
r.Use(func(c *gin.Context) {
|
|
c.Set("account_id", s.account.ID)
|
|
c.Set("user_id", uint(99))
|
|
c.Next()
|
|
})
|
|
api := r.Group("/api/v1/accounts/:account_id")
|
|
RegisterAgentCapacityRoutes(api, s.handler)
|
|
|
|
w := httptest.NewRecorder()
|
|
body := `{"agent_capacity_policy":{"name":"Audit capacity","description":"tracked"}}`
|
|
req, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/", s.account.ID), bytes.NewBufferString(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("X-Request-ID", "capacity-audit-create")
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusOK, w.Code, w.Body.String())
|
|
var policy map[string]any
|
|
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &policy))
|
|
policyID := uint(policy["id"].(float64))
|
|
|
|
w = httptest.NewRecorder()
|
|
body = `{"agent_capacity_policy":{"name":"Audit capacity updated","description":"tracked again"}}`
|
|
req, _ = http.NewRequest(http.MethodPut, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d", s.account.ID, policyID), bytes.NewBufferString(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusOK, w.Code, w.Body.String())
|
|
|
|
w = httptest.NewRecorder()
|
|
req, _ = http.NewRequest(http.MethodDelete, fmt.Sprintf("/api/v1/accounts/%d/agent_capacity_policies/%d", s.account.ID, policyID), nil)
|
|
r.ServeHTTP(w, req)
|
|
s.Require().Equal(http.StatusOK, w.Code, w.Body.String())
|
|
|
|
var audits []model.Audit
|
|
s.Require().NoError(s.db.Order("id ASC").Find(&audits).Error)
|
|
s.Require().Len(audits, 3)
|
|
for _, audit := range audits {
|
|
s.Equal(s.account.ID, *audit.AccountID)
|
|
s.Equal("Account", audit.AssociatedType)
|
|
s.Equal(s.account.ID, *audit.AssociatedID)
|
|
s.Equal(uint(99), *audit.UserID)
|
|
s.Equal("AgentCapacityPolicy", audit.AuditableType)
|
|
s.Equal(policyID, audit.AuditableID)
|
|
s.NotEmpty(audit.AuditedChanges)
|
|
}
|
|
s.Equal("create", audits[0].Action)
|
|
s.Equal("capacity-audit-create", audits[0].RequestUUID)
|
|
s.Equal("update", audits[1].Action)
|
|
s.Equal("destroy", audits[2].Action)
|
|
}
|