Files
gochat/internal/handler/api/v1/enterprise_account_handler_test.go
T

175 lines
7.8 KiB
Go

package v1
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"gorm.io/datatypes"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/repository"
"github.com/gochat/gochat/internal/service"
)
func TestEnterpriseAccountLimits_ChatwootPayload(t *testing.T) {
router, db, account, user := setupEnterpriseAccountHandlerTest(t)
account.AgentLimit = 3
account.InboxLimit = 4
account.Limits = datatypes.JSON(`{"captain_documents":5,"captain_responses":7}`)
require.NoError(t, account.SetCustomAttributesMap(map[string]any{"captain_responses_usage": 2}))
require.NoError(t, db.Save(account).Error)
require.NoError(t, db.Create(&model.AccountUser{AccountID: account.ID, UserID: user.ID, Role: "administrator"}).Error)
require.NoError(t, db.Create(&model.AccountUser{AccountID: account.ID, UserID: seedEnterpriseUser(t, db, "agent@example.com").ID, Role: "agent"}).Error)
require.NoError(t, db.Create(&model.CaptainDocument{AccountID: account.ID, AssistantID: 1, Name: "Doc", ExternalLink: "https://example.com"}).Error)
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/enterprise/api/v1/accounts/%d/limits", account.ID), nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.Equal(t, float64(account.ID), body["id"])
limits := body["limits"].(map[string]any)
agents := limits["agents"].(map[string]any)
require.Equal(t, float64(3), agents["allowed"])
require.Equal(t, float64(2), agents["consumed"])
captain := limits["captain"].(map[string]any)
documents := captain["documents"].(map[string]any)
require.Equal(t, float64(5), documents["total_count"])
require.Equal(t, float64(4), documents["current_available"])
require.Equal(t, float64(1), documents["consumed"])
responses := captain["responses"].(map[string]any)
require.Equal(t, float64(7), responses["total_count"])
require.Equal(t, float64(5), responses["current_available"])
require.Equal(t, float64(2), responses["consumed"])
}
func TestEnterpriseAccountLimits_DefaultPlanPayload(t *testing.T) {
router, db, account, user := setupEnterpriseAccountHandlerTest(t)
require.NoError(t, account.SetCustomAttributesMap(map[string]any{"default_plan": true}))
require.NoError(t, db.Save(account).Error)
require.NoError(t, db.Create(&model.AccountUser{AccountID: account.ID, UserID: user.ID, Role: "administrator"}).Error)
old := time.Now().AddDate(0, 0, -31)
require.NoError(t, db.Create(&model.Conversation{AccountID: account.ID, InboxID: 1, ContactID: 1, ChannelType: "web_widget", Channel: "web_widget"}).Error)
oldConversation := &model.Conversation{AccountID: account.ID, InboxID: 1, ContactID: 1, ChannelType: "web_widget", Channel: "web_widget"}
oldConversation.CreatedAt = old
require.NoError(t, db.Create(oldConversation).Error)
require.NoError(t, db.Create(&model.Inbox{AccountID: account.ID, Name: "Web", ChannelType: "web_widget", ChannelID: 1}).Error)
require.NoError(t, db.Create(&model.Inbox{AccountID: account.ID, Name: "Email", ChannelType: "email", ChannelID: 2}).Error)
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/enterprise/api/v1/accounts/%d/limits", account.ID), nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
limits := body["limits"].(map[string]any)
conversation := limits["conversation"].(map[string]any)
require.Equal(t, float64(500), conversation["allowed"])
require.Equal(t, float64(1), conversation["consumed"])
nonWeb := limits["non_web_inboxes"].(map[string]any)
require.Equal(t, float64(0), nonWeb["allowed"])
require.Equal(t, float64(1), nonWeb["consumed"])
}
func TestEnterpriseAccountToggleDeletion(t *testing.T) {
router, db, account, user := setupEnterpriseAccountHandlerTest(t)
require.NoError(t, db.Create(&model.AccountUser{AccountID: account.ID, UserID: user.ID, Role: "administrator"}).Error)
w := enterpriseAccountRequest(t, router, account.ID, http.MethodPost, "toggle_deletion", `{"action_type":"delete"}`)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
require.NoError(t, db.First(account, account.ID).Error)
attrs := account.CustomAttributesMap()
require.Equal(t, "manual_deletion", attrs["marked_for_deletion_reason"])
require.NotEmpty(t, attrs["marked_for_deletion_at"])
w = enterpriseAccountRequest(t, router, account.ID, http.MethodPost, "toggle_deletion", `{"action_type":"undelete"}`)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
require.NoError(t, db.First(account, account.ID).Error)
attrs = account.CustomAttributesMap()
require.NotContains(t, attrs, "marked_for_deletion_reason")
require.NotContains(t, attrs, "marked_for_deletion_at")
}
func TestEnterpriseAccountSubscriptionSetsCreationFlag(t *testing.T) {
router, db, account, user := setupEnterpriseAccountHandlerTest(t)
require.NoError(t, db.Create(&model.AccountUser{AccountID: account.ID, UserID: user.ID, Role: "administrator"}).Error)
w := enterpriseAccountRequest(t, router, account.ID, http.MethodPost, "subscription", ``)
require.Equal(t, http.StatusNoContent, w.Code, w.Body.String())
require.NoError(t, db.First(account, account.ID).Error)
require.Equal(t, true, account.CustomAttributesMap()["is_creating_customer"])
}
func TestEnterpriseAccountRejectsAccountOutsideCurrentUser(t *testing.T) {
router, _, account, _ := setupEnterpriseAccountHandlerTest(t)
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/enterprise/api/v1/accounts/%d/limits", account.ID), nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusNotFound, w.Code, w.Body.String())
}
func setupEnterpriseAccountHandlerTest(t *testing.T) (*gin.Engine, *gorm.DB, *model.Account, *model.User) {
t.Helper()
gin.SetMode(gin.TestMode)
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
t.Cleanup(func() {
sqlDB, _ := db.DB()
_ = sqlDB.Close()
})
require.NoError(t, db.AutoMigrate(&model.Account{}, &model.User{}, &model.AccountUser{}, &model.Conversation{}, &model.Inbox{}, &model.CaptainDocument{}))
user := seedEnterpriseUser(t, db, "admin@example.com")
account := &model.Account{Name: "Acme", Active: true, Status: "active", Locale: "en"}
require.NoError(t, db.Create(account).Error)
svc := service.NewAccountService(repository.NewAccountRepo(db))
handler := NewEnterpriseAccountHandler(svc)
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set("user_id", user.ID)
c.Next()
})
accounts := router.Group("/enterprise/api/v1/accounts")
accounts.GET("/:account_id/limits", handler.Limits)
accounts.POST("/:account_id/toggle_deletion", handler.ToggleDeletion)
accounts.POST("/:account_id/subscription", handler.Subscription)
accounts.POST("/:account_id/checkout", handler.Checkout)
accounts.POST("/:account_id/topup_checkout", handler.TopupCheckout)
return router, db, account, user
}
func seedEnterpriseUser(t *testing.T, db *gorm.DB, email string) *model.User {
t.Helper()
user := &model.User{Name: email, Email: email, Password: "hashed", Active: true}
require.NoError(t, db.Create(user).Error)
return user
}
func enterpriseAccountRequest(t *testing.T, router *gin.Engine, accountID uint, method, action, body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, fmt.Sprintf("/enterprise/api/v1/accounts/%d/%s", accountID, action), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
return w
}