Skip to content

BillionMail gives you open-source MailServer, NewsLetter, Email Marketing — fully self-hosted, dev-friendly, and free from monthly fees. Join the discord: https://discord.gg/asfXzBUhZr

Add tag filtering functionality to email tasks with validation

lotka9652f793ce9
diff --git a/core/api/batch_mail/v1/batch_mail.go b/core/api/batch_mail/v1/batch_mail.go
index c4ed7d39..ac2c52b5 100644
--- a/core/api/batch_mail/v1/batch_mail.go
+++ b/core/api/batch_mail/v1/batch_mail.go
@@ -35,6 +35,9 @@ type EmailTask struct {
DeferredCount int `json:"deferredCount" description:""`
StatsUpdateTime int `json:"statsUpdateTime" description:""`
GroupId int `json:"group_id" dc:"Group ID"`
+ TagIds []int `json:"tag_ids" dc:"Tag IDs"`
+ UseTagFilter int `json:"use_tag_filter" dc:"Whether to use tag filter (1: yes, 0: no)"`
+ TagLogic string `json:"tag_logic" dc:"Tag logic (AND: must have all tags, OR: have any tag)"`
}
type GroupInfo struct {
@@ -140,6 +143,10 @@ type CreateTaskReq struct {
StartTime int `json:"start_time" v:"required" dc:"start time"`
Warmup int `json:"warmup" v:"in:0,1" dc:"warmup" default:"0"`
Remark string `json:"remark" dc:"remark"`
+
+ TagIds []int `json:"tag_ids" dc:"tag ids for filtering contacts"`
+ TagLogic string `json:"tag_logic" v:"in:AND,OR" dc:"tag logic (AND: must have all tags, OR: have any tag)" default:"AND"`
+ UseTagFilter int `json:"use_tag_filter" dc:"whether to use tag filter (1: yes, 0: no)" v:"in:0,1" default:"0"`
}
type CreateTaskRes struct {
diff --git a/core/api/contact/v1/contact.go b/core/api/contact/v1/contact.go
index 0c1af07c..2b9b4c4e 100644
--- a/core/api/contact/v1/contact.go
+++ b/core/api/contact/v1/contact.go
@@ -52,7 +52,6 @@ type GroupInfo struct {
type TagInfo struct {
Id int `json:"id" dc:"Tag ID"`
- GroupId int `json:"group_id" dc:"Group ID"`
Name string `json:"name" dc:"Tag Name"`
CreateTime int `json:"create_time" dc:"Create Time"`
}
diff --git a/core/internal/controller/batch_mail/batch_mail_v1_create_task.go b/core/internal/controller/batch_mail/batch_mail_v1_create_task.go
index f3191d93..86d96e93 100644
--- a/core/internal/controller/batch_mail/batch_mail_v1_create_task.go
+++ b/core/internal/controller/batch_mail/batch_mail_v1_create_task.go
@@ -14,6 +14,11 @@ import (
func (c *ControllerV1) CreateTask(ctx context.Context, req *v1.CreateTaskReq) (res *v1.CreateTaskRes, err error) {
res = &v1.CreateTaskRes{}
+ if err = validateCreateTaskRequest(req); err != nil {
+ res.SetError(err)
+ return
+ }
+
// check template
template, err := email_template.GetTemplate(ctx, req.TemplateId)
if err != nil {
@@ -44,3 +49,24 @@ func (c *ControllerV1) CreateTask(ctx context.Context, req *v1.CreateTaskReq) (r
res.SetSuccess(public.LangCtx(ctx, "Task created successfully"))
return
}
+
+func validateCreateTaskRequest(req *v1.CreateTaskReq) error {
+
+ if req.GroupId <= 0 {
+ return gerror.New("Must select a contact group")
+ }
+
+ if req.UseTagFilter==1 && len(req.TagIds) == 0 {
+ return gerror.New("Must select at least one tag when tag filter is enabled")
+ }
+
+ if req.UseTagFilter==1 && req.TagLogic != "" && req.TagLogic != "AND" && req.TagLogic != "OR" {
+ return gerror.New("Tag logic must be AND or OR")
+ }
+
+ if req.UseTagFilter==1 && req.TagLogic == "" {
+ req.TagLogic = "AND"
+ }
+
+ return nil
+}
diff --git a/core/internal/controller/batch_mail/batch_mail_v1_task_info.go b/core/internal/controller/batch_mail/batch_mail_v1_task_info.go
index 2f8b5ecb..4bd25fac 100644
--- a/core/internal/controller/batch_mail/batch_mail_v1_task_info.go
+++ b/core/internal/controller/batch_mail/batch_mail_v1_task_info.go
@@ -5,6 +5,7 @@ import (
"billionmail-core/internal/service/batch_mail"
"billionmail-core/internal/service/public"
"context"
+ "encoding/json"
"github.com/gogf/gf/v2/errors/gerror"
@@ -27,6 +28,15 @@ func (c *ControllerV1) TaskInfo(ctx context.Context, req *v1.TaskInfoReq) (res *
res.SetError(gerror.New(public.LangCtx(ctx, "Task not found: {}", req.Id)))
return
}
+
+ // Convert tag_ids string to array before returning
+ if taskInfo.TagIdsRaw != "" {
+ var tagIds []int
+ if err := json.Unmarshal([]byte(taskInfo.TagIdsRaw), &tagIds); err == nil {
+ taskInfo.TagIds = tagIds
+ }
+ }
+
res.Data = taskInfo
res.SetSuccess(public.LangCtx(ctx, "Success"))
return
diff --git a/core/internal/model/entity/batch_mail.go b/core/internal/model/entity/batch_mail.go
index e9793e21..a146eda6 100644
--- a/core/internal/model/entity/batch_mail.go
+++ b/core/internal/model/entity/batch_mail.go
@@ -1,5 +1,9 @@
package entity
+import (
+ "encoding/json"
+)
+
// ContactGroup Entity
type ContactGroup struct {
Id int `json:"id" dc:"Group ID"`
@@ -82,9 +86,45 @@ type EmailTask struct {
DeferredCount int `json:"deferredCount" description:""`
StatsUpdateTime int `json:"statsUpdateTime" description:""`
GroupId int `json:"group_id" dc:"Group ID"`
+ TagIdsRaw string `json:"-" dc:"Tag IDs (JSON string - internal use)" orm:"tag_ids"`
+ TagIds []int `json:"tag_ids" dc:"Tag IDs (parsed array)"`
+ TagLogic string `json:"tag_logic" dc:"Tag Logic (AND/OR)"`
+ UseTagFilter int `json:"use_tag_filter" dc:"Use Tag Filter (0: no, 1: yes)"`
+}
+
+// MarshalJSON implements custom JSON marshaling to convert TagIdsRaw to TagIds array
+func (e *EmailTask) MarshalJSON() ([]byte, error) {
+ // Create a temporary struct with all fields
+ type Alias EmailTask
+ aux := &struct {
+ *Alias
+ }{
+ Alias: (*Alias)(e),
+ }
+
+ // Parse TagIdsRaw to TagIds if not already parsed
+ if e.TagIdsRaw != "" && len(e.TagIds) == 0 {
+ var tagIds []int
+ err := json.Unmarshal([]byte(e.TagIdsRaw), &tagIds)
+ if err == nil {
+ aux.TagIds = tagIds
+ }
+ }
+
+ return json.Marshal(aux)
+}
+
+// AfterFind is called after retrieving data from database
+func (e *EmailTask) AfterFind() {
+ if e.TagIdsRaw != "" {
+ var tagIds []int
+ err := json.Unmarshal([]byte(e.TagIdsRaw), &tagIds)
+ if err == nil {
+ e.TagIds = tagIds
+ }
+ }
}
-// RecipientInfo Entity
type RecipientInfo struct {
Id int `json:"id" dc:"Recipient ID"`
TaskId int `json:"task_id" dc:"Task ID"`
diff --git a/core/internal/service/batch_mail/batch_mail.go b/core/internal/service/batch_mail/batch_mail.go
index ccf18c70..7dc4c06b 100644
--- a/core/internal/service/batch_mail/batch_mail.go
+++ b/core/internal/service/batch_mail/batch_mail.go
@@ -13,6 +13,8 @@ import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gvalid"
+ "strconv"
+ "strings"
"sync/atomic"
"time"
)
@@ -32,11 +34,14 @@ type CreateTaskArgs struct {
TrackOpen int `json:"track_open"` // Track email opens
TrackClick int `json:"track_click"` // Track email clicks
//Etypes string `json:"etypes"` // Email types (e.g., group IDs)
- Remark string `json:"remark"` // Task remark
- StartTime int `json:"start_time"` // Scheduled start time
- Warmup int `json:"warmup"` // Warmup campaign association
- AddType int `json:"add_type"` // Add type (0: normal)
- GroupId int `json:"group_id"` // Groups to unsubscribe from
+ Remark string `json:"remark"` // Task remark
+ StartTime int `json:"start_time"` // Scheduled start time
+ Warmup int `json:"warmup"` // Warmup campaign association
+ AddType int `json:"add_type"` // Add type (0: normal)
+ GroupId int `json:"group_id"` // Groups to unsubscribe from
+ TagIds []int `json:"tag_ids"` // Tag IDs for filtering contacts
+ TagLogic string `json:"tag_logic"` // Tag logic (AND/OR)
+ UseTagFilter int `json:"use_tag_filter"` // Whether to use tag filter
}
// ============= task related operations =============
@@ -117,6 +122,13 @@ func CreateTask(ctx context.Context, args CreateTaskArgs) (int, error) {
now := time.Now().Unix()
// generate task name
taskName := "task_" + gconv.String(now)
+
+ // Convert tag IDs to JSON string for database storage
+ tagIdsJson := ""
+ if len(args.TagIds) > 0 {
+ tagIdsJson = gconv.String(args.TagIds)
+ }
+
result, err := g.DB().Model("email_tasks").Insert(g.Map{
"task_name": taskName,
"addresser": args.Addresser,
@@ -130,15 +142,18 @@ func CreateTask(ctx context.Context, args CreateTaskArgs) (int, error) {
"unsubscribe": args.Unsubscribe,
"threads": args.Threads,
//"etypes": args.Etypes,
- "track_open": args.TrackOpen,
- "track_click": args.TrackClick,
- "start_time": args.StartTime,
- "create_time": now,
- "update_time": now,
- "active": 1,
- "remark": args.Remark,
- "add_type": args.AddType,
- "group_id": args.GroupId,
+ "track_open": args.TrackOpen,
+ "track_click": args.TrackClick,
+ "start_time": args.StartTime,
+ "create_time": now,
+ "update_time": now,
+ "active": 1,
+ "remark": args.Remark,
+ "add_type": args.AddType,
+ "group_id": args.GroupId,
+ "tag_ids": tagIdsJson,
+ "tag_logic": args.TagLogic,
+ "use_tag_filter": args.UseTagFilter,
})
if err != nil {
g.Log().Debug(ctx, "Failed to create campaign:", err.Error())
@@ -284,8 +299,66 @@ func GetActiveContacts(ctx context.Context, groupId int) ([]*entity.Contact, err
return contacts, err
}
+type ContactFilter struct {
+ GroupId int
+ TagIds []int
+ TagLogic string // "AND" or "OR"
+ UseTagFilter int
+}
+
+func GetFilteredContacts(ctx context.Context, filter ContactFilter) ([]*entity.Contact, error) {
+ var contacts []*entity.Contact
+
+ model := g.DB().Model("bm_contacts c").
+ Where("c.active", 1).
+ Where("c.status", 1). // Confirmed email address
+ Fields("c.*")
+
+ if filter.GroupId > 0 {
+ model = model.Where("c.group_id", filter.GroupId)
+ }
+
+ if filter.UseTagFilter == 1 && len(filter.TagIds) > 0 {
+ if filter.TagLogic == "AND" {
+ // AND
+ for i, tagId := range filter.TagIds {
+ alias := g.NewVar("ct" + g.NewVar(i).String()).String()
+ model = model.InnerJoin(
+ "bm_contact_tags "+alias,
+ "c.id = "+alias+".contact_id AND "+alias+".tag_id = "+g.NewVar(tagId).String(),
+ )
+ }
+ } else {
+ // OR
+ var inValues []string
+ for _, tagId := range filter.TagIds {
+
+ inValues = append(inValues, strconv.Itoa(tagId))
+ }
+
+ subQuery := fmt.Sprintf(
+ "(SELECT DISTINCT contact_id FROM bm_contact_tags WHERE tag_id IN (%s)) ct",
+ strings.Join(inValues, ","),
+ )
+
+ model = model.InnerJoin(
+ subQuery,
+ "c.id = ct.contact_id",
+ )
+ }
+ }
+
+ err := model.Scan(&contacts)
+ if err != nil {
+ g.Log().Error(ctx, "Failed to get filtered contacts: %v", err)
+ return nil, err
+ }
+
+ return contacts, nil
+}
+
// ============= business logic combination =============
-// add type parameter add_type default 0 todo 改用单个组
+// add type parameter add_type default 0
//
// func CreateTaskWithRecipients(ctx context.Context, req *v1.CreateTaskReq, addType int) (int, error) {
// var taskId int
@@ -405,6 +478,7 @@ func GetActiveContacts(ctx context.Context, groupId int) ([]*entity.Contact, err
//
// return taskId, nil
// }
+
func CreateTaskWithRecipients(ctx context.Context, req *v1.CreateTaskReq, addType int) (int, error) {
var taskId int
var err error
@@ -421,11 +495,14 @@ func CreateTaskWithRecipients(ctx context.Context, req *v1.CreateTaskReq, addTyp
TrackOpen: req.TrackOpen,
TrackClick: req.TrackClick,
//Etypes: etype,
- Remark: req.Remark,
- StartTime: req.StartTime,
- Warmup: req.Warmup,
- AddType: addType,
- GroupId: req.GroupId,
+ Remark: req.Remark,
+ StartTime: req.StartTime,
+ Warmup: req.Warmup,
+ AddType: addType,
+ GroupId: req.GroupId,
+ TagIds: req.TagIds,
+ TagLogic: req.TagLogic,
+ UseTagFilter: req.UseTagFilter,
})
if err != nil {
return gerror.New(public.LangCtx(ctx, "Failed to create task {}", err.Error()))
@@ -452,15 +529,37 @@ func CreateTaskWithRecipients(ctx context.Context, req *v1.CreateTaskReq, addTyp
}
}
- // import recipient information
- totalSkipped := 0
+ filter := ContactFilter{
+ GroupId: req.GroupId,
+ TagIds: req.TagIds,
+ TagLogic: req.TagLogic,
+ UseTagFilter: req.UseTagFilter,
+ }
- contacts, err := GetActiveContacts(ctx, req.GroupId)
- if err != nil {
- return gerror.New(public.LangCtx(ctx, "Failed to get contacts for group {}: {}", req.GroupId, err.Error()))
+ var contacts []*entity.Contact
+ if req.UseTagFilter == 1 {
+
+ contacts, err = GetFilteredContacts(ctx, filter)
+ if err != nil {
+ return gerror.New(public.LangCtx(ctx, "Failed to get filtered contacts: {}", err.Error()))
+ }
+ } else {
+ // Compatible with older versions: Use group filtering
+ if req.GroupId <= 0 {
+ return gerror.New(public.LangCtx(ctx, "Group ID is required when not using tag filter"))
+ }
+ contacts, err = GetActiveContacts(ctx, req.GroupId)
+ if err != nil {
+ return gerror.New(public.LangCtx(ctx, "Failed to get contacts for group {}: {}", req.GroupId, err.Error()))
+ }
}
+
if len(contacts) == 0 {
- return gerror.New(public.LangCtx(ctx, "No contacts found in group {}: {}", req.GroupId))
+ if req.UseTagFilter == 1 {
+ return gerror.New(public.LangCtx(ctx, "No contacts found matching the tag filter criteria"))
+ } else {
+ return gerror.New(public.LangCtx(ctx, "No contacts found in group {}", req.GroupId))
+ }
}
// abnormal skip and email format validation
@@ -484,17 +583,13 @@ func CreateTaskWithRecipients(ctx context.Context, req *v1.CreateTaskReq, addTyp
filteredContacts = append(filteredContacts, contact)
}
- if skippedInGroup > 0 {
- totalSkipped += skippedInGroup
- }
-
if len(filteredContacts) == 0 {
- return gerror.New(public.LangCtx(ctx, "No valid contacts found in group {}: {}", req.GroupId))
+ return gerror.New(public.LangCtx(ctx, "No valid contacts found after filtering"))
}
err = ImportRecipients(ctx, taskId, filteredContacts)
if err != nil {
- return gerror.New(public.LangCtx(ctx, "Failed to import recipients for group {}: {}", req.GroupId, err.Error()))
+ return gerror.New(public.LangCtx(ctx, "Failed to import recipients: {}", err.Error()))
}
// update recipient count
@@ -521,6 +616,7 @@ func GetTaskInfo(ctx context.Context, taskId int) (*entity.EmailTask, error) {
var task entity.EmailTask
err := g.DB().Model("email_tasks").
Where("id", taskId).
+ Fields("*, tag_ids as TagIdsRaw").
Scan(&task)
if err != nil {
diff --git a/core/internal/service/database_initialization/batch_mail.go b/core/internal/service/database_initialization/batch_mail.go
index 356135ba..e9ba9b3a 100644
--- a/core/internal/service/database_initialization/batch_mail.go
+++ b/core/internal/service/database_initialization/batch_mail.go
@@ -90,7 +90,11 @@ func init() {
bounced_count INTEGER NOT NULL DEFAULT 0,
deferred_count INTEGER NOT NULL DEFAULT 0,
group_id INTEGER NOT NULL DEFAULT 0,
- stats_update_time INTEGER NOT NULL DEFAULT 0
+ stats_update_time INTEGER NOT NULL DEFAULT 0,
+ tag_ids TEXT DEFAULT '', -- JSON array of tag ids for filtering contacts
+ tag_logic VARCHAR(10) DEFAULT 'AND', -- Tag logic (AND: must have all tags, OR: have any tag)
+ use_tag_filter SMALLINT NOT NULL DEFAULT 0 -- Whether to use tag filter (0: no, 1: yes)
+
)`,
`CREATE TABLE IF NOT EXISTS recipient_info (
@@ -251,6 +255,9 @@ func init() {
_ = AddColumnIfNotExists("email_tasks", "deferred_count", "INTEGER", "0", true)
_ = AddColumnIfNotExists("email_tasks", "stats_update_time", "INTEGER", "0", true)
_ = AddColumnIfNotExists("email_tasks", "group_id", "INTEGER", "0", true)
+ _ = AddColumnIfNotExists("email_tasks", "tag_ids", "TEXT", "''", false)
+ _ = AddColumnIfNotExists("email_tasks", "tag_logic", "VARCHAR(10)", "'AND'", false)
+ _ = AddColumnIfNotExists("email_tasks", "use_tag_filter", "SMALLINT", "0", true)
// unsubscribe_records
_ = DropForeignKeyIfExists("unsubscribe_records", "group_id")