feat(labels): align chatwoot label payloads

This commit is contained in:
2026-06-06 00:33:00 +08:00
parent 8b378c79e4
commit 171cbd16d2
10 changed files with 474 additions and 60 deletions
+3
View File
@@ -11,6 +11,9 @@ import (
)
func bindJSONWrappedOrRaw(c *gin.Context, wrapperKey string, target any) error {
if c.Request.Body == nil {
return fmt.Errorf("empty request body")
}
body, err := io.ReadAll(c.Request.Body)
if err != nil {
return err
+66 -21
View File
@@ -5,6 +5,7 @@ import (
"strconv"
"github.com/gin-gonic/gin"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/service"
applogger "github.com/gochat/gochat/pkg/logger"
"github.com/gochat/gochat/pkg/response"
@@ -31,15 +32,11 @@ func (h *LabelHandler) CreateTag(c *gin.Context) {
return
}
// Chatwoot: params.require(:label) → {"label": {...}}
var wrapper struct {
Label service.CreateTagRequest `json:"label"`
}
if err := c.ShouldBindJSON(&wrapper); err != nil {
var req service.CreateTagRequest
if err := bindJSONWrappedOrRaw(c, "label", &req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
req := wrapper.Label
tag, err := h.tagSvc.Create(c.Request.Context(), accountID, &req)
if err != nil {
@@ -48,26 +45,31 @@ func (h *LabelHandler) CreateTag(c *gin.Context) {
return
}
response.Created(c, tag)
c.JSON(http.StatusOK, serializeLabel(tag))
}
// GetTag retrieves a tag by ID.
// GET /api/v1/accounts/:account_id/tags/:tag_id
func (h *LabelHandler) GetTag(c *gin.Context) {
accountID, err := parseUintParam(c, "account_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
tagID, err := parseUintParam(c, "tag_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid tag_id")
return
}
tag, err := h.tagSvc.GetByID(c.Request.Context(), tagID)
tag, err := h.tagSvc.GetByIDAndAccountID(c.Request.Context(), accountID, tagID)
if err != nil {
applogger.L().Errorf("Get tag: %v", err)
handleServiceError(c, err)
return
}
response.OK(c, tag)
c.JSON(http.StatusOK, serializeLabel(tag))
}
// ListTags returns all tags in an account.
@@ -86,27 +88,34 @@ func (h *LabelHandler) ListTags(c *gin.Context) {
return
}
response.OK(c, tags)
c.JSON(http.StatusOK, gin.H{"payload": serializeLabels(tags)})
}
// UpdateTag modifies an existing tag.
// PUT /api/v1/accounts/:account_id/tags/:tag_id
func (h *LabelHandler) UpdateTag(c *gin.Context) {
accountID, err := parseUintParam(c, "account_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
tagID, err := parseUintParam(c, "tag_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid tag_id")
return
}
// Chatwoot: params.require(:label) → {"label": {...}}
var wrapper struct {
Label service.UpdateTagRequest `json:"label"`
if _, err := h.tagSvc.GetByIDAndAccountID(c.Request.Context(), accountID, tagID); err != nil {
applogger.L().Errorf("Get tag for update: %v", err)
handleServiceError(c, err)
return
}
if err := c.ShouldBindJSON(&wrapper); err != nil {
var req service.UpdateTagRequest
if err := bindJSONWrappedOrRaw(c, "label", &req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
req := wrapper.Label
tag, err := h.tagSvc.Update(c.Request.Context(), tagID, &req)
if err != nil {
@@ -115,25 +124,61 @@ func (h *LabelHandler) UpdateTag(c *gin.Context) {
return
}
response.OK(c, tag)
c.JSON(http.StatusOK, serializeLabel(tag))
}
// DeleteTag soft-deletes a tag.
// DELETE /api/v1/accounts/:account_id/tags/:tag_id
func (h *LabelHandler) DeleteTag(c *gin.Context) {
accountID, err := parseUintParam(c, "account_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
tagID, err := parseUintParam(c, "tag_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid tag_id")
return
}
if _, err := h.tagSvc.GetByIDAndAccountID(c.Request.Context(), accountID, tagID); err != nil {
applogger.L().Errorf("Get tag for delete: %v", err)
handleServiceError(c, err)
return
}
if err := h.tagSvc.Delete(c.Request.Context(), tagID); err != nil {
applogger.L().Errorf("Delete tag: %v", err)
handleServiceError(c, err)
return
}
response.NoContent(c)
c.Status(http.StatusOK)
}
func serializeLabels(tags []model.Tag) []gin.H {
payload := make([]gin.H, 0, len(tags))
for i := range tags {
payload = append(payload, serializeLabel(&tags[i]))
}
return payload
}
func serializeLabel(tag *model.Tag) gin.H {
return gin.H{
"id": tag.ID,
"title": tag.Name,
"description": tag.Description,
"color": tag.Color,
"show_on_sidebar": labelShowOnSidebar(tag),
}
}
func labelShowOnSidebar(tag *model.Tag) bool {
if tag.ShowOnSidebar == nil {
return false
}
return *tag.ShowOnSidebar
}
// ========== Conversation-Label Association ==========
@@ -327,9 +372,9 @@ func (h *LabelHandler) GetConversationsByTag(c *gin.Context) {
}
response.OK(c, gin.H{
"labels": labels,
"count": count,
"page": page,
"labels": labels,
"count": count,
"page": page,
"per_page": perPage,
})
}
}
+93 -4
View File
@@ -33,7 +33,7 @@ func (s *LabelHandlerTestSuite) SetupSuite() {
Logger: logger.Default.LogMode(logger.Silent),
})
s.Require().NoError(err)
s.Require().NoError(db.AutoMigrate(&model.Account{}, &model.User{}, &model.Tag{}, &model.ConversationLabel{}, &model.Conversation{}, &model.Inbox{}, &model.Contact{}))
s.Require().NoError(db.AutoMigrate(&model.Account{}, &model.User{}, &model.Tag{}, &model.ConversationLabel{}, &model.ContactLabel{}, &model.Conversation{}, &model.Inbox{}, &model.Contact{}))
s.db = db
convLabelRepo := repository.NewConversationLabelRepo(db)
@@ -57,15 +57,31 @@ func TestLabelHandlerSuite(t *testing.T) {
suite.Run(t, new(LabelHandlerTestSuite))
}
func labelBoolPtr(v bool) *bool { return &v }
func (s *LabelHandlerTestSuite) SetupTest() {
s.Require().NoError(s.db.Exec("DELETE FROM conversation_labels").Error)
s.Require().NoError(s.db.Exec("DELETE FROM contact_labels").Error)
s.Require().NoError(s.db.Unscoped().Where("account_id = ?", s.account.ID).Delete(&model.Tag{}).Error)
}
func (s *LabelHandlerTestSuite) TestListTags_Success() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/tags", s.handler.ListTags)
s.Require().NoError(s.db.Create(&model.Tag{AccountID: s.account.ID, Name: "billing", Color: "#ff0000", Description: "Billing issues", ShowOnSidebar: labelBoolPtr(true)}).Error)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/tags", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var resp map[string][]map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &resp))
s.Require().Len(resp["payload"], 1)
assert.Equal(s.T(), "billing", resp["payload"][0]["title"])
assert.Equal(s.T(), "Billing issues", resp["payload"][0]["description"])
assert.Equal(s.T(), "#ff0000", resp["payload"][0]["color"])
assert.Equal(s.T(), true, resp["payload"][0]["show_on_sidebar"])
}
func (s *LabelHandlerTestSuite) TestCreateTag_BadRequest_EmptyBody() {
@@ -81,10 +97,31 @@ func (s *LabelHandlerTestSuite) TestCreateTag_BadRequest_EmptyBody() {
}
func (s *LabelHandlerTestSuite) TestCreateTag_Success() {
r := gin.New()
r.POST("/api/v1/accounts/:account_id/labels", s.handler.CreateTag)
body := map[string]interface{}{"label": map[string]interface{}{"title": "Priority", "description": "Hot queue", "color": "#FF0000", "show_on_sidebar": false}}
b, _ := json.Marshal(body)
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/labels", s.account.ID), bytes.NewBuffer(b))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var resp map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &resp))
assert.Equal(s.T(), "priority", resp["title"])
assert.Equal(s.T(), "Hot queue", resp["description"])
assert.Equal(s.T(), "#FF0000", resp["color"])
assert.Equal(s.T(), false, resp["show_on_sidebar"])
}
func (s *LabelHandlerTestSuite) TestCreateTag_RawNameCompatibility() {
r := gin.New()
r.POST("/api/v1/accounts/:account_id/tags", s.handler.CreateTag)
body := map[string]interface{}{"name": "priority", "color": "#FF0000"}
body := map[string]interface{}{"name": "legacy", "color": ""}
b, _ := json.Marshal(body)
w := httptest.NewRecorder()
@@ -92,7 +129,59 @@ func (s *LabelHandlerTestSuite) TestCreateTag_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)
var resp map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &resp))
assert.Equal(s.T(), "legacy", resp["title"])
assert.Equal(s.T(), "#1f93ff", resp["color"])
assert.Equal(s.T(), true, resp["show_on_sidebar"])
}
func (s *LabelHandlerTestSuite) TestUpdateTag_ChatwootPayloadAndAccountScope() {
r := gin.New()
r.PUT("/api/v1/accounts/:account_id/labels/:tag_id", s.handler.UpdateTag)
tag := &model.Tag{AccountID: s.account.ID, Name: "old", Color: "#000000", ShowOnSidebar: labelBoolPtr(true)}
s.Require().NoError(s.db.Create(tag).Error)
desc := "New description"
color := "#00ff00"
show := false
body := map[string]interface{}{"label": map[string]interface{}{"title": "New", "description": desc, "color": color, "show_on_sidebar": show}}
b, _ := json.Marshal(body)
w := httptest.NewRecorder()
req, _ := http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/%d/labels/%d", s.account.ID, tag.ID), bytes.NewBuffer(b))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var resp map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &resp))
assert.Equal(s.T(), "new", resp["title"])
assert.Equal(s.T(), desc, resp["description"])
assert.Equal(s.T(), color, resp["color"])
assert.Equal(s.T(), show, resp["show_on_sidebar"])
}
func (s *LabelHandlerTestSuite) TestDeleteTag_ReturnsOKAndRemovesAssociations() {
r := gin.New()
r.DELETE("/api/v1/accounts/:account_id/labels/:tag_id", s.handler.DeleteTag)
tag := &model.Tag{AccountID: s.account.ID, Name: "old", Color: "#000000", ShowOnSidebar: labelBoolPtr(true)}
s.Require().NoError(s.db.Create(tag).Error)
s.Require().NoError(s.db.Create(&model.ConversationLabel{AccountID: s.account.ID, ConversationID: 10, TagID: tag.ID}).Error)
s.Require().NoError(s.db.Create(&model.ContactLabel{AccountID: s.account.ID, ContactID: 20, TagID: tag.ID}).Error)
w := httptest.NewRecorder()
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/labels/%d", s.account.ID, tag.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var convCount int64
s.Require().NoError(s.db.Model(&model.ConversationLabel{}).Where("tag_id = ?", tag.ID).Count(&convCount).Error)
assert.Equal(s.T(), int64(0), convCount)
var contactCount int64
s.Require().NoError(s.db.Model(&model.ContactLabel{}).Where("tag_id = ?", tag.ID).Count(&contactCount).Error)
assert.Equal(s.T(), int64(0), contactCount)
}
func (s *LabelHandlerTestSuite) TestGetTag_BadRequest_InvalidID() {
@@ -196,4 +285,4 @@ func (s *LabelHandlerTestSuite) TestBatchRemoveLabel_BadRequest_InvalidAccountID
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
}
}