feat(enterprise): align account limits API
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
"github.com/gochat/gochat/pkg/response"
|
||||
)
|
||||
|
||||
// EnterpriseAccountHandler implements Chatwoot enterprise account billing and
|
||||
// limit endpoints consumed by the reused dashboard EnterpriseAccountAPI client.
|
||||
type EnterpriseAccountHandler struct {
|
||||
svc *service.AccountService
|
||||
}
|
||||
|
||||
func NewEnterpriseAccountHandler(svc *service.AccountService) *EnterpriseAccountHandler {
|
||||
return &EnterpriseAccountHandler{svc: svc}
|
||||
}
|
||||
|
||||
// Limits returns account usage limits in Chatwoot's enterprise payload shape.
|
||||
// GET /enterprise/api/v1/accounts/:account_id/limits
|
||||
func (h *EnterpriseAccountHandler) Limits(c *gin.Context) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account id")
|
||||
return
|
||||
}
|
||||
|
||||
payload, err := h.svc.EnterpriseLimits(c.Request.Context(), accountID, getUserID(c))
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrAccountNotFound, "account not found")
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, payload)
|
||||
}
|
||||
|
||||
// ToggleDeletion marks or unmarks an account for scheduled deletion.
|
||||
// POST /enterprise/api/v1/accounts/:account_id/toggle_deletion
|
||||
func (h *EnterpriseAccountHandler) ToggleDeletion(c *gin.Context) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account id")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
ActionType string `json:"action_type" form:"action_type"`
|
||||
}
|
||||
_ = c.ShouldBind(&req)
|
||||
|
||||
switch req.ActionType {
|
||||
case "delete":
|
||||
if _, err := h.svc.MarkForDeletion(c.Request.Context(), accountID, getUserID(c), "manual_deletion"); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusUnprocessableEntity, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Account marked for deletion"})
|
||||
case "undelete":
|
||||
if _, err := h.svc.UnmarkForDeletion(c.Request.Context(), accountID, getUserID(c)); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusUnprocessableEntity, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Account unmarked for deletion"})
|
||||
default:
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Invalid action_type. Must be either \"delete\" or \"undelete\""})
|
||||
}
|
||||
}
|
||||
|
||||
// Subscription mirrors the Cloud customer-creation guard and returns no content.
|
||||
// POST /enterprise/api/v1/accounts/:account_id/subscription
|
||||
func (h *EnterpriseAccountHandler) Subscription(c *gin.Context) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account id")
|
||||
return
|
||||
}
|
||||
if err := h.svc.EnsureEnterpriseAccountCustomerCreationFlag(c.Request.Context(), accountID, getUserID(c)); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrAccountNotFound, "account not found")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// Checkout returns Chatwoot's billing-details error when no Stripe session can be created locally.
|
||||
// POST /enterprise/api/v1/accounts/:account_id/checkout
|
||||
func (h *EnterpriseAccountHandler) Checkout(c *gin.Context) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account id")
|
||||
return
|
||||
}
|
||||
if _, err := h.svc.GetByUserAndID(c.Request.Context(), getUserID(c), accountID); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrAccountNotFound, "account not found")
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Please subscribe to a plan before viewing the billing details"})
|
||||
}
|
||||
|
||||
// TopupCheckout validates credits and exposes a provider-unavailable boundary for local installs.
|
||||
// POST /enterprise/api/v1/accounts/:account_id/topup_checkout
|
||||
func (h *EnterpriseAccountHandler) TopupCheckout(c *gin.Context) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account id")
|
||||
return
|
||||
}
|
||||
if _, err := h.svc.GetByUserAndID(c.Request.Context(), getUserID(c), accountID); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrAccountNotFound, "account not found")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Credits int `json:"credits" form:"credits"`
|
||||
}
|
||||
_ = c.ShouldBind(&req)
|
||||
if req.Credits <= 0 {
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Credits are required"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Top-up checkout provider is not configured"})
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user