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
enhance task creation process
lotk5a3401b350fa
diff --git a/core/internal/service/batch_mail/batch_mail.go b/core/internal/service/batch_mail/batch_mail.goindex 8b0464d2..a0bbc5da 100644--- a/core/internal/service/batch_mail/batch_mail.go+++ b/core/internal/service/batch_mail/batch_mail.go@@ -258,6 +258,43 @@ func ImportRecipients(ctx context.Context, taskId int, contacts []*entity.Contacreturn nil}+// ImportRecipientsTx+func ImportRecipientsTx(ctx context.Context, tx gdb.TX, taskId int, contacts []*entity.Contact) error {+ if len(contacts) == 0 {+ return nil+ }+ const batchSize = 1000+ totalBatches := (len(contacts) + batchSize - 1) / batchSize+ now := time.Now().Unix()+ for i := 0; i < totalBatches; i++ {+ startIdx := i * batchSize+ endIdx := (i + 1) * batchSize+ if endIdx > len(contacts) {+ endIdx = len(contacts)+ }+ currentBatch := contacts[startIdx:endIdx]+ values := make([]g.Map, len(currentBatch))+ for j, contact := range currentBatch {+ values[j] = g.Map{+ "task_id": taskId,+ "recipient": contact.Email,+ "is_sent": 0,+ "sent_time": 0,+ "message_id": "",+ "create_time": now,+ }+ }+ result, err := tx.Ctx(ctx).Model("recipient_info").InsertIgnore(values)+ if err != nil {+ return fmt.Errorf("failed to import recipients (batch %d/%d): %w", i+1, totalBatches, err)+ }+ if _, err = result.RowsAffected(); err != nil {+ g.Log().Debugf(ctx, "ImportRecipientsTx: could not get affected rows for batch %d/%d: %v", i+1, totalBatches, err)+ }+ }+ return nil+}+// ============= contact group related operations =============// GetGroupInfo get group info@@ -356,191 +393,69 @@ func GetFilteredContacts(ctx context.Context, filter ContactFilter) ([]*entity.C}// ============= business logic combination =============-// add type parameter add_type default 0-//-// func CreateTaskWithRecipients(ctx context.Context, req *v1.CreateTaskReq, addType int) (int, error) {-// var taskId int-// var err error-// err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {-// etype := strings.Join(gconv.SliceStr(req.GroupIds), ",")-//-// taskId, err = CreateTask(ctx, CreateTaskArgs{-// Addresser: req.Addresser,-// Subject: req.Subject,-// FullName: req.FullName,-// TemplateId: req.TemplateId,-// IsRecord: req.IsRecord,-// Unsubscribe: req.Unsubscribe,-// Threads: req.Threads,-// TrackOpen: req.TrackOpen,-// TrackClick: req.TrackClick,-// Etypes: etype,-// Remark: req.Remark,-// StartTime: req.StartTime,-// Warmup: req.Warmup,-// AddType: addType,-// })-// if err != nil {-// return gerror.New(public.LangCtx(ctx, "Failed to create task {}", err.Error()))-// }-//-// var abnormalRecipients []struct {-// Recipient string `json:"recipient"`-// Count int `json:"count"`-// }-//-// err = tx.Model("abnormal_recipient").-// Where("count >= ?", 3).-// Fields("recipient, count").-// Scan(&abnormalRecipients)-//-// if err != nil {-// g.Log().Debugf(ctx, "Failed to get the exception recipient list: %v", err)-// }-//-// abnormalMap := make(map[string]int)-// if len(abnormalRecipients) > 0 {-// for _, ar := range abnormalRecipients {-// abnormalMap[ar.Recipient] = ar.Count-// }-// }-//-// // import recipient information-// totalRecipients := 0-// totalSkipped := 0-//-// for _, groupId := range req.GroupIds {-// contacts, err := GetActiveContacts(ctx, groupId)-// if err != nil {-// return gerror.New(public.LangCtx(ctx, "Failed to get contacts for group {}: {}", groupId, err.Error()))-// }-// if len(contacts) == 0 {-// continue-// }-//-// // abnormal skip and email format validation-// filteredContacts := make([]*entity.Contact, 0, len(contacts))-// skippedInGroup := 0-//-// for _, contact := range contacts {-// // Check if email is in abnormal list-// if _, exists := abnormalMap[contact.Email]; exists {-// skippedInGroup++-// continue-// }-//-// // Validate email format-// if err := gvalid.New().Rules("email").Data(contact.Email).Run(ctx); err != nil {-// skippedInGroup++-// g.Log().Debug(ctx, "Skip erroneous email addresses:", contact.Email, " Error:", err)-// continue-// }-//-// filteredContacts = append(filteredContacts, contact)-// }-//-// if skippedInGroup > 0 {-// totalSkipped += skippedInGroup-// }-//-// if len(filteredContacts) == 0 {-// continue-// }-//-// err = ImportRecipients(ctx, taskId, filteredContacts)-// if err != nil {-// return gerror.New(public.LangCtx(ctx, "Failed to import recipients for group {}: {}", groupId, err.Error()))-// }-//-// totalRecipients += len(filteredContacts)-// }-//-// // update recipient count-// actualCount, err := GetActualRecipientCount(ctx, taskId)-// if err == nil && actualCount > 0 {-// err = UpdateRecipientCount(ctx, taskId, actualCount)-// if err != nil {-// return gerror.New(public.LangCtx(ctx, "Failed to update recipient count for task {}: {}", taskId, err.Error()))-// }-// }-//-// if totalRecipients == 0 {-// return gerror.New(public.LangCtx(ctx, "No recipients found, task creation is not allowed"))-// }-// return nil-// })-//-// if err != nil {-// return 0, err-// }-//-// return taskId, nil-// }func CreateTaskWithRecipients(ctx context.Context, req *v1.CreateTaskReq, addType int) (int, error) {var taskId intvar err errorerr = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {- taskId, err = CreateTask(ctx, CreateTaskArgs{- Addresser: req.Addresser,- Subject: req.Subject,- FullName: req.FullName,- TemplateId: req.TemplateId,- IsRecord: req.IsRecord,- Unsubscribe: req.Unsubscribe,- Threads: req.Threads,- TrackOpen: req.TrackOpen,- TrackClick: req.TrackClick,- //Etypes: etype,- Remark: req.Remark,- StartTime: req.StartTime,- Warmup: req.Warmup,- AddType: addType,- GroupId: req.GroupId,- TagIds: req.TagIds,- TagLogic: req.TagLogic,+ now := time.Now().Unix()+ taskName := fmt.Sprintf("task_%d", now)+ var tagIdsJson string+ if len(req.TagIds) > 0 {+ tagIdsJson = gconv.String(req.TagIds)+ }++ res, e := tx.Ctx(ctx).Model("email_tasks").Insert(g.Map{+ "task_name": taskName,+ "addresser": req.Addresser,+ "subject": req.Subject,+ "full_name": req.FullName,+ "recipient_count": 0,+ "task_process": 0,+ "pause": 0,+ "template_id": req.TemplateId,+ "is_record": req.IsRecord,+ "unsubscribe": req.Unsubscribe,+ "threads": req.Threads,+ "track_open": req.TrackOpen,+ "track_click": req.TrackClick,+ "start_time": req.StartTime,+ "create_time": now,+ "update_time": now,+ "active": 1,+ "remark": req.Remark,+ "add_type": addType,+ "group_id": req.GroupId,+ "tag_ids": tagIdsJson,+ "tag_logic": req.TagLogic,})- if err != nil {- return gerror.New(public.LangCtx(ctx, "Failed to create task {}", err.Error()))+ if e != nil {+ return gerror.New(public.LangCtx(ctx, "Failed to create task {}", e.Error()))}+ id64, _ := res.LastInsertId()+ taskId = int(id64)var abnormalRecipients []struct {Recipient string `json:"recipient"`Count int `json:"count"`}-- err = tx.Model("abnormal_recipient").- Where("count >= ?", 3).- Fields("recipient, count").- Scan(&abnormalRecipients)-- if err != nil {- g.Log().Debugf(ctx, "Failed to get the exception recipient list: %v", err)+ if e = tx.Model("abnormal_recipient").Where("count >= ?", 3).Fields("recipient, count").Scan(&abnormalRecipients); e != nil {+ g.Log().Debugf(ctx, "Failed to get the exception recipient list: %v", e)}-- abnormalMap := make(map[string]int)- if len(abnormalRecipients) > 0 {- for _, ar := range abnormalRecipients {- abnormalMap[ar.Recipient] = ar.Count- }- }-- filter := ContactFilter{- GroupId: req.GroupId,- TagIds: req.TagIds,- TagLogic: req.TagLogic,+ abnormalMap := make(map[string]int, len(abnormalRecipients))+ for _, ar := range abnormalRecipients {+ abnormalMap[ar.Recipient] = ar.Count}+ filter := ContactFilter{GroupId: req.GroupId, TagIds: req.TagIds, TagLogic: req.TagLogic}var contacts []*entity.Contactif len(req.TagIds) > 0 {-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 filteringif req.GroupId <= 0 {return gerror.New(public.LangCtx(ctx, "Group ID is required when not using tag filter"))}@@ -549,57 +464,47 @@ func CreateTaskWithRecipients(ctx context.Context, req *v1.CreateTaskReq, addTypreturn gerror.New(public.LangCtx(ctx, "Failed to get contacts for group {}: {}", req.GroupId, err.Error()))}}-if len(contacts) == 0 {if len(req.TagIds) > 0 {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))}+ return gerror.New(public.LangCtx(ctx, "No contacts found in group {}", req.GroupId))}- // abnormal skip and email format validationfilteredContacts := make([]*entity.Contact, 0, len(contacts))- skippedInGroup := 0-for _, contact := range contacts {- // Check if email is in abnormal listif _, exists := abnormalMap[contact.Email]; exists {- skippedInGroup++continue}-- // Validate email format- if err := gvalid.New().Rules("email").Data(contact.Email).Run(ctx); err != nil {- skippedInGroup++- g.Log().Debug(ctx, "Skip erroneous email addresses:", contact.Email, " Error:", err)+ if e := gvalid.New().Rules("email").Data(contact.Email).Run(ctx); e != nil {+ g.Log().Debug(ctx, "Skip erroneous email addresses:", contact.Email, " Error:", e)continue}-filteredContacts = append(filteredContacts, contact)}-if len(filteredContacts) == 0 {return gerror.New(public.LangCtx(ctx, "No valid contacts found after filtering"))}- err = ImportRecipients(ctx, taskId, filteredContacts)- if err != nil {+ if err = ImportRecipientsTx(ctx, tx, taskId, filteredContacts); err != nil {return gerror.New(public.LangCtx(ctx, "Failed to import recipients: {}", err.Error()))}- // update recipient count- actualCount, err := GetActualRecipientCount(ctx, taskId)- if err == nil && actualCount > 0 {- err = UpdateRecipientCount(ctx, taskId, actualCount)- if err != nil {- return gerror.New(public.LangCtx(ctx, "Failed to update recipient count for task {}: {}", taskId, err.Error()))+ if actualCount, e2 := GetActualRecipientCount(ctx, taskId); e2 == nil && actualCount > 0 {+ if _, e2 = tx.Ctx(ctx).Model("email_tasks").Where("id", taskId).Data(g.Map{"recipient_count": actualCount}).Update(); e2 != nil {+ return gerror.New(public.LangCtx(ctx, "Failed to update recipient count for task {}: {}", taskId, e2.Error()))}}+ if req.Warmup == 1 {+ if serverIP, _ := public.GetServerIP(); serverIP != "" {+ if _, e2 := warmup.WarmupCampaign().AssociateCampaignWithWarmup(ctx, int64(taskId), serverIP); e2 != nil {+ g.Log().Warning(ctx, "Failed to associate campaign with warmup for task ID %d: %v", taskId, e2)+ }+ }+ }return nil})-if err != nil {return 0, err}