feat(campaigns): align chatwoot payloads
This commit is contained in:
@@ -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))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user