package v1 import ( "bytes" "encoding/json" "fmt" "net/http" "net/http/httptest" "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 (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() 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", 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) } 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) }