feat(inboxes): align chatwoot inbox members

This commit is contained in:
2026-06-05 05:28:41 +08:00
parent c6a22ad99e
commit 82167f5dd3
4 changed files with 235 additions and 47 deletions
+68 -13
View File
@@ -4,6 +4,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/service"
)
@@ -35,10 +36,7 @@ func (h *InboxMemberHandler) ListMembers(c *gin.Context) {
return
}
c.JSON(http.StatusOK, gin.H{
"members": members,
"meta": gin.H{"count": len(members)},
})
c.JSON(http.StatusOK, inboxMembersPayload(members))
}
// AddMember assigns an agent to an inbox (seat assignment).
@@ -66,7 +64,7 @@ func (h *InboxMemberHandler) AddMember(c *gin.Context) {
return
}
c.JSON(http.StatusCreated, member)
c.JSON(http.StatusCreated, inboxMembersPayload([]model.InboxMember{*member}))
}
// RemoveMember removes an agent from an inbox (unassign seat).
@@ -121,7 +119,7 @@ func (h *InboxMemberHandler) UpdateMember(c *gin.Context) {
return
}
c.JSON(http.StatusOK, member)
c.JSON(http.StatusOK, inboxMembersPayload([]model.InboxMember{*member}))
}
// UpdateMultiple replaces all members of an inbox with a new set of user IDs (batch seat assignment).
@@ -147,10 +145,7 @@ func (h *InboxMemberHandler) UpdateMultiple(c *gin.Context) {
return
}
c.JSON(http.StatusOK, gin.H{
"members": members,
"meta": gin.H{"count": len(members)},
})
c.JSON(http.StatusOK, inboxMembersPayload(members))
}
// ShowAccountScoped retrieves all agents assigned to an inbox using Chatwoot's account-level route.
@@ -168,13 +163,25 @@ func (h *InboxMemberHandler) ShowAccountScoped(c *gin.Context) {
return
}
c.JSON(http.StatusOK, gin.H{"members": members, "meta": gin.H{"count": len(members)}})
c.JSON(http.StatusOK, inboxMembersPayload(members))
}
// CreateAccountScoped adds or replaces inbox members using Chatwoot's account-level create route.
// POST /api/v1/accounts/:account_id/inbox_members
func (h *InboxMemberHandler) CreateAccountScoped(c *gin.Context) {
h.updateAccountScoped(c)
var req service.UpdateMultipleRequest
if bindErr := c.ShouldBindJSON(&req); bindErr != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": bindErr.Error()})
return
}
members, svcErr := h.svc.AddMembers(c.Request.Context(), req)
if svcErr != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to update members"})
return
}
c.JSON(http.StatusOK, inboxMembersPayload(members))
}
// UpdateAccountScoped replaces all members of an inbox using Chatwoot's account-level update route.
@@ -196,7 +203,7 @@ func (h *InboxMemberHandler) updateAccountScoped(c *gin.Context) {
return
}
c.JSON(http.StatusOK, gin.H{"members": members, "meta": gin.H{"count": len(members)}})
c.JSON(http.StatusOK, inboxMembersPayload(members))
}
// DestroyAccountScoped removes selected users from an inbox using Chatwoot's account-level route.
@@ -220,3 +227,51 @@ func (h *InboxMemberHandler) DestroyAccountScoped(c *gin.Context) {
c.Status(http.StatusOK)
}
func inboxMembersPayload(members []model.InboxMember) gin.H {
payload := make([]gin.H, 0, len(members))
for _, member := range members {
payload = append(payload, serializeInboxMemberAgent(member))
}
return gin.H{"payload": payload}
}
func serializeInboxMemberAgent(member model.InboxMember) gin.H {
user := member.User
availableName := user.DisplayName
if availableName == "" {
availableName = user.Name
}
if availableName == "" {
availableName = user.Email
}
availabilityStatus := member.AvailabilityStatus
if availabilityStatus == "" {
if user.Available {
availabilityStatus = "online"
} else {
availabilityStatus = "offline"
}
}
role := user.Role
if role == "" {
role = member.Role
}
if role == "" {
role = "agent"
}
return gin.H{
"id": user.ID,
"account_id": member.Inbox.AccountID,
"availability_status": availabilityStatus,
"auto_offline": true,
"confirmed": user.ConfirmedAt != nil,
"email": user.Email,
"provider": user.Provider,
"available_name": availableName,
"name": user.Name,
"role": role,
"thumbnail": user.AvatarURL,
"custom_role_id": user.CustomRoleID,
}
}
@@ -2,16 +2,19 @@ package v1
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"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/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
@@ -77,6 +80,10 @@ func (s *InboxMemberHandlerTestSuite) TestListMembers_Success() {
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var body map[string]any
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &body))
s.Require().Contains(body, "payload")
s.Require().NotContains(body, "members")
}
func (s *InboxMemberHandlerTestSuite) TestAddMember_BadRequest_InvalidInboxID() {
@@ -91,6 +98,79 @@ func (s *InboxMemberHandlerTestSuite) TestAddMember_BadRequest_InvalidInboxID()
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
}
func (s *InboxMemberHandlerTestSuite) TestAccountScopedInboxMembers_ChatwootPayloadAndDiffUpdate() {
s.db.Exec("DELETE FROM inbox_members")
users := []*model.User{
{AccountID: s.account.ID, Name: "Agent One", DisplayName: "Agent 1", Email: "agent1@example.com", Password: "password", Provider: "email", Role: "agent", ConfirmedAt: ptrTimeNow()},
{AccountID: s.account.ID, Name: "Agent Two", Email: "agent2@example.com", Password: "password", Provider: "email", Role: "agent"},
{AccountID: s.account.ID, Name: "Agent Three", Email: "agent3@example.com", Password: "password", Provider: "email", Role: "agent"},
}
for _, user := range users {
s.Require().NoError(s.db.Create(user).Error)
}
s.Require().NoError(s.db.Create(&model.InboxMember{InboxID: s.inbox.ID, UserID: users[0].ID, Role: "agent", AvailabilityStatus: "online"}).Error)
r := gin.New()
r.GET("/api/v1/accounts/:account_id/inbox_members/:inbox_id", s.handler.ShowAccountScoped)
r.POST("/api/v1/accounts/:account_id/inbox_members", s.handler.CreateAccountScoped)
r.PATCH("/api/v1/accounts/:account_id/inbox_members", s.handler.UpdateAccountScoped)
r.DELETE("/api/v1/accounts/:account_id/inbox_members", s.handler.DestroyAccountScoped)
show := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/inbox_members/%d", s.account.ID, s.inbox.ID), nil)
r.ServeHTTP(show, req)
s.Require().Equal(http.StatusOK, show.Code, show.Body.String())
payload := inboxMemberPayload(s.T(), show)
s.Require().Len(payload, 1)
s.Require().Equal("Agent 1", payload[0]["available_name"])
s.Require().Equal("online", payload[0]["availability_status"])
s.Require().NotContains(payload[0], "inbox_id")
create := httptest.NewRecorder()
body := fmt.Sprintf(`{"inbox_id":%d,"user_ids":[%d,%d,%d]}`, s.inbox.ID, users[0].ID, users[1].ID, users[1].ID)
req, _ = http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/inbox_members", s.account.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(create, req)
s.Require().Equal(http.StatusOK, create.Code, create.Body.String())
payload = inboxMemberPayload(s.T(), create)
s.Require().Len(payload, 2)
update := httptest.NewRecorder()
body = fmt.Sprintf(`{"inbox_id":%d,"user_ids":[%d]}`, s.inbox.ID, users[2].ID)
req, _ = http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/inbox_members", s.account.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(update, req)
s.Require().Equal(http.StatusOK, update.Code, update.Body.String())
payload = inboxMemberPayload(s.T(), update)
s.Require().Len(payload, 1)
s.Require().Equal(float64(users[2].ID), payload[0]["id"])
destroy := httptest.NewRecorder()
body = fmt.Sprintf(`{"inbox_id":%d,"user_ids":[%d]}`, s.inbox.ID, users[2].ID)
req, _ = http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/inbox_members", s.account.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(destroy, req)
s.Require().Equal(http.StatusOK, destroy.Code, destroy.Body.String())
var count int64
s.Require().NoError(s.db.Model(&model.InboxMember{}).Where("inbox_id = ?", s.inbox.ID).Count(&count).Error)
s.Require().Zero(count)
}
func inboxMemberPayload(t *testing.T, response *httptest.ResponseRecorder) []map[string]any {
t.Helper()
var body struct {
Payload []map[string]any `json:"payload"`
}
require.NoError(t, json.Unmarshal(response.Body.Bytes(), &body), response.Body.String())
return body.Payload
}
func ptrTimeNow() *time.Time {
now := time.Now()
return &now
}
func (s *InboxMemberHandlerTestSuite) TestRemoveMember_BadRequest_InvalidInboxID() {
r := gin.New()
r.DELETE("/api/v1/accounts/:account_id/inboxes/:inbox_id/members/:user_id", s.handler.RemoveMember)
@@ -100,4 +180,4 @@ func (s *InboxMemberHandlerTestSuite) TestRemoveMember_BadRequest_InvalidInboxID
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
}
}