feat(campaigns): align chatwoot payloads
This commit is contained in:
@@ -45,6 +45,9 @@ type Campaign struct {
|
||||
ScheduledAt *time.Time `gorm:"index" json:"scheduled_at,omitempty"`
|
||||
Enabled bool `gorm:"default:true" json:"enabled"`
|
||||
TriggerOnlyDuringBusinessHours bool `gorm:"default:false" json:"trigger_only_during_business_hours"`
|
||||
|
||||
Inbox model.Inbox `gorm:"foreignKey:InboxID" json:"-"`
|
||||
Sender *model.User `gorm:"foreignKey:SenderID" json:"-"`
|
||||
}
|
||||
|
||||
func (Campaign) TableName() string { return "campaigns" }
|
||||
|
||||
@@ -22,6 +22,14 @@ func NewCampaignService(db *gorm.DB) *CampaignService {
|
||||
|
||||
// Create creates a new campaign.
|
||||
func (s *CampaignService) Create(ctx context.Context, campaign *Campaign) error {
|
||||
if campaign.DisplayID == 0 {
|
||||
var next uint
|
||||
if err := s.db.WithContext(ctx).Model(&Campaign{}).
|
||||
Select("COALESCE(MAX(display_id), 0) + 1").Scan(&next).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
campaign.DisplayID = next
|
||||
}
|
||||
return s.db.WithContext(ctx).Create(campaign).Error
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/campaign"
|
||||
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
"github.com/gochat/gochat/pkg/pagination"
|
||||
"github.com/gochat/gochat/pkg/response"
|
||||
)
|
||||
|
||||
@@ -32,15 +34,14 @@ func (h *CampaignHandler) List(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
pg := pagination.Parse(c)
|
||||
campaigns, total, err := h.svc.List(c.Request.Context(), accountID, pg.Offset, pg.PerPage)
|
||||
campaigns, _, err := h.svc.List(c.Request.Context(), accountID, 0, 0)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("List campaigns for account %d: %v", accountID, err)
|
||||
handleServiceError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OKWithMeta(c, campaigns, pg.Page, pg.PerPage, total)
|
||||
c.JSON(http.StatusOK, serializeCampaigns(campaigns, accountID))
|
||||
}
|
||||
|
||||
// Get returns a single campaign by ID.
|
||||
@@ -65,7 +66,7 @@ func (h *CampaignHandler) Get(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, campaign)
|
||||
c.JSON(http.StatusOK, serializeCampaign(campaign, accountID))
|
||||
}
|
||||
|
||||
// Create creates a new campaign within an account.
|
||||
@@ -94,7 +95,7 @@ func (h *CampaignHandler) Create(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.Created(c, campaign)
|
||||
c.JSON(http.StatusOK, serializeCampaign(campaign, accountID))
|
||||
}
|
||||
|
||||
// Update updates an existing campaign.
|
||||
@@ -129,7 +130,7 @@ func (h *CampaignHandler) Update(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, campaign)
|
||||
c.JSON(http.StatusOK, serializeCampaign(campaign, accountID))
|
||||
}
|
||||
|
||||
// Delete soft-deletes a campaign.
|
||||
@@ -153,7 +154,7 @@ func (h *CampaignHandler) Delete(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.NoContent(c)
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
// Start triggers a campaign execution.
|
||||
@@ -180,6 +181,68 @@ func (h *CampaignHandler) Start(c *gin.Context) {
|
||||
response.OK(c, gin.H{"message": "campaign triggered successfully"})
|
||||
}
|
||||
|
||||
func serializeCampaigns(campaigns []campaign.Campaign, accountID uint) []map[string]any {
|
||||
payload := make([]map[string]any, 0, len(campaigns))
|
||||
for i := range campaigns {
|
||||
payload = append(payload, serializeCampaign(&campaigns[i], accountID))
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
func serializeCampaign(item *campaign.Campaign, accountID uint) map[string]any {
|
||||
if item == nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
id := item.DisplayID
|
||||
if id == 0 {
|
||||
id = item.ID
|
||||
}
|
||||
payload := map[string]any{
|
||||
"id": id,
|
||||
"title": item.Title,
|
||||
"description": item.Description,
|
||||
"account_id": item.AccountID,
|
||||
"inbox": nil,
|
||||
"sender": nil,
|
||||
"message": item.Message,
|
||||
"template_params": campaignJSONValue(item.TemplateParams),
|
||||
"campaign_status": item.CampaignStatus,
|
||||
"enabled": item.Enabled,
|
||||
"campaign_type": item.CampaignType,
|
||||
"trigger_rules": campaignJSONValue(item.TriggerRules),
|
||||
"trigger_only_during_business_hours": item.TriggerOnlyDuringBusinessHours,
|
||||
"created_at": item.CreatedAt,
|
||||
"updated_at": item.UpdatedAt,
|
||||
}
|
||||
if item.Inbox.ID != 0 {
|
||||
payload["inbox"] = serializeInbox(&item.Inbox)
|
||||
}
|
||||
if item.Sender != nil && item.Sender.ID != 0 {
|
||||
payload["sender"] = serializeAgentUser(item.Sender, accountID, "", "", false, 0)
|
||||
}
|
||||
if item.CampaignType == campaign.CampaignTypeOneOff {
|
||||
if item.ScheduledAt != nil {
|
||||
payload["scheduled_at"] = item.ScheduledAt.Unix()
|
||||
} else {
|
||||
payload["scheduled_at"] = nil
|
||||
}
|
||||
payload["audience"] = campaignJSONValue(item.Audience)
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
func campaignJSONValue(raw string) any {
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
if trimmed == "" {
|
||||
return map[string]any{}
|
||||
}
|
||||
var value any
|
||||
if err := json.Unmarshal([]byte(trimmed), &value); err != nil {
|
||||
return trimmed
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// Stop marks a campaign as completed.
|
||||
// POST /api/v1/accounts/:id/campaigns/:campaign_id/stop
|
||||
func (h *CampaignHandler) Stop(c *gin.Context) {
|
||||
|
||||
@@ -83,6 +83,7 @@ func (s *CampaignHandlerTestSuite) SetupSuite() {
|
||||
campaigns.GET("", s.handler.List)
|
||||
campaigns.GET("/:campaign_id", s.handler.Get)
|
||||
campaigns.POST("", s.handler.Create)
|
||||
campaigns.PATCH("/:campaign_id", s.handler.Update)
|
||||
campaigns.PUT("/:campaign_id", s.handler.Update)
|
||||
campaigns.DELETE("/:campaign_id", s.handler.Delete)
|
||||
campaigns.POST("/:campaign_id/start", s.handler.Start)
|
||||
@@ -171,19 +172,12 @@ func (s *CampaignHandlerTestSuite) TestList_Success() {
|
||||
|
||||
s.Equal(http.StatusOK, w.Code)
|
||||
|
||||
var resp struct {
|
||||
Success bool `json:"success"`
|
||||
Data []campaign.Campaign `json:"data"`
|
||||
Meta struct {
|
||||
Page int `json:"page"`
|
||||
PerPage int `json:"per_page"`
|
||||
TotalCount int64 `json:"total_count"`
|
||||
} `json:"meta"`
|
||||
}
|
||||
var resp []map[string]interface{}
|
||||
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &resp))
|
||||
s.True(resp.Success)
|
||||
s.Len(resp.Data, 2)
|
||||
s.Equal(int64(2), resp.Meta.TotalCount)
|
||||
s.Len(resp, 2)
|
||||
s.NotContains(resp[0], "success")
|
||||
s.NotContains(resp[0], "data")
|
||||
s.Contains(resp[0], "inbox")
|
||||
}
|
||||
|
||||
func (s *CampaignHandlerTestSuite) TestList_Empty() {
|
||||
@@ -193,17 +187,9 @@ func (s *CampaignHandlerTestSuite) TestList_Empty() {
|
||||
|
||||
s.Equal(http.StatusOK, w.Code)
|
||||
|
||||
var resp struct {
|
||||
Success bool `json:"success"`
|
||||
Data []campaign.Campaign `json:"data"`
|
||||
Meta struct {
|
||||
TotalCount int64 `json:"total_count"`
|
||||
} `json:"meta"`
|
||||
}
|
||||
var resp []map[string]interface{}
|
||||
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &resp))
|
||||
s.True(resp.Success)
|
||||
s.Empty(resp.Data)
|
||||
s.Equal(int64(0), resp.Meta.TotalCount)
|
||||
s.Empty(resp)
|
||||
}
|
||||
|
||||
func (s *CampaignHandlerTestSuite) TestList_Unauthorized() {
|
||||
@@ -225,19 +211,18 @@ func (s *CampaignHandlerTestSuite) TestGet_Success() {
|
||||
c := s.seedCampaign("GetTest Campaign", "Test message", "ongoing")
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("GET", s.accountURL()+"/"+strconv.FormatUint(uint64(c.ID), 10), nil)
|
||||
req, _ := http.NewRequest("GET", s.accountURL()+"/"+strconv.FormatUint(uint64(c.DisplayID), 10), nil)
|
||||
s.router.ServeHTTP(w, req)
|
||||
|
||||
s.Equal(http.StatusOK, w.Code)
|
||||
|
||||
var resp struct {
|
||||
Success bool `json:"success"`
|
||||
Data campaign.Campaign `json:"data"`
|
||||
}
|
||||
var resp map[string]interface{}
|
||||
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &resp))
|
||||
s.True(resp.Success)
|
||||
s.Equal(c.Title, resp.Data.Title)
|
||||
s.Equal(c.ID, resp.Data.ID)
|
||||
s.NotContains(resp, "success")
|
||||
s.NotContains(resp, "data")
|
||||
s.Equal(c.Title, resp["title"])
|
||||
s.Equal(float64(c.DisplayID), resp["id"])
|
||||
s.Contains(resp, "inbox")
|
||||
}
|
||||
|
||||
func (s *CampaignHandlerTestSuite) TestGet_NotFound() {
|
||||
@@ -272,11 +257,14 @@ func (s *CampaignHandlerTestSuite) TestGet_Unauthorized() {
|
||||
|
||||
func (s *CampaignHandlerTestSuite) TestCreate_Success() {
|
||||
body := map[string]interface{}{
|
||||
"inbox_id": s.inbox.ID,
|
||||
"title": "New Campaign",
|
||||
"message": "Hello from campaign",
|
||||
"campaign_type": "ongoing",
|
||||
"enabled": true,
|
||||
"inbox_id": s.inbox.ID,
|
||||
"title": "New Campaign",
|
||||
"message": "Hello from campaign",
|
||||
"campaign_type": "one_off",
|
||||
"enabled": true,
|
||||
"audience": []map[string]interface{}{{"type": "Label", "id": 1}},
|
||||
"trigger_rules": map[string]interface{}{"url": "https://example.com"},
|
||||
"template_params": map[string]interface{}{"name": "value"},
|
||||
}
|
||||
bodyBytes := marshalNested("campaign", body)
|
||||
|
||||
@@ -285,17 +273,17 @@ func (s *CampaignHandlerTestSuite) TestCreate_Success() {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
s.router.ServeHTTP(w, req)
|
||||
|
||||
s.Equal(http.StatusCreated, w.Code)
|
||||
s.Equal(http.StatusOK, w.Code)
|
||||
|
||||
var resp struct {
|
||||
Success bool `json:"success"`
|
||||
Data campaign.Campaign `json:"data"`
|
||||
}
|
||||
var resp map[string]interface{}
|
||||
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &resp))
|
||||
s.True(resp.Success)
|
||||
s.Equal("New Campaign", resp.Data.Title)
|
||||
s.Equal(s.account.ID, resp.Data.AccountID)
|
||||
s.Equal(s.inbox.ID, resp.Data.InboxID)
|
||||
s.NotContains(resp, "success")
|
||||
s.NotContains(resp, "data")
|
||||
s.Equal("New Campaign", resp["title"])
|
||||
s.Equal(float64(s.account.ID), resp["account_id"])
|
||||
s.Greater(resp["id"].(float64), float64(0))
|
||||
s.Contains(resp, "audience")
|
||||
s.Contains(resp, "template_params")
|
||||
}
|
||||
|
||||
func (s *CampaignHandlerTestSuite) TestCreate_ValidationError() {
|
||||
@@ -355,19 +343,16 @@ func (s *CampaignHandlerTestSuite) TestUpdate_Success() {
|
||||
bodyBytes := marshalNested("campaign", body)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("PUT", s.accountURL()+"/"+strconv.FormatUint(uint64(c.ID), 10), bytes.NewReader(bodyBytes))
|
||||
req, _ := http.NewRequest("PATCH", s.accountURL()+"/"+strconv.FormatUint(uint64(c.DisplayID), 10), bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
s.router.ServeHTTP(w, req)
|
||||
|
||||
s.Equal(http.StatusOK, w.Code)
|
||||
|
||||
var resp struct {
|
||||
Success bool `json:"success"`
|
||||
Data campaign.Campaign `json:"data"`
|
||||
}
|
||||
var resp map[string]interface{}
|
||||
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &resp))
|
||||
s.True(resp.Success)
|
||||
s.Equal("Updated Title", resp.Data.Title)
|
||||
s.NotContains(resp, "success")
|
||||
s.Equal("Updated Title", resp["title"])
|
||||
}
|
||||
|
||||
func (s *CampaignHandlerTestSuite) TestUpdate_NotFound() {
|
||||
@@ -423,10 +408,10 @@ func (s *CampaignHandlerTestSuite) TestDelete_Success() {
|
||||
c := s.seedCampaign("DeleteTest Campaign", "Test message", "ongoing")
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("DELETE", s.accountURL()+"/"+strconv.FormatUint(uint64(c.ID), 10), nil)
|
||||
req, _ := http.NewRequest("DELETE", s.accountURL()+"/"+strconv.FormatUint(uint64(c.DisplayID), 10), nil)
|
||||
s.router.ServeHTTP(w, req)
|
||||
|
||||
s.Equal(http.StatusNoContent, w.Code)
|
||||
s.Equal(http.StatusOK, w.Code)
|
||||
|
||||
// Verify the campaign is soft-deleted
|
||||
var count int64
|
||||
@@ -439,9 +424,7 @@ func (s *CampaignHandlerTestSuite) TestDelete_NotFound() {
|
||||
req, _ := http.NewRequest("DELETE", s.accountURL()+"/99999", nil)
|
||||
s.router.ServeHTTP(w, req)
|
||||
|
||||
// GORM soft-delete on a non-existent ID succeeds silently (0 rows affected is not an error),
|
||||
// so the handler returns 204 No Content rather than 404/500.
|
||||
s.Equal(http.StatusNoContent, w.Code)
|
||||
s.Equal(http.StatusNotFound, w.Code)
|
||||
}
|
||||
|
||||
func (s *CampaignHandlerTestSuite) TestDelete_InvalidID() {
|
||||
@@ -595,11 +578,11 @@ func (s *CampaignHandlerTestSuite) TestLifecycle_StartThenStop() {
|
||||
func (s *CampaignHandlerTestSuite) TestCRUD_FullLifecycle() {
|
||||
// Create
|
||||
createBody := map[string]interface{}{
|
||||
"inbox_id": s.inbox.ID,
|
||||
"title": "Lifecycle Campaign",
|
||||
"message": "Test lifecycle message",
|
||||
"campaign_type": "one_off",
|
||||
"enabled": true,
|
||||
"inbox_id": s.inbox.ID,
|
||||
"title": "Lifecycle Campaign",
|
||||
"message": "Test lifecycle message",
|
||||
"campaign_type": "one_off",
|
||||
"enabled": true,
|
||||
}
|
||||
createBytes := marshalNested("campaign", createBody)
|
||||
|
||||
@@ -607,15 +590,11 @@ func (s *CampaignHandlerTestSuite) TestCRUD_FullLifecycle() {
|
||||
req, _ := http.NewRequest("POST", s.accountURL(), bytes.NewReader(createBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
s.router.ServeHTTP(w, req)
|
||||
s.Equal(http.StatusCreated, w.Code)
|
||||
s.Equal(http.StatusOK, w.Code)
|
||||
|
||||
var createResp struct {
|
||||
Success bool `json:"success"`
|
||||
Data campaign.Campaign `json:"data"`
|
||||
}
|
||||
var createResp map[string]interface{}
|
||||
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &createResp))
|
||||
s.True(createResp.Success)
|
||||
createdID := createResp.Data.ID
|
||||
createdID := uint(createResp["id"].(float64))
|
||||
|
||||
// Get
|
||||
w = httptest.NewRecorder()
|
||||
@@ -623,12 +602,9 @@ func (s *CampaignHandlerTestSuite) TestCRUD_FullLifecycle() {
|
||||
s.router.ServeHTTP(w, req)
|
||||
s.Equal(http.StatusOK, w.Code)
|
||||
|
||||
var getResp struct {
|
||||
Success bool `json:"success"`
|
||||
Data campaign.Campaign `json:"data"`
|
||||
}
|
||||
var getResp map[string]interface{}
|
||||
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &getResp))
|
||||
s.Equal("Lifecycle Campaign", getResp.Data.Title)
|
||||
s.Equal("Lifecycle Campaign", getResp["title"])
|
||||
|
||||
// Update
|
||||
updateBody := map[string]interface{}{
|
||||
@@ -638,17 +614,14 @@ func (s *CampaignHandlerTestSuite) TestCRUD_FullLifecycle() {
|
||||
updateBytes := marshalNested("campaign", updateBody)
|
||||
|
||||
w = httptest.NewRecorder()
|
||||
req, _ = http.NewRequest("PUT", s.accountURL()+"/"+strconv.FormatUint(uint64(createdID), 10), bytes.NewReader(updateBytes))
|
||||
req, _ = http.NewRequest("PATCH", s.accountURL()+"/"+strconv.FormatUint(uint64(createdID), 10), bytes.NewReader(updateBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
s.router.ServeHTTP(w, req)
|
||||
s.Equal(http.StatusOK, w.Code)
|
||||
|
||||
var updateResp struct {
|
||||
Success bool `json:"success"`
|
||||
Data campaign.Campaign `json:"data"`
|
||||
}
|
||||
var updateResp map[string]interface{}
|
||||
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &updateResp))
|
||||
s.Equal("Updated Lifecycle", updateResp.Data.Title)
|
||||
s.Equal("Updated Lifecycle", updateResp["title"])
|
||||
|
||||
// List (should include our campaign)
|
||||
w = httptest.NewRecorder()
|
||||
@@ -656,22 +629,15 @@ func (s *CampaignHandlerTestSuite) TestCRUD_FullLifecycle() {
|
||||
s.router.ServeHTTP(w, req)
|
||||
s.Equal(http.StatusOK, w.Code)
|
||||
|
||||
var listResp struct {
|
||||
Success bool `json:"success"`
|
||||
Data []campaign.Campaign `json:"data"`
|
||||
Meta struct {
|
||||
TotalCount int64 `json:"total_count"`
|
||||
} `json:"meta"`
|
||||
}
|
||||
var listResp []map[string]interface{}
|
||||
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &listResp))
|
||||
s.True(listResp.Success)
|
||||
s.GreaterOrEqual(int64(len(listResp.Data)), int64(1))
|
||||
s.GreaterOrEqual(len(listResp), 1)
|
||||
|
||||
// Delete
|
||||
w = httptest.NewRecorder()
|
||||
req, _ = http.NewRequest("DELETE", s.accountURL()+"/"+strconv.FormatUint(uint64(createdID), 10), nil)
|
||||
s.router.ServeHTTP(w, req)
|
||||
s.Equal(http.StatusNoContent, w.Code)
|
||||
s.Equal(http.StatusOK, w.Code)
|
||||
|
||||
// Get after delete → should be not found (soft delete)
|
||||
w = httptest.NewRecorder()
|
||||
@@ -718,4 +684,4 @@ func (s *CampaignHandlerTestSuite) TestGet_DifferentAccount() {
|
||||
|
||||
func TestCampaignHandlerTestSuite(t *testing.T) {
|
||||
suite.Run(t, new(CampaignHandlerTestSuite))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,14 @@ func NewCampaignRepo(db *gorm.DB) *CampaignRepo {
|
||||
|
||||
// Create creates a new campaign.
|
||||
func (r *CampaignRepo) Create(ctx context.Context, c *campaign.Campaign) error {
|
||||
if c.DisplayID == 0 {
|
||||
var next uint
|
||||
if err := r.db.WithContext(ctx).Model(&campaign.Campaign{}).
|
||||
Select("COALESCE(MAX(display_id), 0) + 1").Scan(&next).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
c.DisplayID = next
|
||||
}
|
||||
return r.db.WithContext(ctx).Create(c).Error
|
||||
}
|
||||
|
||||
@@ -35,9 +43,19 @@ func (r *CampaignRepo) FindByID(ctx context.Context, id uint) (*campaign.Campaig
|
||||
|
||||
// FindByIDAndAccount retrieves a campaign scoped to an account.
|
||||
func (r *CampaignRepo) FindByIDAndAccount(ctx context.Context, id, accountID uint) (*campaign.Campaign, error) {
|
||||
return r.FindByDisplayIDAndAccountOrID(ctx, id, accountID)
|
||||
}
|
||||
|
||||
// FindByDisplayIDAndAccountOrID retrieves a campaign by Chatwoot display_id, falling back to primary key for legacy callers/tests.
|
||||
func (r *CampaignRepo) FindByDisplayIDAndAccountOrID(ctx context.Context, routeID, accountID uint) (*campaign.Campaign, error) {
|
||||
var c campaign.Campaign
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("id = ? AND account_id = ?", id, accountID).First(&c).Error; err != nil {
|
||||
base := r.db.WithContext(ctx).Preload("Inbox").Preload("Sender")
|
||||
if err := base.Where("account_id = ? AND display_id = ?", accountID, routeID).First(&c).Error; err == nil {
|
||||
return &c, nil
|
||||
} else if err != gorm.ErrRecordNotFound {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Preload("Inbox").Preload("Sender").Where("account_id = ? AND id = ?", accountID, routeID).First(&c).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
@@ -53,10 +71,17 @@ func (r *CampaignRepo) ListByAccount(ctx context.Context, accountID uint, offset
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
err := r.db.WithContext(ctx).
|
||||
query := r.db.WithContext(ctx).
|
||||
Preload("Inbox").Preload("Sender").
|
||||
Where("account_id = ?", accountID).
|
||||
Order("created_at DESC").Offset(offset).Limit(limit).
|
||||
Find(&campaigns).Error
|
||||
Order("created_at DESC")
|
||||
if offset > 0 {
|
||||
query = query.Offset(offset)
|
||||
}
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
err := query.Find(&campaigns).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
@@ -1575,9 +1575,12 @@ func registerV1Routes(g *gin.RouterGroup, h *Handlers) {
|
||||
// Reference: Chatwoot namespace :campaigns
|
||||
campaigns := accountScoped.Group("/campaigns")
|
||||
{
|
||||
campaigns.GET("", h.Campaign.List)
|
||||
campaigns.GET("/", h.Campaign.List)
|
||||
campaigns.POST("", h.Campaign.Create)
|
||||
campaigns.POST("/", h.Campaign.Create)
|
||||
campaigns.GET("/:campaign_id", h.Campaign.Get)
|
||||
campaigns.PATCH("/:campaign_id", h.Campaign.Update)
|
||||
campaigns.PUT("/:campaign_id", h.Campaign.Update)
|
||||
campaigns.DELETE("/:campaign_id", h.Campaign.Delete)
|
||||
campaigns.POST("/:campaign_id/start", h.Campaign.Start)
|
||||
|
||||
@@ -2,7 +2,9 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/gochat/gochat/internal/campaign"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
@@ -13,7 +15,7 @@ import (
|
||||
// CampaignService implements business logic for Campaign operations.
|
||||
// Reference: Chatwoot app/controllers/api/v1/campaigns_controller.rb
|
||||
type CampaignService struct {
|
||||
campaignSvc *campaign.CampaignService
|
||||
campaignSvc *campaign.CampaignService
|
||||
campaignRepo *repository.CampaignRepo
|
||||
}
|
||||
|
||||
@@ -24,32 +26,32 @@ func NewCampaignService(campaignSvc *campaign.CampaignService, campaignRepo *rep
|
||||
|
||||
// CreateCampaignRequest is the DTO for creating a campaign.
|
||||
type CreateCampaignRequest struct {
|
||||
InboxID uint `json:"inbox_id" validate:"required"`
|
||||
SenderID *uint `json:"sender_id,omitempty"`
|
||||
Title string `json:"title" validate:"required,min=2"`
|
||||
Message string `json:"message" validate:"required"`
|
||||
Description string `json:"description,omitempty"`
|
||||
CampaignType string `json:"campaign_type" validate:"required,oneof=ongoing one_off"`
|
||||
Audience string `json:"audience,omitempty"`
|
||||
TriggerRules string `json:"trigger_rules,omitempty"`
|
||||
TemplateParams string `json:"template_params,omitempty"`
|
||||
ScheduledAt *string `json:"scheduled_at,omitempty"` // ISO8601 timestamp string
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
TriggerOnlyDuringBusinessHours *bool `json:"trigger_only_during_business_hours,omitempty"`
|
||||
InboxID uint `json:"inbox_id" validate:"required"`
|
||||
SenderID *uint `json:"sender_id,omitempty"`
|
||||
Title string `json:"title" validate:"required,min=2"`
|
||||
Message string `json:"message" validate:"required"`
|
||||
Description string `json:"description,omitempty"`
|
||||
CampaignType string `json:"campaign_type" validate:"required,oneof=ongoing one_off"`
|
||||
Audience json.RawMessage `json:"audience,omitempty"`
|
||||
TriggerRules json.RawMessage `json:"trigger_rules,omitempty"`
|
||||
TemplateParams json.RawMessage `json:"template_params,omitempty"`
|
||||
ScheduledAt *string `json:"scheduled_at,omitempty"` // ISO8601 timestamp string
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
TriggerOnlyDuringBusinessHours *bool `json:"trigger_only_during_business_hours,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateCampaignRequest is the DTO for updating a campaign.
|
||||
type UpdateCampaignRequest struct {
|
||||
Title string `json:"title,omitempty" validate:"omitempty,min=2"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
CampaignType string `json:"campaign_type,omitempty" validate:"omitempty,oneof=ongoing one_off"`
|
||||
Audience string `json:"audience,omitempty"`
|
||||
TriggerRules string `json:"trigger_rules,omitempty"`
|
||||
TemplateParams string `json:"template_params,omitempty"`
|
||||
ScheduledAt *string `json:"scheduled_at,omitempty"`
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
TriggerOnlyDuringBusinessHours *bool `json:"trigger_only_during_business_hours,omitempty"`
|
||||
Title string `json:"title,omitempty" validate:"omitempty,min=2"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
CampaignType string `json:"campaign_type,omitempty" validate:"omitempty,oneof=ongoing one_off"`
|
||||
Audience json.RawMessage `json:"audience,omitempty"`
|
||||
TriggerRules json.RawMessage `json:"trigger_rules,omitempty"`
|
||||
TemplateParams json.RawMessage `json:"template_params,omitempty"`
|
||||
ScheduledAt *string `json:"scheduled_at,omitempty"`
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
TriggerOnlyDuringBusinessHours *bool `json:"trigger_only_during_business_hours,omitempty"`
|
||||
}
|
||||
|
||||
// List retrieves all campaigns for an account with pagination.
|
||||
@@ -91,9 +93,9 @@ func (s *CampaignService) Create(ctx context.Context, accountID uint, req Create
|
||||
Description: req.Description,
|
||||
CampaignStatus: campaign.CampaignStatusActive,
|
||||
CampaignType: campaign.CampaignType(req.CampaignType),
|
||||
Audience: req.Audience,
|
||||
TriggerRules: req.TriggerRules,
|
||||
TemplateParams: req.TemplateParams,
|
||||
Audience: rawJSONParamString(req.Audience),
|
||||
TriggerRules: rawJSONParamString(req.TriggerRules),
|
||||
TemplateParams: rawJSONParamString(req.TemplateParams),
|
||||
Enabled: enabled,
|
||||
TriggerOnlyDuringBusinessHours: triggerDuringBH,
|
||||
}
|
||||
@@ -132,14 +134,14 @@ func (s *CampaignService) Update(ctx context.Context, id, accountID uint, req Up
|
||||
if req.CampaignType != "" {
|
||||
c.CampaignType = campaign.CampaignType(req.CampaignType)
|
||||
}
|
||||
if req.Audience != "" {
|
||||
c.Audience = req.Audience
|
||||
if len(req.Audience) > 0 {
|
||||
c.Audience = rawJSONParamString(req.Audience)
|
||||
}
|
||||
if req.TriggerRules != "" {
|
||||
c.TriggerRules = req.TriggerRules
|
||||
if len(req.TriggerRules) > 0 {
|
||||
c.TriggerRules = rawJSONParamString(req.TriggerRules)
|
||||
}
|
||||
if req.TemplateParams != "" {
|
||||
c.TemplateParams = req.TemplateParams
|
||||
if len(req.TemplateParams) > 0 {
|
||||
c.TemplateParams = rawJSONParamString(req.TemplateParams)
|
||||
}
|
||||
if req.Enabled != nil {
|
||||
c.Enabled = *req.Enabled
|
||||
@@ -149,14 +151,14 @@ func (s *CampaignService) Update(ctx context.Context, id, accountID uint, req Up
|
||||
}
|
||||
|
||||
if err := s.campaignSvc.Update(ctx, c.ID, map[string]interface{}{
|
||||
"title": c.Title,
|
||||
"message": c.Message,
|
||||
"description": c.Description,
|
||||
"campaign_type": c.CampaignType,
|
||||
"audience": c.Audience,
|
||||
"trigger_rules": c.TriggerRules,
|
||||
"template_params": c.TemplateParams,
|
||||
"enabled": c.Enabled,
|
||||
"title": c.Title,
|
||||
"message": c.Message,
|
||||
"description": c.Description,
|
||||
"campaign_type": c.CampaignType,
|
||||
"audience": c.Audience,
|
||||
"trigger_rules": c.TriggerRules,
|
||||
"template_params": c.TemplateParams,
|
||||
"enabled": c.Enabled,
|
||||
"trigger_only_during_business_hours": c.TriggerOnlyDuringBusinessHours,
|
||||
}); err != nil {
|
||||
applogger.L().Errorf("failed to update campaign: %v", err)
|
||||
@@ -167,7 +169,11 @@ func (s *CampaignService) Update(ctx context.Context, id, accountID uint, req Up
|
||||
|
||||
// Delete soft-deletes a campaign scoped to an account.
|
||||
func (s *CampaignService) Delete(ctx context.Context, id, accountID uint) error {
|
||||
if err := s.campaignSvc.Delete(ctx, id); err != nil {
|
||||
c, err := s.campaignRepo.FindByDisplayIDAndAccountOrID(ctx, id, accountID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("campaign not found: %w", err)
|
||||
}
|
||||
if err := s.campaignSvc.Delete(ctx, c.ID); err != nil {
|
||||
return fmt.Errorf("failed to delete campaign: %w", err)
|
||||
}
|
||||
return nil
|
||||
@@ -185,6 +191,18 @@ func (s *CampaignService) Start(ctx context.Context, id, accountID uint) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func rawJSONParamString(raw json.RawMessage) string {
|
||||
trimmed := strings.TrimSpace(string(raw))
|
||||
if trimmed == "" || trimmed == "null" {
|
||||
return ""
|
||||
}
|
||||
var value string
|
||||
if err := json.Unmarshal(raw, &value); err == nil {
|
||||
return value
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
// Stop marks a campaign as completed.
|
||||
func (s *CampaignService) Stop(ctx context.Context, id, accountID uint) error {
|
||||
c, err := s.campaignRepo.FindByIDAndAccount(ctx, id, accountID)
|
||||
|
||||
Reference in New Issue
Block a user