feat(inboxes): align agent bot member actions
This commit is contained in:
@@ -1,13 +1,23 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"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"
|
||||
)
|
||||
|
||||
@@ -15,12 +25,39 @@ func setupInboxAgentBotRouter(handler *InboxHandler) *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(gin.Recovery())
|
||||
r.POST("/api/v1/accounts/:account_id/inboxes/:inbox_id/set_agent_bot", handler.SetAgentBot)
|
||||
r.GET("/api/v1/accounts/:account_id/inboxes/:inbox_id/agent_bot", handler.GetAgentBot)
|
||||
r.DELETE("/api/v1/accounts/:account_id/inboxes/:inbox_id/avatar", handler.DeleteAvatar)
|
||||
r.GET("/api/v1/accounts/:account_id/inboxes/:inbox_id/campaigns", handler.ListCampaigns)
|
||||
return r
|
||||
}
|
||||
|
||||
func setupInboxAgentBotDB(t *testing.T) (*gin.Engine, *gorm.DB, *model.Account, *model.Inbox, *model.AgentBot) {
|
||||
t.Helper()
|
||||
dbName := "file:" + strings.ReplaceAll(t.Name(), "/", "_") + "?mode=memory&cache=shared"
|
||||
db, err := gorm.Open(sqlite.Open(dbName), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
sqlDB, dbErr := db.DB()
|
||||
if dbErr == nil {
|
||||
sqlDB.Close()
|
||||
}
|
||||
})
|
||||
require.NoError(t, db.AutoMigrate(&model.Account{}, &model.Inbox{}, &model.AgentBot{}, &model.AgentBotInbox{}))
|
||||
account := &model.Account{Name: "Agent bot org", Locale: "en", Active: true}
|
||||
require.NoError(t, db.Create(account).Error)
|
||||
inbox := &model.Inbox{AccountID: account.ID, Name: "Support", ChannelType: "web_widget", ChannelID: 1}
|
||||
require.NoError(t, db.Create(inbox).Error)
|
||||
bot := &model.AgentBot{AccountID: &account.ID, Name: "Triage bot", Description: "Routes chats", AvatarURL: "https://example.test/bot.png", OutgoingURL: "https://example.test/hook", BotType: "webhook", Config: json.RawMessage(`{"handoff":true}`), AccessToken: "access-token", Secret: "secret"}
|
||||
require.NoError(t, db.Create(bot).Error)
|
||||
svc := service.NewInboxService(repository.NewInboxRepo(db), repository.NewAgentBotInboxRepo(db), repository.NewAgentBotRepo(db), nil, nil, nil, nil)
|
||||
return setupInboxAgentBotRouter(NewInboxHandler(svc)), db, account, inbox, bot
|
||||
}
|
||||
|
||||
func inboxAgentBotTestID(id uint) string {
|
||||
return strconv.FormatUint(uint64(id), 10)
|
||||
}
|
||||
|
||||
// --- GetAgentBot tests ---
|
||||
|
||||
func TestInboxHandler_GetAgentBot_InvalidAccountID(t *testing.T) {
|
||||
@@ -57,6 +94,55 @@ func TestInboxHandler_GetAgentBot_ValidIDs_ZeroService(t *testing.T) {
|
||||
assert.True(t, w.Code == http.StatusUnprocessableEntity || w.Code == http.StatusOK)
|
||||
}
|
||||
|
||||
func TestInboxHandler_SetAndGetAgentBot_ChatwootPayload(t *testing.T) {
|
||||
router, _, account, inbox, bot := setupInboxAgentBotDB(t)
|
||||
|
||||
body, _ := json.Marshal(map[string]uint{"agent_bot": bot.ID})
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest(http.MethodPost, "/api/v1/accounts/"+inboxAgentBotTestID(account.ID)+"/inboxes/"+inboxAgentBotTestID(inbox.ID)+"/set_agent_bot", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Empty(t, w.Body.String(), "Chatwoot set_agent_bot responds head :ok")
|
||||
|
||||
w = httptest.NewRecorder()
|
||||
req, _ = http.NewRequest(http.MethodGet, "/api/v1/accounts/"+inboxAgentBotTestID(account.ID)+"/inboxes/"+inboxAgentBotTestID(inbox.ID)+"/agent_bot", nil)
|
||||
router.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
var resp map[string]map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
|
||||
agentBot := resp["agent_bot"]
|
||||
assert.Equal(t, float64(bot.ID), agentBot["id"])
|
||||
assert.Equal(t, bot.Name, agentBot["name"])
|
||||
assert.Equal(t, bot.AvatarURL, agentBot["thumbnail"])
|
||||
assert.Equal(t, bot.OutgoingURL, agentBot["outgoing_url"])
|
||||
assert.Equal(t, bot.BotType, agentBot["bot_type"])
|
||||
assert.NotContains(t, agentBot, "avatar_url")
|
||||
}
|
||||
|
||||
func TestInboxHandler_SetAgentBot_NullDisconnectsWithHeadOK(t *testing.T) {
|
||||
router, db, account, inbox, bot := setupInboxAgentBotDB(t)
|
||||
require.NoError(t, db.Create(&model.AgentBotInbox{AccountID: &account.ID, InboxID: inbox.ID, AgentBotID: bot.ID, Status: model.AgentBotInboxActive}).Error)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest(http.MethodPost, "/api/v1/accounts/"+inboxAgentBotTestID(account.ID)+"/inboxes/"+inboxAgentBotTestID(inbox.ID)+"/set_agent_bot", bytes.NewReader([]byte(`{"agent_bot":null}`)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Empty(t, w.Body.String())
|
||||
|
||||
var count int64
|
||||
require.NoError(t, db.Model(&model.AgentBotInbox{}).Where("inbox_id = ?", inbox.ID).Count(&count).Error)
|
||||
assert.Equal(t, int64(0), count)
|
||||
|
||||
w = httptest.NewRecorder()
|
||||
req, _ = http.NewRequest(http.MethodGet, "/api/v1/accounts/"+inboxAgentBotTestID(account.ID)+"/inboxes/"+inboxAgentBotTestID(inbox.ID)+"/agent_bot", nil)
|
||||
router.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
assert.JSONEq(t, `{"agent_bot":{}}`, w.Body.String())
|
||||
}
|
||||
|
||||
// --- DeleteAvatar tests ---
|
||||
|
||||
func TestInboxHandler_DeleteAvatar_InvalidAccountID(t *testing.T) {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"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/gochat/gochat/pkg/response"
|
||||
@@ -576,29 +577,29 @@ func (h *InboxHandler) SetAgentBot(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var req service.SetAgentBotRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body: " + err.Error()})
|
||||
return
|
||||
req := service.SetAgentBotRequest{}
|
||||
if c.Request.Body != nil && c.Request.ContentLength != 0 {
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if c.Request.ContentLength < 0 && errors.Is(err, io.EOF) {
|
||||
// Chunked empty body behaves like omitted params in Chatwoot and disconnects the bot.
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body: " + err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if !h.svc.Ready() {
|
||||
response.AbortWithStatusError(c, http.StatusUnprocessableEntity, response.ErrInternal, "failed to set agent bot")
|
||||
return
|
||||
}
|
||||
|
||||
binding, svcErr := h.svc.SetAgentBot(c.Request.Context(), accountID, inboxID, req)
|
||||
_, svcErr := h.svc.SetAgentBot(c.Request.Context(), accountID, inboxID, req)
|
||||
if svcErr != nil {
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
|
||||
if binding == nil {
|
||||
// Agent bot was removed
|
||||
c.JSON(http.StatusOK, gin.H{"message": "agent bot removed from inbox"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, binding)
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
// Health checks the health status of an inbox's channel connection.
|
||||
@@ -738,11 +739,28 @@ func (h *InboxHandler) GetAgentBot(c *gin.Context) {
|
||||
}
|
||||
|
||||
if agentBot == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"agent_bot": nil})
|
||||
c.JSON(http.StatusOK, gin.H{"agent_bot": gin.H{}})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"agent_bot": agentBot})
|
||||
c.JSON(http.StatusOK, gin.H{"agent_bot": serializeAgentBot(agentBot)})
|
||||
}
|
||||
|
||||
func serializeAgentBot(bot *model.AgentBot) gin.H {
|
||||
if bot == nil {
|
||||
return gin.H{}
|
||||
}
|
||||
return gin.H{
|
||||
"id": bot.ID,
|
||||
"name": bot.Name,
|
||||
"description": bot.Description,
|
||||
"thumbnail": bot.AvatarURL,
|
||||
"outgoing_url": bot.OutgoingURL,
|
||||
"bot_type": bot.BotType,
|
||||
"bot_config": bot.Config,
|
||||
"account_id": bot.AccountID,
|
||||
"access_token": bot.AccessToken,
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteAvatar removes the avatar URL from an inbox.
|
||||
|
||||
Reference in New Issue
Block a user