feat(labels): align chatwoot label payloads
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
+10
-8
@@ -10,15 +10,17 @@ import (
|
||||
// Reference: Chatwoot Tag + Taggings merged + P2B M4 spec
|
||||
// Each tag belongs to an account and has a unique name within that account.
|
||||
type Tag struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
AccountID uint `gorm:"not null;uniqueIndex:idx_tag_account_name" json:"account_id"`
|
||||
Name string `gorm:"size:255;not null;uniqueIndex:idx_tag_account_name" json:"name"`
|
||||
Color string `gorm:"size:50" json:"color,omitempty"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
AccountID uint `gorm:"not null;uniqueIndex:idx_tag_account_name" json:"account_id"`
|
||||
Name string `gorm:"size:255;not null;uniqueIndex:idx_tag_account_name" json:"name"`
|
||||
Color string `gorm:"size:50;not null;default:#1f93ff" json:"color,omitempty"`
|
||||
Description string `gorm:"type:text" json:"description,omitempty"`
|
||||
ShowOnSidebar *bool `json:"show_on_sidebar"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
|
||||
|
||||
Account Account `gorm:"foreignKey:AccountID" json:"account,omitempty"`
|
||||
}
|
||||
|
||||
func (Tag) TableName() string { return "tags" }
|
||||
func (Tag) TableName() string { return "tags" }
|
||||
|
||||
@@ -2,6 +2,7 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"gorm.io/gorm"
|
||||
@@ -30,6 +31,15 @@ func (r *TagRepo) GetByID(ctx context.Context, id uint) (*model.Tag, error) {
|
||||
return &tag, nil
|
||||
}
|
||||
|
||||
// GetByIDAndAccountID retrieves a tag scoped to an account.
|
||||
func (r *TagRepo) GetByIDAndAccountID(ctx context.Context, accountID, id uint) (*model.Tag, error) {
|
||||
var tag model.Tag
|
||||
if err := r.db.WithContext(ctx).Where("account_id = ?", accountID).First(&tag, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tag, nil
|
||||
}
|
||||
|
||||
// Update saves changes to an existing tag.
|
||||
func (r *TagRepo) Update(ctx context.Context, tag *model.Tag) error {
|
||||
return r.db.WithContext(ctx).Save(tag).Error
|
||||
@@ -40,6 +50,29 @@ func (r *TagRepo) Delete(ctx context.Context, id uint) error {
|
||||
return r.db.WithContext(ctx).Delete(&model.Tag{}, id).Error
|
||||
}
|
||||
|
||||
// DeleteWithAssociations removes a tag and the local association rows that point to it.
|
||||
func (r *TagRepo) DeleteWithAssociations(ctx context.Context, tag *model.Tag) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Where("account_id = ? AND tag_id = ?", tag.AccountID, tag.ID).Delete(&model.ConversationLabel{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Where("account_id = ? AND tag_id = ?", tag.AccountID, tag.ID).Delete(&model.ContactLabel{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.updateConversationLabelText(ctx, tx, tag.AccountID, tag.Name, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Delete(&model.Tag{}, tag.ID).Error
|
||||
})
|
||||
}
|
||||
|
||||
// RenameConversationLabelText keeps the legacy conversations.labels field aligned with label title changes.
|
||||
func (r *TagRepo) RenameConversationLabelText(ctx context.Context, accountID uint, oldName, newName string) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
return r.updateConversationLabelText(ctx, tx, accountID, oldName, newName)
|
||||
})
|
||||
}
|
||||
|
||||
// FindByAccountID returns all tags for an account, ordered by name.
|
||||
func (r *TagRepo) FindByAccountID(ctx context.Context, accountID uint) ([]model.Tag, error) {
|
||||
var tags []model.Tag
|
||||
@@ -75,6 +108,61 @@ func (r *TagRepo) FindByNameAndAccountID(ctx context.Context, accountID uint, na
|
||||
return &tag, nil
|
||||
}
|
||||
|
||||
func (r *TagRepo) updateConversationLabelText(ctx context.Context, tx *gorm.DB, accountID uint, oldName, newName string) error {
|
||||
oldName = strings.TrimSpace(oldName)
|
||||
newName = strings.TrimSpace(newName)
|
||||
if oldName == "" || oldName == newName {
|
||||
return nil
|
||||
}
|
||||
|
||||
var conversations []model.Conversation
|
||||
if err := tx.WithContext(ctx).
|
||||
Where("account_id = ? AND labels IS NOT NULL AND labels != ''", accountID).
|
||||
Find(&conversations).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, conversation := range conversations {
|
||||
updated, changed := replaceLabelName(conversation.Labels, oldName, newName)
|
||||
if !changed {
|
||||
continue
|
||||
}
|
||||
if err := tx.Model(&model.Conversation{}).Where("id = ?", conversation.ID).Update("labels", updated).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func replaceLabelName(labels, oldName, newName string) (string, bool) {
|
||||
parts := strings.Split(labels, ",")
|
||||
seen := map[string]struct{}{}
|
||||
changed := false
|
||||
result := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
label := strings.TrimSpace(part)
|
||||
if label == "" {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(label, oldName) {
|
||||
changed = true
|
||||
label = newName
|
||||
}
|
||||
if label == "" {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(label)
|
||||
if _, ok := seen[key]; ok {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
result = append(result, label)
|
||||
}
|
||||
if !changed {
|
||||
return labels, false
|
||||
}
|
||||
return strings.Join(result, ","), true
|
||||
}
|
||||
|
||||
// FindByIDs retrieves multiple tags by their IDs.
|
||||
func (r *TagRepo) FindByIDs(ctx context.Context, ids []uint) ([]model.Tag, error) {
|
||||
var tags []model.Tag
|
||||
@@ -82,4 +170,4 @@ func (r *TagRepo) FindByIDs(ctx context.Context, ids []uint) ([]model.Tag, error
|
||||
return nil, err
|
||||
}
|
||||
return tags, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
@@ -20,28 +21,52 @@ func NewTagService(repo *repository.TagRepo) *TagService {
|
||||
|
||||
// CreateTagRequest is the DTO for creating a tag.
|
||||
type CreateTagRequest struct {
|
||||
Name string `json:"name" validate:"required,min=1,max=255"`
|
||||
Color string `json:"color"`
|
||||
Name string `json:"name" validate:"omitempty,min=1,max=255"`
|
||||
Title string `json:"title" validate:"omitempty,min=1,max=255"`
|
||||
Description string `json:"description"`
|
||||
Color string `json:"color"`
|
||||
ShowOnSidebar *bool `json:"show_on_sidebar"`
|
||||
}
|
||||
|
||||
// UpdateTagRequest is the DTO for updating a tag.
|
||||
type UpdateTagRequest struct {
|
||||
Name string `json:"name" validate:"omitempty,min=1,max=255"`
|
||||
Color string `json:"color"`
|
||||
Name string `json:"name" validate:"omitempty,min=1,max=255"`
|
||||
Title string `json:"title" validate:"omitempty,min=1,max=255"`
|
||||
Description *string `json:"description"`
|
||||
Color *string `json:"color"`
|
||||
ShowOnSidebar *bool `json:"show_on_sidebar"`
|
||||
}
|
||||
|
||||
// Create creates a new tag for the given account.
|
||||
func (s *TagService) Create(ctx context.Context, accountID uint, req *CreateTagRequest) (*model.Tag, error) {
|
||||
name := normalizeLabelTitle(req.Title)
|
||||
if name == "" {
|
||||
name = normalizeLabelTitle(req.Name)
|
||||
}
|
||||
if name == "" {
|
||||
return nil, errors.New("label title is required")
|
||||
}
|
||||
color := strings.TrimSpace(req.Color)
|
||||
if color == "" {
|
||||
color = "#1f93ff"
|
||||
}
|
||||
showOnSidebar := true
|
||||
if req.ShowOnSidebar != nil {
|
||||
showOnSidebar = *req.ShowOnSidebar
|
||||
}
|
||||
|
||||
// Check for duplicate name within account
|
||||
existing, err := s.repo.FindByNameAndAccountID(ctx, accountID, req.Name)
|
||||
existing, err := s.repo.FindByNameAndAccountID(ctx, accountID, name)
|
||||
if err == nil && existing != nil {
|
||||
return nil, errors.New("tag name already exists in this account")
|
||||
}
|
||||
|
||||
tag := &model.Tag{
|
||||
AccountID: accountID,
|
||||
Name: req.Name,
|
||||
Color: req.Color,
|
||||
AccountID: accountID,
|
||||
Name: name,
|
||||
Description: req.Description,
|
||||
Color: color,
|
||||
ShowOnSidebar: &showOnSidebar,
|
||||
}
|
||||
if err := s.repo.Create(ctx, tag); err != nil {
|
||||
applogger.L().Errorf("Create tag: %v", err)
|
||||
@@ -59,6 +84,15 @@ func (s *TagService) GetByID(ctx context.Context, id uint) (*model.Tag, error) {
|
||||
return tag, nil
|
||||
}
|
||||
|
||||
// GetByIDAndAccountID retrieves a tag by ID scoped to an account.
|
||||
func (s *TagService) GetByIDAndAccountID(ctx context.Context, accountID, id uint) (*model.Tag, error) {
|
||||
tag, err := s.repo.GetByIDAndAccountID(ctx, accountID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tag, nil
|
||||
}
|
||||
|
||||
// Update modifies an existing tag.
|
||||
func (s *TagService) Update(ctx context.Context, id uint, req *UpdateTagRequest) (*model.Tag, error) {
|
||||
tag, err := s.repo.GetByID(ctx, id)
|
||||
@@ -66,34 +100,62 @@ func (s *TagService) Update(ctx context.Context, id uint, req *UpdateTagRequest)
|
||||
return nil, errors.New("tag not found")
|
||||
}
|
||||
|
||||
if req.Name != "" {
|
||||
oldName := tag.Name
|
||||
name := normalizeLabelTitle(req.Title)
|
||||
if name == "" {
|
||||
name = normalizeLabelTitle(req.Name)
|
||||
}
|
||||
if name != "" {
|
||||
// Check for duplicate name within account (excluding current tag)
|
||||
existing, err := s.repo.FindByNameAndAccountID(ctx, tag.AccountID, req.Name)
|
||||
existing, err := s.repo.FindByNameAndAccountID(ctx, tag.AccountID, name)
|
||||
if err == nil && existing != nil && existing.ID != id {
|
||||
return nil, errors.New("tag name already exists in this account")
|
||||
}
|
||||
tag.Name = req.Name
|
||||
tag.Name = name
|
||||
}
|
||||
if req.Color != "" {
|
||||
tag.Color = req.Color
|
||||
if req.Color != nil {
|
||||
color := strings.TrimSpace(*req.Color)
|
||||
if color == "" {
|
||||
color = "#1f93ff"
|
||||
}
|
||||
tag.Color = color
|
||||
}
|
||||
if req.Description != nil {
|
||||
tag.Description = *req.Description
|
||||
}
|
||||
if req.ShowOnSidebar != nil {
|
||||
tag.ShowOnSidebar = req.ShowOnSidebar
|
||||
}
|
||||
|
||||
if err := s.repo.Update(ctx, tag); err != nil {
|
||||
applogger.L().Errorf("Update tag: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
if oldName != tag.Name {
|
||||
if err := s.repo.RenameConversationLabelText(ctx, tag.AccountID, oldName, tag.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return tag, nil
|
||||
}
|
||||
|
||||
// Delete removes a tag by ID.
|
||||
func (s *TagService) Delete(ctx context.Context, id uint) error {
|
||||
if err := s.repo.Delete(ctx, id); err != nil {
|
||||
tag, err := s.repo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.repo.DeleteWithAssociations(ctx, tag); err != nil {
|
||||
applogger.L().Errorf("Delete tag: %v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeLabelTitle(title string) string {
|
||||
return strings.ToLower(strings.TrimSpace(title))
|
||||
}
|
||||
|
||||
// List returns all tags for an account.
|
||||
func (s *TagService) List(ctx context.Context, accountID uint) ([]model.Tag, error) {
|
||||
tags, err := s.repo.FindByAccountID(ctx, accountID)
|
||||
@@ -113,4 +175,4 @@ func (s *TagService) ListPaginated(ctx context.Context, accountID uint, page, pe
|
||||
return nil, 0, err
|
||||
}
|
||||
return tags, count, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func newTagServiceTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&model.Account{}, &model.Tag{}, &model.Conversation{}, &model.ConversationLabel{}, &model.ContactLabel{}))
|
||||
return db
|
||||
}
|
||||
|
||||
func tagBoolPtr(v bool) *bool { return &v }
|
||||
|
||||
func TestTagService_CreateNormalizesChatwootLabelFields(t *testing.T) {
|
||||
db := newTagServiceTestDB(t)
|
||||
svc := NewTagService(repository.NewTagRepo(db))
|
||||
show := false
|
||||
|
||||
tag, err := svc.Create(context.Background(), 1, &CreateTagRequest{
|
||||
Title: "Priority",
|
||||
Description: "Hot queue",
|
||||
Color: "",
|
||||
ShowOnSidebar: &show,
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "priority", tag.Name)
|
||||
require.Equal(t, "Hot queue", tag.Description)
|
||||
require.Equal(t, "#1f93ff", tag.Color)
|
||||
require.NotNil(t, tag.ShowOnSidebar)
|
||||
require.False(t, *tag.ShowOnSidebar)
|
||||
}
|
||||
|
||||
func TestTagService_UpdateRenamesLegacyConversationLabelText(t *testing.T) {
|
||||
db := newTagServiceTestDB(t)
|
||||
svc := NewTagService(repository.NewTagRepo(db))
|
||||
tag := &model.Tag{AccountID: 1, Name: "old", Color: "#000000", ShowOnSidebar: tagBoolPtr(true)}
|
||||
require.NoError(t, db.Create(tag).Error)
|
||||
conversation := &model.Conversation{AccountID: 1, InboxID: 1, ContactID: 1, ChannelType: "Channel::WebWidget", Channel: "web_widget", Labels: "old,keep"}
|
||||
require.NoError(t, db.Create(conversation).Error)
|
||||
desc := "Renamed"
|
||||
color := "#123456"
|
||||
|
||||
updated, err := svc.Update(context.Background(), tag.ID, &UpdateTagRequest{
|
||||
Title: "New",
|
||||
Description: &desc,
|
||||
Color: &color,
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "new", updated.Name)
|
||||
require.Equal(t, desc, updated.Description)
|
||||
require.Equal(t, color, updated.Color)
|
||||
require.NoError(t, db.First(conversation, conversation.ID).Error)
|
||||
require.Equal(t, "new,keep", conversation.Labels)
|
||||
}
|
||||
|
||||
func TestTagService_DeleteRemovesAssociationsAndLegacyConversationText(t *testing.T) {
|
||||
db := newTagServiceTestDB(t)
|
||||
svc := NewTagService(repository.NewTagRepo(db))
|
||||
tag := &model.Tag{AccountID: 1, Name: "old", Color: "#000000", ShowOnSidebar: tagBoolPtr(true)}
|
||||
require.NoError(t, db.Create(tag).Error)
|
||||
conversation := &model.Conversation{AccountID: 1, InboxID: 1, ContactID: 1, ChannelType: "Channel::WebWidget", Channel: "web_widget", Labels: "old,keep"}
|
||||
require.NoError(t, db.Create(conversation).Error)
|
||||
require.NoError(t, db.Create(&model.ConversationLabel{AccountID: 1, ConversationID: conversation.ID, TagID: tag.ID}).Error)
|
||||
require.NoError(t, db.Create(&model.ContactLabel{AccountID: 1, ContactID: 10, TagID: tag.ID}).Error)
|
||||
|
||||
require.NoError(t, svc.Delete(context.Background(), tag.ID))
|
||||
|
||||
var convLabelCount int64
|
||||
require.NoError(t, db.Model(&model.ConversationLabel{}).Where("tag_id = ?", tag.ID).Count(&convLabelCount).Error)
|
||||
require.Equal(t, int64(0), convLabelCount)
|
||||
var contactLabelCount int64
|
||||
require.NoError(t, db.Model(&model.ContactLabel{}).Where("tag_id = ?", tag.ID).Count(&contactLabelCount).Error)
|
||||
require.Equal(t, int64(0), contactLabelCount)
|
||||
require.NoError(t, db.First(conversation, conversation.ID).Error)
|
||||
require.Equal(t, "keep", conversation.Labels)
|
||||
}
|
||||
Reference in New Issue
Block a user