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.
321 lines
16 KiB
Go
321 lines
16 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_CaptainUsageDoesNotExposeNegativeAvailability(t *testing.T) {
|
|
router, db, account, user := setupEnterpriseAccountHandlerTest(t)
|
|
|
|
account.Limits = datatypes.JSON(`{"captain_documents":1,"captain_responses":2}`)
|
|
require.NoError(t, account.SetCustomAttributesMap(map[string]any{
|
|
"captain_documents_usage": 3,
|
|
"captain_responses_usage": 4,
|
|
}))
|
|
require.NoError(t, db.Save(account).Error)
|
|
require.NoError(t, db.Create(&model.AccountUser{AccountID: account.ID, UserID: user.ID, Role: "administrator"}).Error)
|
|
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/enterprise/api/v1/accounts/%d/limits", account.ID), nil)
|
|
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)
|
|
captain := limits["captain"].(map[string]any)
|
|
documents := captain["documents"].(map[string]any)
|
|
responses := captain["responses"].(map[string]any)
|
|
require.Equal(t, float64(1), documents["total_count"])
|
|
require.Equal(t, float64(3), documents["consumed"])
|
|
require.Equal(t, float64(0), documents["current_available"])
|
|
require.Equal(t, float64(2), responses["total_count"])
|
|
require.Equal(t, float64(4), responses["consumed"])
|
|
require.Equal(t, float64(0), responses["current_available"])
|
|
}
|
|
|
|
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 TestEnterpriseAccountLiteralFrontendPathsUseCurrentAccountContext(t *testing.T) {
|
|
router, db, account, user := setupEnterpriseAccountHandlerTest(t)
|
|
account.AgentLimit = 4
|
|
account.Limits = datatypes.JSON(`{"captain_documents":3,"captain_responses":9}`)
|
|
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.CaptainDocument{AccountID: account.ID, AssistantID: 1, Name: "Doc", ExternalLink: "https://example.com"}).Error)
|
|
|
|
limits := httptest.NewRecorder()
|
|
limitsReq := httptest.NewRequest(http.MethodGet, "/enterprise/api/v1/limits", nil)
|
|
limitsReq.Header.Set("X-Account-ID", fmt.Sprint(account.ID))
|
|
router.ServeHTTP(limits, limitsReq)
|
|
require.Equal(t, http.StatusOK, limits.Code, limits.Body.String())
|
|
var body map[string]any
|
|
require.NoError(t, json.Unmarshal(limits.Body.Bytes(), &body))
|
|
require.Equal(t, float64(account.ID), body["id"])
|
|
limitPayload := body["limits"].(map[string]any)
|
|
agents := limitPayload["agents"].(map[string]any)
|
|
require.Equal(t, float64(4), agents["allowed"])
|
|
require.Equal(t, float64(1), agents["consumed"])
|
|
captain := limitPayload["captain"].(map[string]any)
|
|
documents := captain["documents"].(map[string]any)
|
|
require.Equal(t, float64(3), documents["total_count"])
|
|
require.Equal(t, float64(1), documents["consumed"])
|
|
require.Equal(t, float64(2), documents["current_available"])
|
|
|
|
subscription := enterpriseAccountLiteralRequest(t, router, account.ID, http.MethodPost, "subscription", ``)
|
|
require.Equal(t, http.StatusNoContent, subscription.Code, subscription.Body.String())
|
|
require.NoError(t, db.First(account, account.ID).Error)
|
|
require.Equal(t, true, account.CustomAttributesMap()["is_creating_customer"])
|
|
|
|
checkout := enterpriseAccountLiteralRequest(t, router, account.ID, http.MethodPost, "checkout", ``)
|
|
require.Equal(t, http.StatusUnprocessableEntity, checkout.Code, checkout.Body.String())
|
|
require.Contains(t, checkout.Body.String(), "Please subscribe to a plan before viewing the billing details")
|
|
|
|
topupMissingCredits := enterpriseAccountLiteralRequest(t, router, account.ID, http.MethodPost, "topup_checkout", `{}`)
|
|
require.Equal(t, http.StatusUnprocessableEntity, topupMissingCredits.Code, topupMissingCredits.Body.String())
|
|
require.Contains(t, topupMissingCredits.Body.String(), "Credits are required")
|
|
|
|
deleteResp := enterpriseAccountLiteralRequest(t, router, account.ID, http.MethodPost, "toggle_deletion", `{"action_type":"delete"}`)
|
|
require.Equal(t, http.StatusOK, deleteResp.Code, deleteResp.Body.String())
|
|
require.NoError(t, db.First(account, account.ID).Error)
|
|
require.Equal(t, "manual_deletion", account.CustomAttributesMap()["marked_for_deletion_reason"])
|
|
}
|
|
|
|
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 TestEnterpriseAccountBillingErrorBoundariesDoNotMutateAccount(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)
|
|
require.NoError(t, account.SetCustomAttributesMap(map[string]any{"existing": "kept"}))
|
|
require.NoError(t, db.Save(account).Error)
|
|
|
|
checkout := enterpriseAccountRequest(t, router, account.ID, http.MethodPost, "checkout", ``)
|
|
require.Equal(t, http.StatusUnprocessableEntity, checkout.Code, checkout.Body.String())
|
|
var checkoutBody map[string]any
|
|
require.NoError(t, json.Unmarshal(checkout.Body.Bytes(), &checkoutBody))
|
|
require.Equal(t, "Please subscribe to a plan before viewing the billing details", checkoutBody["error"])
|
|
|
|
missingCredits := enterpriseAccountRequest(t, router, account.ID, http.MethodPost, "topup_checkout", `{}`)
|
|
require.Equal(t, http.StatusUnprocessableEntity, missingCredits.Code, missingCredits.Body.String())
|
|
var missingCreditsBody map[string]any
|
|
require.NoError(t, json.Unmarshal(missingCredits.Body.Bytes(), &missingCreditsBody))
|
|
require.Equal(t, "Credits are required", missingCreditsBody["error"])
|
|
|
|
providerUnavailable := enterpriseAccountRequest(t, router, account.ID, http.MethodPost, "topup_checkout", `{"credits":50}`)
|
|
require.Equal(t, http.StatusUnprocessableEntity, providerUnavailable.Code, providerUnavailable.Body.String())
|
|
var providerUnavailableBody map[string]any
|
|
require.NoError(t, json.Unmarshal(providerUnavailable.Body.Bytes(), &providerUnavailableBody))
|
|
require.Equal(t, "Top-up checkout provider is not configured", providerUnavailableBody["error"])
|
|
|
|
invalidToggle := enterpriseAccountRequest(t, router, account.ID, http.MethodPost, "toggle_deletion", `{"action_type":"archive"}`)
|
|
require.Equal(t, http.StatusUnprocessableEntity, invalidToggle.Code, invalidToggle.Body.String())
|
|
var invalidToggleBody map[string]any
|
|
require.NoError(t, json.Unmarshal(invalidToggle.Body.Bytes(), &invalidToggleBody))
|
|
require.Equal(t, `Invalid action_type. Must be either "delete" or "undelete"`, invalidToggleBody["error"])
|
|
|
|
require.NoError(t, db.First(account, account.ID).Error)
|
|
attrs := account.CustomAttributesMap()
|
|
require.Equal(t, "kept", attrs["existing"])
|
|
require.NotContains(t, attrs, "is_creating_customer")
|
|
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 TestEnterpriseAccountSubscriptionPreservesExistingCustomerState(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)
|
|
require.NoError(t, account.SetCustomAttributesMap(map[string]any{
|
|
"stripe_customer_id": "cus_existing",
|
|
"existing": "kept",
|
|
}))
|
|
require.NoError(t, db.Save(account).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)
|
|
attrs := account.CustomAttributesMap()
|
|
require.Equal(t, "cus_existing", attrs["stripe_customer_id"])
|
|
require.Equal(t, "kept", attrs["existing"])
|
|
require.NotContains(t, attrs, "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)
|
|
router.GET("/enterprise/api/v1/limits", handler.Limits)
|
|
router.POST("/enterprise/api/v1/subscription", handler.Subscription)
|
|
router.POST("/enterprise/api/v1/checkout", handler.Checkout)
|
|
router.POST("/enterprise/api/v1/topup_checkout", handler.TopupCheckout)
|
|
router.POST("/enterprise/api/v1/toggle_deletion", handler.ToggleDeletion)
|
|
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
|
|
}
|
|
|
|
func enterpriseAccountLiteralRequest(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/%s", action), bytes.NewBufferString(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("X-Account-ID", fmt.Sprint(accountID))
|
|
w := httptest.NewRecorder()
|
|
router.ServeHTTP(w, req)
|
|
return w
|
|
}
|