feat(campaigns): align chatwoot payloads

This commit is contained in:
2026-06-06 03:09:54 +08:00
parent 4b2c1a97ae
commit ca3c045f21
9 changed files with 242 additions and 151 deletions
+30 -5
View File
@@ -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
}