feat(agent-bots): align account payloads

This commit is contained in:
2026-06-06 06:03:42 +08:00
parent 689c79bb9c
commit 1adf1c9c31
9 changed files with 394 additions and 75 deletions
+86 -22
View File
@@ -5,6 +5,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/service"
"github.com/gochat/gochat/pkg/pagination"
"github.com/gochat/gochat/pkg/response"
@@ -33,32 +34,41 @@ func (h *AgentBotHandler) List(c *gin.Context) {
return
}
page := pagination.Parse(c)
bots, total, svcErr := h.svc.ListAccessible(c.Request.Context(), accountID, page.Offset, page.PerPage)
bots, svcErr := h.svc.ListAccessibleAll(c.Request.Context(), accountID)
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.OKWithMeta(c, bots, page.Page, page.PerPage, total)
payload := make([]gin.H, 0, len(bots))
for i := range bots {
payload = append(payload, serializeAccountAgentBot(&bots[i], accountID))
}
c.JSON(http.StatusOK, payload)
}
// Get retrieves a single agent bot by ID.
// GET /api/v1/accounts/:account_id/agent_bots/:id
func (h *AgentBotHandler) Get(c *gin.Context) {
accountID, err := parseUintParam(c, "account_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
agentBotID, err := parseUintParam(c, "agent_bot_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid agent bot ID")
return
}
bot, svcErr := h.svc.Get(c.Request.Context(), agentBotID)
bot, svcErr := h.svc.GetAccessible(c.Request.Context(), accountID, agentBotID)
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.OK(c, bot)
c.JSON(http.StatusOK, serializeAccountAgentBot(bot, accountID))
}
// Create creates a new agent bot scoped to an account.
@@ -71,7 +81,7 @@ func (h *AgentBotHandler) Create(c *gin.Context) {
}
var req service.CreateAgentBotRequest
if err := c.ShouldBindJSON(&req); err != nil {
if err := c.ShouldBind(&req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
@@ -85,12 +95,18 @@ func (h *AgentBotHandler) Create(c *gin.Context) {
return
}
response.Created(c, bot)
c.JSON(http.StatusOK, serializeAccountAgentBot(bot, accountID))
}
// Update modifies an existing agent bot.
// PUT /api/v1/accounts/:account_id/agent_bots/:id
func (h *AgentBotHandler) Update(c *gin.Context) {
accountID, err := parseUintParam(c, "account_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
agentBotID, err := parseUintParam(c, "agent_bot_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid agent bot ID")
@@ -98,96 +114,143 @@ func (h *AgentBotHandler) Update(c *gin.Context) {
}
var req service.UpdateAgentBotRequest
if err := c.ShouldBindJSON(&req); err != nil {
if err := c.ShouldBind(&req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
bot, svcErr := h.svc.Update(c.Request.Context(), agentBotID, req)
bot, svcErr := h.svc.UpdateByAccount(c.Request.Context(), accountID, agentBotID, req)
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.OK(c, bot)
c.JSON(http.StatusOK, serializeAccountAgentBot(bot, accountID))
}
// Delete removes an agent bot by ID.
// DELETE /api/v1/accounts/:account_id/agent_bots/:id
func (h *AgentBotHandler) Delete(c *gin.Context) {
accountID, err := parseUintParam(c, "account_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
agentBotID, err := parseUintParam(c, "agent_bot_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid agent bot ID")
return
}
if svcErr := h.svc.Delete(c.Request.Context(), agentBotID); svcErr != nil {
if svcErr := h.svc.DeleteByAccount(c.Request.Context(), accountID, agentBotID); svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.NoContent(c)
c.Status(http.StatusOK)
}
// ResetToken generates a new access token for the bot.
// POST /api/v1/accounts/:account_id/agent_bots/:id/reset_token
// Reference: Chatwoot AgentBotsController#reset_access_token
func (h *AgentBotHandler) ResetToken(c *gin.Context) {
accountID, err := parseUintParam(c, "account_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
agentBotID, err := parseUintParam(c, "agent_bot_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid agent bot ID")
return
}
newToken, svcErr := h.svc.ResetToken(c.Request.Context(), agentBotID)
bot, svcErr := h.svc.ResetTokenByAccount(c.Request.Context(), accountID, agentBotID)
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.OK(c, gin.H{
"access_token": newToken,
})
c.JSON(http.StatusOK, serializeAccountAgentBot(bot, accountID))
}
// ResetSecret generates a new webhook signing secret for the bot.
// POST /api/v1/accounts/:account_id/agent_bots/:id/reset_secret
// Reference: Chatwoot AgentBotsController#reset_secret
func (h *AgentBotHandler) ResetSecret(c *gin.Context) {
accountID, err := parseUintParam(c, "account_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
agentBotID, err := parseUintParam(c, "agent_bot_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid agent bot ID")
return
}
newSecret, svcErr := h.svc.ResetSecret(c.Request.Context(), agentBotID)
bot, svcErr := h.svc.ResetSecretByAccount(c.Request.Context(), accountID, agentBotID)
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.OK(c, gin.H{
"secret": newSecret,
})
c.JSON(http.StatusOK, serializeAccountAgentBot(bot, accountID))
}
// DeleteAvatar removes the bot's avatar URL.
// POST /api/v1/accounts/:account_id/agent_bots/:id/delete_avatar
// Reference: Chatwoot AgentBotsController#destroy_avatar
func (h *AgentBotHandler) DeleteAvatar(c *gin.Context) {
accountID, err := parseUintParam(c, "account_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
agentBotID, err := parseUintParam(c, "agent_bot_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid agent bot ID")
return
}
bot, svcErr := h.svc.DeleteAvatar(c.Request.Context(), agentBotID)
bot, svcErr := h.svc.DeleteAvatarByAccount(c.Request.Context(), accountID, agentBotID)
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.OK(c, bot)
c.JSON(http.StatusOK, serializeAccountAgentBot(bot, accountID))
}
func serializeAccountAgentBot(bot *model.AgentBot, accountID uint) gin.H {
if bot == nil {
return gin.H{}
}
systemBot := bot.AccountID == nil
payload := gin.H{
"id": bot.ID,
"name": bot.Name,
"description": bot.Description,
"thumbnail": bot.AvatarURL,
"bot_type": bot.BotType,
"bot_config": bot.Config,
"account_id": bot.AccountID,
"system_bot": systemBot,
}
if !systemBot {
payload["outgoing_url"] = bot.OutgoingURL
}
if bot.AccountID != nil && *bot.AccountID == accountID && bot.AccessToken != "" {
payload["access_token"] = bot.AccessToken
}
if bot.AccountID != nil && *bot.AccountID == accountID && bot.Secret != "" {
payload["secret"] = bot.Secret
}
return payload
}
// --- Platform (super admin) AgentBot endpoints ---
@@ -347,6 +410,7 @@ func (h *AgentBotHandler) PlatformResetConfig(c *gin.Context) {
response.OK(c, bot)
}
// ListAccessible retrieves agent bots accessible to an account (global + account-scoped), paginated.
// GET /api/v1/accounts/:account_id/agent_bots/accessible
func (h *AgentBotHandler) ListAccessible(c *gin.Context) {
@@ -74,8 +74,8 @@ func (s *AgentBotHandlerTestSuite) TestPlatformCreate_Success() {
r.POST("/platform/api/v1/agent_bots", s.handler.PlatformCreate)
body := map[string]interface{}{
"name": "test-global-bot",
"bot_type": "webhook",
"name": "test-global-bot",
"bot_type": "webhook",
"outgoing_url": "https://example.com/webhook",
}
b, _ := json.Marshal(body)
@@ -116,8 +116,8 @@ func (s *AgentBotHandlerTestSuite) TestAccountCreate_Success() {
r.POST("/api/v1/accounts/:account_id/agent_bots", s.handler.Create)
body := map[string]interface{}{
"name": "test-account-bot",
"bot_type": "webhook",
"name": "test-account-bot",
"bot_type": "webhook",
"outgoing_url": "https://example.com/webhook",
}
b, _ := json.Marshal(body)
@@ -127,7 +127,101 @@ func (s *AgentBotHandlerTestSuite) TestAccountCreate_Success() {
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusCreated, w.Code)
assert.Equal(s.T(), http.StatusOK, w.Code)
}
func (s *AgentBotHandlerTestSuite) TestAccountChatwootPayloadsAndRoutes() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/agent_bots", s.handler.List)
r.POST("/api/v1/accounts/:account_id/agent_bots", s.handler.Create)
r.GET("/api/v1/accounts/:account_id/agent_bots/:agent_bot_id", s.handler.Get)
r.PATCH("/api/v1/accounts/:account_id/agent_bots/:agent_bot_id", s.handler.Update)
r.DELETE("/api/v1/accounts/:account_id/agent_bots/:agent_bot_id", s.handler.Delete)
r.DELETE("/api/v1/accounts/:account_id/agent_bots/:agent_bot_id/avatar", s.handler.DeleteAvatar)
r.POST("/api/v1/accounts/:account_id/agent_bots/:agent_bot_id/reset_access_token", s.handler.ResetToken)
r.POST("/api/v1/accounts/:account_id/agent_bots/:agent_bot_id/reset_secret", s.handler.ResetSecret)
global := &model.AgentBot{Name: "system-bot", BotType: "webhook", OutgoingURL: "https://system.example/hook", AccessToken: "global-token", Secret: "global-secret", Config: json.RawMessage(`{"mode":"system"}`)}
s.Require().NoError(s.db.Create(global).Error)
createBody := []byte(`{"name":"chatwoot-bot","description":"before","bot_type":"webhook","outgoing_url":"https://example.com/webhook","avatar_url":"https://example.com/bot.png","bot_config":{"handoff":true}}`)
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/agent_bots", s.account.ID), bytes.NewReader(createBody))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var created map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &created))
botID := uint(created["id"].(float64))
assert.NotContains(s.T(), created, "success")
assert.Equal(s.T(), "chatwoot-bot", created["name"])
assert.Equal(s.T(), "https://example.com/bot.png", created["thumbnail"])
assert.Equal(s.T(), "https://example.com/webhook", created["outgoing_url"])
assert.Equal(s.T(), false, created["system_bot"])
assert.NotEmpty(s.T(), created["access_token"])
assert.NotEmpty(s.T(), created["secret"])
assert.Contains(s.T(), created, "bot_config")
w = httptest.NewRecorder()
req, _ = http.NewRequest(http.MethodGet, fmt.Sprintf("/api/v1/accounts/%d/agent_bots", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var list []map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &list))
assert.GreaterOrEqual(s.T(), len(list), 2)
assert.NotContains(s.T(), list[0], "success")
w = httptest.NewRecorder()
updateBody := []byte(`{"description":"","outgoing_url":"","bot_config":{"handoff":false}}`)
req, _ = http.NewRequest(http.MethodPatch, fmt.Sprintf("/api/v1/accounts/%d/agent_bots/%d", s.account.ID, botID), bytes.NewReader(updateBody))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var updated map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &updated))
assert.Equal(s.T(), "", updated["description"])
assert.Equal(s.T(), "", updated["outgoing_url"])
w = httptest.NewRecorder()
req, _ = http.NewRequest(http.MethodPatch, fmt.Sprintf("/api/v1/accounts/%d/agent_bots/%d", s.account.ID, global.ID), bytes.NewReader([]byte(`{"name":"blocked"}`)))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusNotFound, w.Code)
oldToken := created["access_token"]
w = httptest.NewRecorder()
req, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/agent_bots/%d/reset_access_token", s.account.ID, botID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var resetToken map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &resetToken))
assert.Equal(s.T(), float64(botID), resetToken["id"])
assert.NotEqual(s.T(), oldToken, resetToken["access_token"])
assert.NotContains(s.T(), resetToken, "data")
oldSecret := resetToken["secret"]
w = httptest.NewRecorder()
req, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/agent_bots/%d/reset_secret", s.account.ID, botID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var resetSecret map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &resetSecret))
assert.NotEqual(s.T(), oldSecret, resetSecret["secret"])
w = httptest.NewRecorder()
req, _ = http.NewRequest(http.MethodDelete, fmt.Sprintf("/api/v1/accounts/%d/agent_bots/%d/avatar", s.account.ID, botID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var avatar map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &avatar))
assert.Equal(s.T(), "", avatar["thumbnail"])
w = httptest.NewRecorder()
req, _ = http.NewRequest(http.MethodDelete, fmt.Sprintf("/api/v1/accounts/%d/agent_bots/%d", s.account.ID, botID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
assert.Empty(s.T(), w.Body.String())
}
func (s *AgentBotHandlerTestSuite) TestAccountCreate_BadRequest() {
@@ -218,4 +312,4 @@ func (s *AgentBotHandlerTestSuite) TestDeleteAvatar_BadRequest() {
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
}
}