Files
gochat/internal/handler/api/v1/campaign_handler.go
T

269 lines
8.4 KiB
Go

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/response"
)
// CampaignHandler handles Campaign CRUD + trigger actions.
// Reference: Chatwoot app/controllers/api/v1/campaigns_controller.rb
type CampaignHandler struct {
svc *service.CampaignService
}
// NewCampaignHandler creates a new Campaign handler.
func NewCampaignHandler(svc *service.CampaignService) *CampaignHandler {
return &CampaignHandler{svc: svc}
}
// List returns all campaigns for an account.
// GET /api/v1/accounts/:id/campaigns
func (h *CampaignHandler) List(c *gin.Context) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
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
}
c.JSON(http.StatusOK, serializeCampaigns(campaigns, accountID))
}
// Get returns a single campaign by ID.
// GET /api/v1/accounts/:id/campaigns/:campaign_id
func (h *CampaignHandler) Get(c *gin.Context) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
id, err := strconv.ParseUint(c.Param("campaign_id"), 10, 32)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid campaign ID")
return
}
campaign, svcErr := h.svc.Get(c.Request.Context(), uint(id), accountID)
if svcErr != nil {
applogger.L().Errorf("Get campaign %d for account %d: %v", id, accountID, svcErr)
handleServiceError(c, svcErr)
return
}
c.JSON(http.StatusOK, serializeCampaign(campaign, accountID))
}
// Create creates a new campaign within an account.
// POST /api/v1/accounts/:id/campaigns
func (h *CampaignHandler) Create(c *gin.Context) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
// Chatwoot: params.require(:campaign) → request body must be {"campaign": {...}}
var wrapper struct {
Campaign service.CreateCampaignRequest `json:"campaign"`
}
if err := c.ShouldBindJSON(&wrapper); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, err.Error())
return
}
req := wrapper.Campaign
campaign, svcErr := h.svc.Create(c.Request.Context(), accountID, req)
if svcErr != nil {
applogger.L().Errorf("Create campaign for account %d: %v", accountID, svcErr)
handleServiceError(c, svcErr)
return
}
c.JSON(http.StatusOK, serializeCampaign(campaign, accountID))
}
// Update updates an existing campaign.
// PUT /api/v1/accounts/:id/campaigns/:campaign_id
func (h *CampaignHandler) Update(c *gin.Context) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
id, err := strconv.ParseUint(c.Param("campaign_id"), 10, 32)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid campaign ID")
return
}
// Chatwoot: params.require(:campaign) → request body must be {"campaign": {...}}
var wrapper struct {
Campaign service.UpdateCampaignRequest `json:"campaign"`
}
if err := c.ShouldBindJSON(&wrapper); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, err.Error())
return
}
req := wrapper.Campaign
campaign, svcErr := h.svc.Update(c.Request.Context(), uint(id), accountID, req)
if svcErr != nil {
applogger.L().Errorf("Update campaign %d for account %d: %v", id, accountID, svcErr)
handleServiceError(c, svcErr)
return
}
c.JSON(http.StatusOK, serializeCampaign(campaign, accountID))
}
// Delete soft-deletes a campaign.
// DELETE /api/v1/accounts/:id/campaigns/:campaign_id
func (h *CampaignHandler) Delete(c *gin.Context) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
id, err := strconv.ParseUint(c.Param("campaign_id"), 10, 32)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid campaign ID")
return
}
if svcErr := h.svc.Delete(c.Request.Context(), uint(id), accountID); svcErr != nil {
applogger.L().Errorf("Delete campaign %d for account %d: %v", id, accountID, svcErr)
handleServiceError(c, svcErr)
return
}
c.Status(http.StatusOK)
}
// Start triggers a campaign execution.
// POST /api/v1/accounts/:id/campaigns/:campaign_id/start
func (h *CampaignHandler) Start(c *gin.Context) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
id, err := strconv.ParseUint(c.Param("campaign_id"), 10, 32)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid campaign ID")
return
}
if svcErr := h.svc.Start(c.Request.Context(), uint(id), accountID); svcErr != nil {
applogger.L().Errorf("Start campaign %d for account %d: %v", id, accountID, svcErr)
handleServiceError(c, svcErr)
return
}
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) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
id, err := strconv.ParseUint(c.Param("campaign_id"), 10, 32)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid campaign ID")
return
}
if svcErr := h.svc.Stop(c.Request.Context(), uint(id), accountID); svcErr != nil {
applogger.L().Errorf("Stop campaign %d for account %d: %v", id, accountID, svcErr)
handleServiceError(c, svcErr)
return
}
response.OK(c, gin.H{"message": "campaign stopped successfully"})
}