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 batch tagging functionality for contacts and enhance contact trend retrieval
lotk09cde837621c
diff --git a/core/api/contact/contact.go b/core/api/contact/contact.goindex e4d22175..f515080c 100644--- a/core/api/contact/contact.go+++ b/core/api/contact/contact.go@@ -16,6 +16,7 @@ type IContactV1 interface {ExportContacts(ctx context.Context, req *v1.ExportContactsReq) (res *v1.ExportContactsRes, err error)DeleteGroup(ctx context.Context, req *v1.DeleteGroupReq) (res *v1.DeleteGroupRes, err error)UpdateGroup(ctx context.Context, req *v1.UpdateGroupReq) (res *v1.UpdateGroupRes, err error)+ UpdateGroupUnsubscribe(ctx context.Context, req *v1.UpdateGroupUnsubscribeReq) (res *v1.UpdateGroupUnsubscribeRes, err error)ListGroups(ctx context.Context, req *v1.ListGroupsReq) (res *v1.ListGroupsRes, err error)ListContacts(ctx context.Context, req *v1.ListContactsReq) (res *v1.ListContactsRes, err error)ListContactsGroups(ctx context.Context, req *v1.ListContactsGroupsReq) (res *v1.ListContactsGroupsRes, err error)@@ -29,4 +30,5 @@ type IContactV1 interface {ListContactsNDP(ctx context.Context, req *v1.ListContactsNDPReq) (res *v1.ListContactsNDPRes, err error)EditContactsNDP(ctx context.Context, req *v1.EditContactsNDPReq) (res *v1.EditContactsNDPRes, err error)DeleteContactsNDP(ctx context.Context, req *v1.DeleteContactsNDPReq) (res *v1.DeleteContactsNDPRes, err error)+ BatchTagContacts(ctx context.Context, req *v1.BatchTagContactsReq) (res *v1.BatchTagContactsRes, err error)}diff --git a/core/api/contact/v1/contact.go b/core/api/contact/v1/contact.goindex e796749a..0c1af07c 100644--- a/core/api/contact/v1/contact.go+++ b/core/api/contact/v1/contact.go@@ -50,6 +50,13 @@ type GroupInfo struct {Name string `json:"name" dc:"Group Name"`}+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"`+}+type Contact struct {Id int `json:"id" dc:"Contact ID"`Email string `json:"email" dc:"Email Address"`@@ -62,6 +69,7 @@ type Contact struct {GroupName string `json:"group_name" dc:"Contact Group Name"`Attribs map[string]string `json:"attribs"`LastActiveAt int `json:"last_active_at" dc:"Last Active At"`+ Tags []TagInfo `json:"tags" dc:"Contact Tags"`}type CreateGroupReq struct {@@ -151,7 +159,17 @@ type UpdateGroupReq struct {WelcomeSubject string `json:"welcome_subject" dc:"Welcome Email Subject"`SendWelcomeEmail int `json:"send_welcome_email" dc:"Whether to send a welcome email"`ConfirmSubject string `json:"confirm_subject" dc:"Confirmation Email Subject"`- // New unsubscribe related fields+}++type UpdateGroupRes struct {+ api_v1.StandardRes+}++type UpdateGroupUnsubscribeReq struct {+ g.Meta `path:"/contact/group/update_unsubscribe" method:"post" tags:"Contact" summary:"Update contact group Unsubscribe settings"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+ GroupId int `json:"group_id" v:"required" dc:"Group ID"`+UnsubscribeMailHtml string `json:"unsubscribe_mail_html" dc:"Unsubscribe EmailHtml"`UnsubscribeMailDrag string `json:"unsubscribe_mail_drag" dc:"Unsubscribe EmailDrag"`UnsubscribeSubject string `json:"unsubscribe_subject" dc:"Unsubscribe Email Subject"`@@ -159,10 +177,9 @@ type UpdateGroupReq struct {SendUnsubscribeEmail int `json:"send_unsubscribe_email" dc:"Whether to send unsubscribe email"`}-type UpdateGroupRes struct {+type UpdateGroupUnsubscribeRes struct {api_v1.StandardRes}-type ListGroupsReq struct {g.Meta `path:"/contact/group/list" method:"get" tags:"Contact" summary:"List contact groups"`Authorization string `json:"authorization" dc:"Authorization" in:"header"`@@ -251,9 +268,13 @@ type UpdateContactsGroupRes struct {}type GetContactsTrendReq struct {- g.Meta `path:"/contact/trend" method:"get" tags:"Contact" summary:"Get contact trend"`- Authorization string `json:"authorization" dc:"Authorization" in:"header"`- GroupId int `json:"group_id" dc:"Group ID"`+ g.Meta `path:"/contact/trend" method:"get" tags:"Contact" summary:"Get contact trend"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+ GroupId int `json:"group_id" dc:"Group ID"`+ Active int `json:"active" v:"in:0,1,-1" dc:"Active(1:Subscribed 0:Unsubscribed -1:all)" default:"-1"`+ LastActiveStatus int `json:"last_active_status" v:"in:0,1,-1" dc:"Status(1:active 0:inactive -1:all)" default:"-1"`+ TimeInterval int `json:"time_interval" dc:"TimeInterval(7 : last 7 days, 30: last 30 days, 90: last 90 days, 180: last half year, 365: last year, 0: all)" default:"0"`+ Tags string `json:"tags" dc:"Tags(-1:all or tag IDs, multiple IDs separated by commas)" default:"-1"`}type MonthlyTrend struct {@@ -262,11 +283,18 @@ type MonthlyTrend struct {UnsubscribeCount int `json:"unsubscribe_count" dc:"Unsubscribe Count"`}+type DailyTrend struct {+ Date string `json:"date" dc:"Date Format: YYYY-MM-DD"`+ SubscribeCount int `json:"subscribe_count" dc:"Subscribe Count"`+ UnsubscribeCount int `json:"unsubscribe_count" dc:"Unsubscribe Count"`+}+type GetContactsTrendRes struct {api_v1.StandardResData struct {- Subscribe []*MonthlyCount `json:"subscribe" dc:"Subscribe Trend"`- Unsubscribe []*MonthlyCount `json:"unsubscribe" dc:"Unsubscribe Trend"`+ TimeGranularity string `json:"time_granularity" dc:"Time Granularity (daily/monthly)"`+ MonthlyData []*MonthlyCount `json:"monthly_data" dc:"Monthly Trend Data"`+ DailyData []*DailyCount `json:"daily_data" dc:"Daily Trend Data"`} `json:"data"`}@@ -275,6 +303,11 @@ type MonthlyCount struct {Count int `json:"count" dc:"Count"`}+type DailyCount struct {+ Date string `json:"date" dc:"Date Format: YYYY-MM-DD"`+ Count int `json:"count" dc:"Count"`+}+type GetGroupContactCountReq struct {g.Meta `path:"/contact/group/contact_count" method:"post" tags:"Contact" summary:"Get group contact count"`Authorization string `json:"authorization" dc:"Authorization" in:"header"`@@ -313,13 +346,18 @@ type EditContactsRes struct {}type ListContactsNDPReq struct {- g.Meta `path:"/contact/list_ndp" method:"get" tags:"Contact" summary:"List all contacts"`- Authorization string `json:"authorization" dc:"Authorization" in:"header"`- Page int `json:"page" v:"required|min:1" dc:"Page Number"`- PageSize int `json:"page_size" v:"required|min:1" dc:"Page Size"`- GroupId int `json:"group_id" dc:"Group ID(Optional)"`- Keyword string `json:"keyword" dc:"Search Email"`- Active int `json:"active" v:"required|in:0,1,-1" dc:"Active(1:Subscribed 0:Unsubscribed -1:all)" default:"-1"`+ g.Meta `path:"/contact/list_ndp" method:"get" tags:"Contact" summary:"List all contacts"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+ Page int `json:"page" v:"required|min:1" dc:"Page Number"`+ PageSize int `json:"page_size" v:"required|min:1" dc:"Page Size"`+ GroupId int `json:"group_id" dc:"Group ID(Optional)"`+ Keyword string `json:"keyword" dc:"Search Email"`+ Active int `json:"active" v:"required|in:0,1,-1" dc:"Active(1:Subscribed 0:Unsubscribed -1:all)" default:"-1"`+ LastActiveStatus int `json:"last_active_status" v:"in:0,1,-1" dc:"Status(1:active 0:inactive -1:all)" default:"-1"`+ TimeInterval int `json:"time_interval" dc:"TimeInterval(7 : last 7 days, 30: last 30 days, 90: last 90 days, 180: last half year, 365: last year, 0: all)" default:"0"`+ Tags string `json:"tags" dc:"Tags(-1:all or tag IDs, multiple IDs separated by commas)" default:"-1"`+ SortBy string `json:"sort_by" v:"in:create_time,last_active_at" dc:"Sort field (create_time: creation time, last_active_at: last active time)" default:"create_time"`+ SortOrder string `json:"sort_order" v:"in:asc,desc" dc:"Sort order (asc: ascending, desc: descending)" default:"desc"`}type ListContactsNDPRes struct {@@ -352,3 +390,14 @@ type DeleteContactsNDPReq struct {type DeleteContactsNDPRes struct {api_v1.StandardRes}++type BatchTagContactsReq struct {+ g.Meta `path:"/contact/batch_tags_opt" method:"post" tags:"Contact" summary:"Tag contacts in bulk"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+ Ids []int `json:"ids" v:"required" dc:"Contact IDs"`+ TagIds []int `json:"tag_ids" v:"required" dc:"Tag IDs"`+ Action int `json:"action" v:"required|in:1,2" dc:"Action (1: Add Tag, 2: Remove Tag)"`+}+type BatchTagContactsRes struct {+ api_v1.StandardRes+}diff --git a/core/api/tags/v1/tags.go b/core/api/tags/v1/tags.goindex 7d846ae7..f89576f5 100644--- a/core/api/tags/v1/tags.go+++ b/core/api/tags/v1/tags.go@@ -13,11 +13,10 @@ type TagInfo struct {CreateTime int `json:"create_time" dc:"Create Time"`}-// 获取标签列表type TagListReq struct {g.Meta `path:"/tags/list" method:"get" tags:"Tag" summary:"Get tag list"`Authorization string `json:"authorization" dc:"Authorization" in:"header"`- GroupId int `json:"group_id" v:"required|min:1" dc:"Group ID"`+ GroupId int `json:"group_id" v:"min:1" dc:"Group ID"`Keyword string `json:"keyword" dc:"Search keyword"`Page int `json:"page" dc:"Page" d:"1"`PageSize int `json:"page_size" dc:"Page size" d:"20"`@@ -25,12 +24,11 @@ type TagListReq struct {type TagListRes struct {api_v1.StandardResData struct {- Total int `json:"total" dc:"Total Count"`+ Total int `json:"total" dc:"Total Count"`List []*entity.Tag `json:"list" dc:"Tag list"`} `json:"data"`}-// 创建标签type TagCreateReq struct {g.Meta `path:"/tags/create" method:"post" tags:"Tag" summary:"Create a new tag"`Authorization string `json:"authorization" dc:"Authorization" in:"header"`@@ -41,7 +39,6 @@ type TagCreateRes struct {api_v1.StandardRes}-// 更新标签type TagUpdateReq struct {g.Meta `path:"/tags/update" method:"post" tags:"Tag" summary:"Update a tag"`Authorization string `json:"authorization" dc:"Authorization" in:"header"`@@ -52,7 +49,6 @@ type TagUpdateRes struct {api_v1.StandardRes}-// 删除标签type TagDeleteReq struct {g.Meta `path:"/tags/delete" method:"post" tags:"Tag" summary:"Delete a tag"`Authorization string `json:"authorization" dc:"Authorization" in:"header"`@@ -62,8 +58,6 @@ type TagDeleteRes struct {api_v1.StandardRes}--// 批量标记联系人 传 group_id tag_id data(联系人邮箱 换行分隔) mark_include(标记包含1,标记不包含0)type BatchTagContactsReq struct {g.Meta `path:"/tags/batch_contacts" method:"post" tags:"Tag" summary:"Tag contacts in bulk"`Authorization string `json:"authorization" dc:"Authorization" in:"header"`@@ -75,4 +69,3 @@ type BatchTagContactsReq struct {type BatchTagContactsRes struct {api_v1.StandardRes}-diff --git a/core/internal/controller/contact/contact_v1_batch_tag_contacts.go b/core/internal/controller/contact/contact_v1_batch_tag_contacts.gonew file mode 100644index 00000000..e605574a--- /dev/null+++ b/core/internal/controller/contact/contact_v1_batch_tag_contacts.go@@ -0,0 +1,305 @@+package contact++import (+ "context"+ "database/sql"+ "time"++ "github.com/gogf/gf/v2/database/gdb"+ "github.com/gogf/gf/v2/errors/gerror"+ "github.com/gogf/gf/v2/frame/g"++ "billionmail-core/api/contact/v1"+ "billionmail-core/internal/consts"+ "billionmail-core/internal/service/public"+)++func (c *ControllerV1) BatchTagContacts(ctx context.Context, req *v1.BatchTagContactsReq) (res *v1.BatchTagContactsRes, err error) {+ res = &v1.BatchTagContactsRes{}++ if len(req.Ids) == 0 {+ res.SetError(gerror.New(public.LangCtx(ctx, "No contact IDs provided")))+ return+ }++ if len(req.TagIds) == 0 {+ res.SetError(gerror.New(public.LangCtx(ctx, "No tag IDs provided")))+ return+ }++ g.Log().Infof(ctx, "BatchTagContacts: Processing %d contacts with %d tags, action: %d",+ len(req.Ids), len(req.TagIds), req.Action)++ var processedCount, skippedCount, errorCount int+++ err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {+ if req.Action == 1 {++ processedCount, skippedCount, errorCount, err = c.batchAddTagsToContacts(ctx, tx, req.Ids, req.TagIds)+ } else {++ processedCount, skippedCount, errorCount, err = c.batchRemoveTagsFromContacts(ctx, tx, req.Ids, req.TagIds)+ }+ return err+ })++ if err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to process batch tag operation")))+ return+ }+++ operation := "Add tags"+ if req.Action == 2 {+ operation = "Remove tags"+ }++ _ = public.WriteLog(ctx, public.LogParams{+ Type: consts.LOGTYPE.Tag,+ Log: operation + " for " + g.NewVar(processedCount).String() + " contacts successfully",+ Data: map[string]interface{}{+ "tag_ids": req.TagIds,+ "contact_ids": req.Ids,+ "operation": operation,+ "total_contacts": len(req.Ids),+ "processed": processedCount,+ "skipped": skippedCount,+ "errors": errorCount,+ },+ })+++ var successMsg string+ if req.Action == 1 {+ successMsg = public.LangCtx(ctx, "Successfully added tags to {} contacts", processedCount)+ } else {+ successMsg = public.LangCtx(ctx, "Successfully removed tags from {} contacts", processedCount)+ }++ if skippedCount > 0 || errorCount > 0 {+ successMsg += public.LangCtx(ctx, " ({} skipped, {} errors)", skippedCount, errorCount)+ }++ res.SetSuccess(successMsg)+ return+}+++func (c *ControllerV1) batchAddTagsToContacts(ctx context.Context, tx gdb.TX, contactIds []int, tagIds []int) (processed, skipped, errors int, err error) {+ const batchSize = 500+ now := time.Now().Unix()+++ var existingContacts []struct {+ Id int `json:"id"`+ GroupId int `json:"group_id"`+ }+ err = tx.Model("bm_contacts").+ Fields("id, group_id").+ WhereIn("id", contactIds).+ Scan(&existingContacts)+ if err != nil && err != sql.ErrNoRows {+ g.Log().Error(ctx, "Failed to query existing contacts: %v", err)+ return 0, 0, len(contactIds), err+ }++ if len(existingContacts) == 0 {+ return 0, len(contactIds), 0, nil+ }+++ validContactIds := make([]int, len(existingContacts))+ contactGroupMap := make(map[int]int) // contact_id -> group_id+ for i, contact := range existingContacts {+ validContactIds[i] = contact.Id+ contactGroupMap[contact.Id] = contact.GroupId+ }+++ var existingTags []struct {+ Id int `json:"id"`+ GroupId int `json:"group_id"`+ Name string `json:"name"`+ }+ err = tx.Model("bm_tags").+ Fields("id, group_id, name").+ WhereIn("id", tagIds).+ Scan(&existingTags)+ if err != nil && err != sql.ErrNoRows {+ g.Log().Error(ctx, "Failed to query existing tags: %v", err)+ return 0, 0, len(contactIds), err+ }++ if len(existingTags) == 0 {+ return 0, len(contactIds), 0, nil+ }++ validTagIds := make([]int, len(existingTags))+ tagGroupMap := make(map[int]int) // tag_id -> group_id+ for i, tag := range existingTags {+ validTagIds[i] = tag.Id+ tagGroupMap[tag.Id] = tag.GroupId+ }+++ var existingTagRelations []struct {+ ContactId int `json:"contact_id"`+ TagId int `json:"tag_id"`+ }+ err = tx.Model("bm_contact_tags").+ Fields("contact_id, tag_id").+ WhereIn("contact_id", validContactIds).+ WhereIn("tag_id", validTagIds).+ Scan(&existingTagRelations)+ if err != nil && err != sql.ErrNoRows {+ g.Log().Error(ctx, "Failed to query existing tag relations: %v", err)+ return 0, 0, len(contactIds), err+ }+++ existingRelationMap := make(map[string]bool)+ for _, relation := range existingTagRelations {+ key := g.NewVar(relation.ContactId).String() + "_" + g.NewVar(relation.TagId).String()+ existingRelationMap[key] = true+ }+++ var currentBatch []g.Map+ batchCount := 0++ for _, contactId := range validContactIds {+ contactGroupId := contactGroupMap[contactId]++ for _, tagId := range validTagIds {+ tagGroupId := tagGroupMap[tagId]+++ if contactGroupId != tagGroupId {+ skipped+++ continue+ }+++ key := g.NewVar(contactId).String() + "_" + g.NewVar(tagId).String()+ if existingRelationMap[key] {+ skipped+++ continue+ }++ currentBatch = append(currentBatch, g.Map{+ "contact_id": contactId,+ "tag_id": tagId,+ "create_time": now,+ })+++ if len(currentBatch) >= batchSize {+ _, err = tx.Model("bm_contact_tags").InsertIgnore(currentBatch)+ if err != nil {+ g.Log().Error(ctx, "Failed to insert contact tags batch: %v", err)+ errors += len(currentBatch)+ } else {+ processed += len(currentBatch)+ }+ currentBatch = nil+ batchCount+++ }+ }+ }+++ if len(currentBatch) > 0 {+ _, err = tx.Model("bm_contact_tags").InsertIgnore(currentBatch)+ if err != nil {+ g.Log().Error(ctx, "Failed to insert final contact tags batch: %v", err)+ errors += len(currentBatch)+ } else {+ processed += len(currentBatch)+ }+ }+++ return processed, skipped, errors, nil+}+++func (c *ControllerV1) batchRemoveTagsFromContacts(ctx context.Context, tx gdb.TX, contactIds []int, tagIds []int) (processed, skipped, errors int, err error) {+ const batchSize = 500+++ var existingContacts []struct {+ Id int `json:"id"`+ }+ err = tx.Model("bm_contacts").+ Fields("id").+ WhereIn("id", contactIds).+ Scan(&existingContacts)+ if err != nil && err != sql.ErrNoRows {+ g.Log().Error(ctx, "Failed to query existing contacts: %v", err)+ return 0, 0, len(contactIds), err+ }++ if len(existingContacts) == 0 {+ return 0, len(contactIds), 0, nil+ }++ validContactIds := make([]int, len(existingContacts))+ for i, contact := range existingContacts {+ validContactIds[i] = contact.Id+ }+++ var existingTags []struct {+ Id int `json:"id"`+ }+ err = tx.Model("bm_tags").+ Fields("id").+ WhereIn("id", tagIds).+ Scan(&existingTags)+ if err != nil && err != sql.ErrNoRows {+ g.Log().Error(ctx, "Failed to query existing tags: %v", err)+ return 0, 0, len(contactIds), err+ }++ if len(existingTags) == 0 {+ return 0, len(contactIds), 0, nil+ }++ validTagIds := make([]int, len(existingTags))+ for i, tag := range existingTags {+ validTagIds[i] = tag.Id+ }+++ for i := 0; i < len(validContactIds); i += batchSize {+ end := i + batchSize+ if end > len(validContactIds) {+ end = len(validContactIds)+ }++ currentContactBatch := validContactIds[i:end]+++ result, err := tx.Model("bm_contact_tags").+ WhereIn("contact_id", currentContactBatch).+ WhereIn("tag_id", validTagIds).+ Delete()++ if err != nil {+ g.Log().Error(ctx, "Failed to delete contact tags batch: %v", err)+ errors += len(currentContactBatch) * len(validTagIds)+ continue+ }++ rowsAffected, _ := result.RowsAffected()+ processed += int(rowsAffected)+ }+++ totalExpected := len(validContactIds) * len(validTagIds)+ skipped = totalExpected - processed - errors+++ return processed, skipped, errors, nil+}diff --git a/core/internal/controller/contact/contact_v1_get_contacts_trend.go b/core/internal/controller/contact/contact_v1_get_contacts_trend.goindex c65f87f1..b48c05ad 100644--- a/core/internal/controller/contact/contact_v1_get_contacts_trend.go+++ b/core/internal/controller/contact/contact_v1_get_contacts_trend.go@@ -1,10 +1,13 @@package contactimport (- "billionmail-core/internal/service/contact""billionmail-core/internal/service/public""context"+ "github.com/gogf/gf/v2/database/gdb""github.com/gogf/gf/v2/errors/gerror"+ "github.com/gogf/gf/v2/frame/g"+ "strconv"+ "strings""time""billionmail-core/api/contact/v1"@@ -13,55 +16,267 @@ import (func (c *ControllerV1) GetContactsTrend(ctx context.Context, req *v1.GetContactsTrendReq) (res *v1.GetContactsTrendRes, err error) {res = &v1.GetContactsTrendRes{}- // Get trend data for the last 12 months+ var timeGranularity string+ var startTime, endTime time.Timenow := time.Now()- trends, err := contact.GetContactsTrend(ctx, now.AddDate(0, -11, 0), now, req.GroupId)- if err != nil {- res.Code = 500- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to get contacts trend: {}", err.Error())))- return++ switch req.TimeInterval {+ case 7, 30, 90, 180:+ timeGranularity = "daily"+ startTime = now.AddDate(0, 0, -req.TimeInterval).Truncate(24 * time.Hour)+ endTime = now.Truncate(24 * time.Hour).Add(24*time.Hour - time.Second)+ case 365, 0:+ timeGranularity = "monthly"+ startTime = now.AddDate(0, -11, 0).Truncate(24 * time.Hour)+ endTime = now.Truncate(24 * time.Hour).Add(24*time.Hour - time.Second)+ default:+ timeGranularity = "monthly"+ startTime = now.AddDate(0, -11, 0).Truncate(24 * time.Hour)+ endTime = now.Truncate(24 * time.Hour).Add(24*time.Hour - time.Second)+ }++ g.Log().Infof(ctx, "GetContactsTrend: TimeInterval=%d, Granularity=%s, StartTime=%s, EndTime=%s, Active=%d, LastActiveStatus=%d",+ req.TimeInterval, timeGranularity, startTime.Format("2006-01-02 15:04:05"), endTime.Format("2006-01-02 15:04:05"), req.Active, req.LastActiveStatus)++ baseModel := g.DB().Model("bm_contacts c").Safe()++ if req.GroupId > 0 {+ baseModel = baseModel.Where("c.group_id", req.GroupId)+ }++ if req.Active != -1 {+ baseModel = baseModel.Where("c.active", req.Active)}- subscribeTrend := make([]*v1.MonthlyCount, 0)- unsubscribeTrend := make([]*v1.MonthlyCount, 0)-- // Iterate through the last 12 months- for i := 11; i >= 0; i-- {- currentMonth := now.AddDate(0, -i, 0)- monthStr := currentMonth.Format("2006-01")-- // Check if the month exists in the trends data- found := false- for _, trend := range trends {- if trend.Month == monthStr {- subscribeTrend = append(subscribeTrend, &v1.MonthlyCount{- Month: monthStr,- Count: trend.SubscribeCount,- })- unsubscribeTrend = append(unsubscribeTrend, &v1.MonthlyCount{- Month: monthStr,- Count: trend.UnsubscribeCount,- })- found = true- break+ if req.Tags != "" && req.Tags != "-1" {+ tagIds := strings.Split(req.Tags, ",")+ var validTagIds []int+ for _, tagIdStr := range tagIds {+ tagIdStr = strings.TrimSpace(tagIdStr)+ if tagIdStr != "" {+ if tagId, err := strconv.Atoi(tagIdStr); err == nil && tagId > 0 {+ validTagIds = append(validTagIds, tagId)+ }}}- // No data, Add 0- if !found {- subscribeTrend = append(subscribeTrend, &v1.MonthlyCount{- Month: monthStr,- Count: 0,- })- unsubscribeTrend = append(unsubscribeTrend, &v1.MonthlyCount{- Month: monthStr,- Count: 0,- })+ if len(validTagIds) > 0 {+ baseModel = baseModel.InnerJoin("bm_contact_tags ct", "c.id = ct.contact_id").+ WhereIn("ct.tag_id", validTagIds)+ }+ }++ if req.LastActiveStatus != -1 && req.TimeInterval > 0 {+ var timeCondition time.Time+ switch req.TimeInterval {+ case 7:+ timeCondition = now.AddDate(0, 0, -7)+ case 30:+ timeCondition = now.AddDate(0, -1, 0)+ case 90:+ timeCondition = now.AddDate(0, -3, 0)+ case 180:+ timeCondition = now.AddDate(0, -6, 0)+ case 365:+ timeCondition = now.AddDate(-1, 0, 0)+ }++ timeConditionUnix := timeCondition.Unix()++ if req.LastActiveStatus == 1 {++ baseModel = baseModel.Where("c.last_active_at >= ?", timeConditionUnix)+ } else if req.LastActiveStatus == 0 {++ baseModel = baseModel.Where("c.last_active_at < ? OR c.last_active_at IS NULL OR c.last_active_at = 0", timeConditionUnix)}++ g.Log().Infof(ctx, "Active status filter applied: LastActiveStatus=%d, TimeCondition=%s",+ req.LastActiveStatus, timeCondition.Format("2006-01-02 15:04:05"))+ }++ if req.LastActiveStatus == -1 {++ startTimeUnix := startTime.Unix()+ endTimeUnix := endTime.Unix()+ baseModel = baseModel.WhereBetween("c.create_time", startTimeUnix, endTimeUnix)+ }++ res.Data.TimeGranularity = timeGranularity++ if timeGranularity == "daily" {++ err = c.getDailyTrend(ctx, baseModel, startTime, endTime, req.Active, req.LastActiveStatus, res)+ } else {++ err = c.getMonthlyTrend(ctx, baseModel, startTime, endTime, req.Active, req.LastActiveStatus, res)+ }++ if err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to get contacts trend: {}", err.Error())))+ return}- res.Data.Subscribe = subscribeTrend- res.Data.Unsubscribe = unsubscribeTrendres.SetSuccess(public.LangCtx(ctx, "Get contacts trend successfully"))return}++func (c *ControllerV1) getDailyTrend(ctx context.Context, baseModel *gdb.Model, startTime, endTime time.Time, activeFilter, lastActiveStatus int, res *v1.GetContactsTrendRes) error {++ data, err := c.getDailyTrendByStatus(ctx, baseModel, activeFilter, lastActiveStatus)+ if err != nil {+ return err+ }++ res.Data.DailyData = c.fillDailyTrendData(data, startTime, endTime)+ return nil+}++func (c *ControllerV1) getMonthlyTrend(ctx context.Context, baseModel *gdb.Model, startTime, endTime time.Time, activeFilter, lastActiveStatus int, res *v1.GetContactsTrendRes) error {++ data, err := c.getMonthlyTrendByStatus(ctx, baseModel, activeFilter, lastActiveStatus)+ if err != nil {+ return err+ }++ res.Data.MonthlyData = c.fillMonthlyTrendData(data, startTime, endTime)+ return nil+}++func (c *ControllerV1) getDailyTrendByStatus(ctx context.Context, model *gdb.Model, active, lastActiveStatus int) ([]struct {+ Date string `json:"date"`+ Count int `json:"count"`+}, error) {+ var data []struct {+ Date string `json:"date"`+ Count int `json:"count"`+ }++ var timeField string+ if lastActiveStatus != -1 {++ timeField = "c.last_active_at"+ } else {++ timeField = "c.create_time"+ }++ queryModel := model.Clone()+ if active != -1 {+ queryModel = queryModel.Where("c.active", active)+ }++ err := queryModel.+ Fields("TO_CHAR(TO_TIMESTAMP(" + timeField + "), 'YYYY-MM-DD') as date, COUNT(DISTINCT c.id) as count").+ Group("TO_CHAR(TO_TIMESTAMP(" + timeField + "), 'YYYY-MM-DD')").+ Order("date ASC").+ Scan(&data)++ if err != nil {+ g.Log().Error(ctx, "Failed to get daily trend data for active=%d, lastActiveStatus=%d: %v", active, lastActiveStatus, err)+ return nil, err+ }++ g.Log().Debug(ctx, "getDailyTrendByStatus: active=%d, lastActiveStatus=%d, timeField=%s, results=%d",+ active, lastActiveStatus, timeField, len(data))++ return data, nil+}++func (c *ControllerV1) getMonthlyTrendByStatus(ctx context.Context, model *gdb.Model, active, lastActiveStatus int) ([]struct {+ Month string `json:"month"`+ Count int `json:"count"`+}, error) {+ var data []struct {+ Month string `json:"month"`+ Count int `json:"count"`+ }++ var timeField string+ if lastActiveStatus != -1 {++ timeField = "c.last_active_at"+ } else {++ timeField = "c.create_time"+ }++ queryModel := model.Clone()+ if active != -1 {+ queryModel = queryModel.Where("c.active", active)+ }++ err := queryModel.+ Fields("TO_CHAR(TO_TIMESTAMP(" + timeField + "), 'YYYY-MM') as month, COUNT(DISTINCT c.id) as count").+ Group("TO_CHAR(TO_TIMESTAMP(" + timeField + "), 'YYYY-MM')").+ Order("month ASC").+ Scan(&data)++ if err != nil {+ g.Log().Error(ctx, "Failed to get monthly trend data for active=%d, lastActiveStatus=%d: %v", active, lastActiveStatus, err)+ return nil, err+ }++ g.Log().Debug(ctx, "getMonthlyTrendByStatus: active=%d, lastActiveStatus=%d, timeField=%s, results=%d",+ active, lastActiveStatus, timeField, len(data))++ return data, nil+}++func (c *ControllerV1) fillDailyTrendData(data []struct {+ Date string `json:"date"`+ Count int `json:"count"`+}, startTime, endTime time.Time) []*v1.DailyCount {++ dataMap := make(map[string]int)+ for _, item := range data {+ dataMap[item.Date] = item.Count+ }++ var result []*v1.DailyCount++ for d := startTime; d.Before(endTime) || d.Equal(endTime); d = d.AddDate(0, 0, 1) {+ dateStr := d.Format("2006-01-02")++ count := 0+ if c, exists := dataMap[dateStr]; exists {+ count = c+ }++ result = append(result, &v1.DailyCount{+ Date: dateStr,+ Count: count,+ })+ }++ return result+}++func (c *ControllerV1) fillMonthlyTrendData(data []struct {+ Month string `json:"month"`+ Count int `json:"count"`+}, startTime, endTime time.Time) []*v1.MonthlyCount {++ dataMap := make(map[string]int)+ for _, item := range data {+ dataMap[item.Month] = item.Count+ }++ var result []*v1.MonthlyCount++ for d := startTime; d.Before(endTime) || d.Equal(endTime); d = d.AddDate(0, 1, 0) {+ monthStr := d.Format("2006-01")++ count := 0+ if c, exists := dataMap[monthStr]; exists {+ count = c+ }++ result = append(result, &v1.MonthlyCount{+ Month: monthStr,+ Count: count,+ })+ }++ return result+}diff --git a/core/internal/controller/contact/contact_v1_get_group_info.go b/core/internal/controller/contact/contact_v1_get_group_info.goindex 5741bd79..4230331c 100644--- a/core/internal/controller/contact/contact_v1_get_group_info.go+++ b/core/internal/controller/contact/contact_v1_get_group_info.go@@ -72,6 +72,9 @@ func (c *ControllerV1) GetGroupInfo(ctx context.Context, req *v1.GetGroupInfoReqif group.UnsubscribeSubject == "" {group.UnsubscribeSubject = "You're unsubscribed"}+ if group.UnsubscribeRedirectUrl == "" {+ group.UnsubscribeRedirectUrl = hostUrl + "/unsubscribe_success.html"+ }diff --git a/core/internal/controller/contact/contact_v1_list_contacts_ndp.go b/core/internal/controller/contact/contact_v1_list_contacts_ndp.goindex ea27cc94..137a8e61 100644--- a/core/internal/controller/contact/contact_v1_list_contacts_ndp.go+++ b/core/internal/controller/contact/contact_v1_list_contacts_ndp.go@@ -1,12 +1,14 @@package contactimport (- "billionmail-core/internal/service/contact""billionmail-core/internal/service/public""context""database/sql""github.com/gogf/gf/v2/errors/gerror""github.com/gogf/gf/v2/frame/g"+ "strconv"+ "strings"+ "time""billionmail-core/api/contact/v1")@@ -21,45 +23,172 @@ func (c *ControllerV1) ListContactsNDP(ctx context.Context, req *v1.ListContactsreq.PageSize = 20}- model := g.DB().Model("bm_contacts").Safe()+ if req.SortBy == "" {+ req.SortBy = "create_time"+ }+ if req.SortOrder == "" {+ req.SortOrder = "desc"+ }++ model := g.DB().Model("bm_contacts c").Safe()if req.GroupId > 0 {- model = model.Where("group_id", req.GroupId)+ model = model.Where("c.group_id", req.GroupId)}if req.Keyword != "" {- model = model.WhereLike("email", "%"+req.Keyword+"%")+ model = model.WhereLike("c.email", "%"+req.Keyword+"%")}if req.Active != -1 {- model = model.Where("active", req.Active)+ model = model.Where("c.active", req.Active)+ }++ if req.Tags != "" && req.Tags != "-1" {+ tagIds := strings.Split(req.Tags, ",")+ var validTagIds []int+ for _, tagIdStr := range tagIds {+ tagIdStr = strings.TrimSpace(tagIdStr)+ if tagIdStr != "" {+ if tagId, err := strconv.Atoi(tagIdStr); err == nil && tagId > 0 {+ validTagIds = append(validTagIds, tagId)+ }+ }+ }++ if len(validTagIds) > 0 {++ model = model.InnerJoin("bm_contact_tags ct", "c.id = ct.contact_id").+ WhereIn("ct.tag_id", validTagIds)+ }}- total, err := model.Count()+ if req.LastActiveStatus != -1 && req.TimeInterval > 0 {+ now := time.Now()+ var timeCondition time.Time++ switch req.TimeInterval {+ case 7:+ timeCondition = now.AddDate(0, 0, -7)+ case 30:+ timeCondition = now.AddDate(0, -1, 0)+ case 90:+ timeCondition = now.AddDate(0, -3, 0)+ case 180:+ timeCondition = now.AddDate(0, -6, 0)+ case 365:+ timeCondition = now.AddDate(-1, 0, 0)+ }++ timeConditionUnix := timeCondition.Unix()++ if req.LastActiveStatus == 1 {++ model = model.Where("c.last_active_at >= ?", timeConditionUnix)+ } else if req.LastActiveStatus == 0 {++ model = model.Where("c.last_active_at < ? OR c.last_active_at IS NULL OR c.last_active_at = 0", timeConditionUnix)+ }+ }++ if req.Tags != "" && req.Tags != "-1" {+ model = model.Group("c.id")+ }++ countModel := model.Clone()+ total, err := countModel.Count()if err != nil {- res.Code = 500res.SetError(gerror.New(public.LangCtx(ctx, "Failed to get contacts count: {}", err.Error())))return}- var list []*v1.Contact- err = model.Order("create_time DESC").Page(req.Page, req.PageSize).Scan(&list)+ var orderBy string+ switch req.SortBy {+ case "create_time":+ orderBy = "c.create_time"+ case "last_active_at":+ orderBy = "c.last_active_at"+ default:+ orderBy = "c.create_time"+ }++ if req.SortOrder == "asc" {+ orderBy += " ASC"+ } else {+ orderBy += " DESC"+ }++ orderBy += ", c.id DESC"++ var contacts []*v1.Contact+ queryModel := model.Fields("c.*, cg.name as group_name").+ LeftJoin("bm_contact_groups cg", "c.group_id = cg.id")++ if req.Tags != "" && req.Tags != "-1" {+ queryModel = queryModel.Group("c.id, cg.name")+ }++ err = queryModel.Order(orderBy).+ Page(req.Page, req.PageSize).+ Scan(&contacts)+if err != nil && err != sql.ErrNoRows {- res.Code = 500res.SetError(gerror.New(public.LangCtx(ctx, "Failed to get contacts list: {}", err.Error())))return}- for email, contactInfo := range list {- groups, err := contact.GetGroup(ctx, contactInfo.GroupId)+ if len(contacts) > 0 {+ err = c.attachContactTags(ctx, contacts)if err != nil {- g.Log().Debugf(ctx, "Failed to get groups for contact %s: %v", email, err)- continue+ g.Log().Warning(ctx, "Failed to attach tags to contacts: %v", err)}-- contactInfo.GroupName = groups.Name}res.Data.Total = total- res.Data.List = list+ res.Data.List = contactsres.SetSuccess(public.LangCtx(ctx, "Get contacts list successfully"))return}++func (c *ControllerV1) attachContactTags(ctx context.Context, contacts []*v1.Contact) error {+ if len(contacts) == 0 {+ return nil+ }++ contactIds := make([]int, len(contacts))+ contactMap := make(map[int]*v1.Contact)+ for i, contact := range contacts {+ contactIds[i] = contact.Id+ contactMap[contact.Id] = contact++ contact.Tags = []v1.TagInfo{}+ }++ var contactTags []struct {+ ContactId int `json:"contact_id"`+ TagId int `json:"tag_id"`+ TagName string `json:"tag_name"`+ CreateTime int `json:"create_time"`+ }++ err := g.DB().Model("bm_contact_tags ct").+ LeftJoin("bm_tags t", "ct.tag_id = t.id").+ Fields("ct.contact_id, t.id as tag_id, t.name as tag_name, ct.create_time").+ WhereIn("ct.contact_id", contactIds).+ Order("ct.create_time DESC").+ Scan(&contactTags)+ if err != nil {+ return err+ }++ for _, contactTag := range contactTags {+ if contact, exists := contactMap[contactTag.ContactId]; exists {+ tagInfo := v1.TagInfo{+ Id: contactTag.TagId,+ Name: contactTag.TagName,+ CreateTime: contactTag.CreateTime,+ }+ contact.Tags = append(contact.Tags, tagInfo)+ }+ }++ return nil+}diff --git a/core/internal/controller/contact/contact_v1_update_group.go b/core/internal/controller/contact/contact_v1_update_group.goindex b82d6048..419b9b28 100644--- a/core/internal/controller/contact/contact_v1_update_group.go+++ b/core/internal/controller/contact/contact_v1_update_group.go@@ -24,7 +24,7 @@ func (c *ControllerV1) UpdateGroup(ctx context.Context, req *v1.UpdateGroupReq)}updateData["double_optin"] = req.DoubleOptinupdateData["send_welcome_email"] = req.SendWelcomeEmail- updateData["send_unsubscribe_email"] = req.SendUnsubscribeEmail // 新增是否发退订成功邮件+if req.WelcomeHtml != "" {updateData["welcome_mail_html"] = req.WelcomeHtml@@ -57,18 +57,7 @@ func (c *ControllerV1) UpdateGroup(ctx context.Context, req *v1.UpdateGroupReq)if req.ConfirmSubject != "" {updateData["confirm_subject"] = req.ConfirmSubject}- if req.UnsubscribeSubject != "" {- updateData["unsubscribe_subject"] = req.UnsubscribeSubject- }- if req.UnsubscribeMailHtml != "" {- updateData["unsubscribe_mail_html"] = req.UnsubscribeMailHtml- }- if req.UnsubscribeMailDrag != "" {- updateData["unsubscribe_mail_drag"] = req.UnsubscribeMailDrag- }- if req.UnsubscribeRedirectUrl != "" {- updateData["unsubscribe_redirect_url"] = req.UnsubscribeRedirectUrl- }+if len(updateData) == 0 {res.Code = 400diff --git a/core/internal/controller/contact/contact_v1_update_group_unsubscribe.go b/core/internal/controller/contact/contact_v1_update_group_unsubscribe.gonew file mode 100644index 00000000..e42214d2--- /dev/null+++ b/core/internal/controller/contact/contact_v1_update_group_unsubscribe.go@@ -0,0 +1,65 @@+package contact++import (+ "billionmail-core/internal/consts"+ "billionmail-core/internal/service/contact"+ "billionmail-core/internal/service/public"+ "context"+ "database/sql"+ "fmt"+ "github.com/gogf/gf/v2/frame/g"++ "github.com/gogf/gf/v2/errors/gerror"++ "billionmail-core/api/contact/v1"+)++func (c *ControllerV1) UpdateGroupUnsubscribe(ctx context.Context, req *v1.UpdateGroupUnsubscribeReq) (res *v1.UpdateGroupUnsubscribeRes, err error) {+ res = &v1.UpdateGroupUnsubscribeRes{}++ updateData := g.Map{}+ updateData["send_unsubscribe_email"] = req.SendUnsubscribeEmail+ if req.UnsubscribeSubject != "" {+ updateData["unsubscribe_subject"] = req.UnsubscribeSubject+ }+ if req.UnsubscribeMailHtml != "" {+ updateData["unsubscribe_mail_html"] = req.UnsubscribeMailHtml+ }+ if req.UnsubscribeMailDrag != "" {+ updateData["unsubscribe_mail_drag"] = req.UnsubscribeMailDrag+ }+ if req.UnsubscribeRedirectUrl != "" {+ updateData["unsubscribe_redirect_url"] = req.UnsubscribeRedirectUrl+ }++ if len(updateData) == 0 {+ res.Code = 400+ res.SetError(gerror.New(public.LangCtx(ctx, "No fields to update")))+ return+ }++ oldGroup, err := contact.GetGroup(ctx, req.GroupId)+ if err != nil && err != sql.ErrNoRows {+ res.Code = 404+ res.SetError(gerror.New(public.LangCtx(ctx, "Group not found")))+ return+ }++ err = contact.UpdateGroup(ctx, req.GroupId, updateData)+ if err != nil {+ res.Code = 500+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to update group: {}", err.Error())))+ return+ }+ var log string+ log = fmt.Sprintf("Update the Unsubscribe Settings for group: %s ", oldGroup.Name)++ _ = public.WriteLog(ctx, public.LogParams{+ Type: consts.LOGTYPE.ContactsGroup,+ Log: log,+ Data: updateData,+ })++ res.SetSuccess(public.LangCtx(ctx, "Group updated successfully"))+ return+}diff --git a/core/internal/controller/tags/tags_v1_batch_tag_contacts.go b/core/internal/controller/tags/tags_v1_batch_tag_contacts.goindex d34205fa..085151b4 100644--- a/core/internal/controller/tags/tags_v1_batch_tag_contacts.go+++ b/core/internal/controller/tags/tags_v1_batch_tag_contacts.go@@ -15,7 +15,6 @@ import (func (c *ControllerV1) BatchTagContacts(ctx context.Context, req *v1.BatchTagContactsReq) (res *v1.BatchTagContactsRes, err error) {res = &v1.BatchTagContactsRes{}- // 验证联系人组是否存在var groupCount intgroupCount, err = g.DB().Model("bm_contact_groups").Where("id", req.GroupId).Count()if err != nil {@@ -27,7 +26,6 @@ func (c *ControllerV1) BatchTagContacts(ctx context.Context, req *v1.BatchTagConreturn}- // 验证标签是否存在且属于该组var tag struct {Id int `json:"id"`Name string `json:"name"`@@ -47,7 +45,6 @@ func (c *ControllerV1) BatchTagContacts(ctx context.Context, req *v1.BatchTagConreturn}- // 解析邮箱列表emailList := parseEmailList(req.Data)if len(emailList) == 0 {res.SetError(gerror.New(public.LangCtx(ctx, "No valid emails provided")))@@ -59,13 +56,12 @@ func (c *ControllerV1) BatchTagContacts(ctx context.Context, req *v1.BatchTagConvar processedCount, skippedCount, errorCount int- // 执行批量标记操作err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {if req.MarkInclude == 1 {- // 标记包含:为指定邮箱添加标签+processedCount, skippedCount, errorCount, err = c.batchAddTags(ctx, tx, req.GroupId, req.TagId, emailList)} else {- // 标记���包含:为指定邮箱以外的所有邮箱添加标签+processedCount, skippedCount, errorCount, err = c.batchAddTagsExclude(ctx, tx, req.GroupId, req.TagId, emailList)}return err@@ -76,7 +72,6 @@ func (c *ControllerV1) BatchTagContacts(ctx context.Context, req *v1.BatchTagConreturn}- // 记录操作日志operation := " Include"if req.MarkInclude == 0 {operation = " Not included"@@ -97,7 +92,6 @@ func (c *ControllerV1) BatchTagContacts(ctx context.Context, req *v1.BatchTagCon},})- // 构建成功消息successMsg := public.LangCtx(ctx, "Batch tag operation completed")if req.MarkInclude == 1 {successMsg = public.LangCtx(ctx, "Successfully added tag to {} contacts", processedCount)@@ -113,12 +107,10 @@ func (c *ControllerV1) BatchTagContacts(ctx context.Context, req *v1.BatchTagConreturn}-// batchAddTags 批量添加标签func (c *ControllerV1) batchAddTags(ctx context.Context, tx gdb.TX, groupId, tagId int, emailList []string) (processed, skipped, errors int, err error) {- const batchSize = 500 // PostgreSQL 安全批量大小+ const batchSize = 500now := time.Now().Unix()- // 分批处理邮箱列表for i := 0; i < len(emailList); i += batchSize {end := i + batchSizeif end > len(emailList) {@@ -128,7 +120,6 @@ func (c *ControllerV1) batchAddTags(ctx context.Context, tx gdb.TX, groupId, tagcurrentBatch := emailList[i:end]g.Log().Debug(ctx, "Processing batch %d-%d of %d emails", i+1, end, len(emailList))- // 查询当前批次中存在于组中的联系人var existingContacts []struct {Id int `json:"id"`Email string `json:"email"`@@ -149,7 +140,6 @@ func (c *ControllerV1) batchAddTags(ctx context.Context, tx gdb.TX, groupId, tagcontinue}- // 提取联系人IDcontactIds := make([]int, len(existingContacts))emailToContactId := make(map[string]int)for j, contact := range existingContacts {@@ -157,7 +147,6 @@ func (c *ControllerV1) batchAddTags(ctx context.Context, tx gdb.TX, groupId, tagemailToContactId[contact.Email] = contact.Id}- // 查询已存在的标签关系,避免重复插入var existingTags []struct {ContactId int `json:"contact_id"`}@@ -172,13 +161,11 @@ func (c *ControllerV1) batchAddTags(ctx context.Context, tx gdb.TX, groupId, tagcontinue}- // 创建已存在标签的联系人ID集合existingTagContactIds := make(map[int]bool)for _, tag := range existingTags {existingTagContactIds[tag.ContactId] = true}- // 准备插入数据(仅插入未标记的联���人)var insertData []g.Mapfor _, contact := range existingContacts {if !existingTagContactIds[contact.Id] {@@ -191,7 +178,7 @@ func (c *ControllerV1) batchAddTags(ctx context.Context, tx gdb.TX, groupId, tag}if len(insertData) > 0 {- // 批量插入标签关系+_, err = tx.Model("bm_contact_tags").InsertIgnore(insertData)if err != nil {g.Log().Error(ctx, "Failed to insert contact tags: %v", err)@@ -201,7 +188,6 @@ func (c *ControllerV1) batchAddTags(ctx context.Context, tx gdb.TX, groupId, tagprocessed += len(insertData)}- // 计算跳过的邮箱数量(组中不存在的邮箱 + 已有标签的邮箱)skippedInBatch := len(currentBatch) - len(existingContacts) + len(existingTags)skipped += skippedInBatch}@@ -209,89 +195,20 @@ func (c *ControllerV1) batchAddTags(ctx context.Context, tx gdb.TX, groupId, tagreturn processed, skipped, errors, nil}-// batchRemoveTags 批量移除标签-func (c *ControllerV1) batchRemoveTags(ctx context.Context, tx gdb.TX, groupId, tagId int, emailList []string) (processed, skipped, errors int, err error) {- const batchSize = 500 // PostgreSQL 安全批量大小-- // 分批处理邮箱列表- for i := 0; i < len(emailList); i += batchSize {- end := i + batchSize- if end > len(emailList) {- end = len(emailList)- }-- currentBatch := emailList[i:end]- g.Log().Debug(ctx, "Processing batch %d-%d of %d emails", i+1, end, len(emailList))-- // 查询当前批次中存在于组中且有该标签的联系人- var taggedContacts []struct {- ContactId int `json:"contact_id"`- Email string `json:"email"`- }- err = tx.Model("bm_contacts c").- LeftJoin("bm_contact_tags ct", "c.id = ct.contact_id").- Fields("c.id as contact_id, c.email").- Where("c.group_id", groupId).- Where("c.active", 1).- Where("ct.tag_id", tagId).- WhereIn("c.email", currentBatch).- Scan(&taggedContacts)- if err != nil {- g.Log().Error(ctx, "Failed to query tagged contacts: %v", err)- errors += len(currentBatch)- continue- }-- if len(taggedContacts) == 0 {- skipped += len(currentBatch)- continue- }-- // 提取联系人ID- contactIds := make([]int, len(taggedContacts))- for j, contact := range taggedContacts {- contactIds[j] = contact.ContactId- }-- // 批量删除标签关系- result, err := tx.Model("bm_contact_tags").- Where("tag_id", tagId).- WhereIn("contact_id", contactIds).- Delete()- if err != nil {- g.Log().Error(ctx, "Failed to delete contact tags: %v", err)- errors += len(taggedContacts)- continue- }-- affected, _ := result.RowsAffected()- processed += int(affected)-- // 计算跳过的邮箱数量(组中不存在的邮箱或没有该标签的邮箱)- skippedInBatch := len(currentBatch) - len(taggedContacts)- skipped += skippedInBatch- }-- return processed, skipped, errors, nil-}--// batchAddTagsExclude 批量为指定邮箱以外的联系人添加标签func (c *ControllerV1) batchAddTagsExclude(ctx context.Context, tx gdb.TX, groupId, tagId int, excludeEmailList []string) (processed, skipped, errors int, err error) {- const batchSize = 500 // PostgreSQL 安全批量大小+ const batchSize = 500now := time.Now().Unix()g.Log().Infof(ctx, "batchAddTagsExclude: Excluding %d emails from tagging", len(excludeEmailList))- // 创建排除邮箱的映射表,用于快速查找excludeEmailMap := make(map[string]bool)for _, email := range excludeEmailList {excludeEmailMap[strings.ToLower(email)] = true}- // 分批查询组中的所有联系人(排除指定邮箱)var offset = 0for {- // 查询当前批次的联系人(不在排除列表中的)+var allContacts []struct {Id int `json:"id"`Email string `json:"email"`@@ -308,14 +225,12 @@ func (c *ControllerV1) batchAddTagsExclude(ctx context.Context, tx gdb.TX, groupbreak}- // 如果没有更多联系人,退出循环if len(allContacts) == 0 {break}g.Log().Debug(ctx, "Processing batch starting from offset %d, found %d contacts", offset, len(allContacts))- // 过滤出不在排除列表中的联系人var targetContacts []struct {Id int `json:"id"`Email string `json:"email"`@@ -334,13 +249,11 @@ func (c *ControllerV1) batchAddTagsExclude(ctx context.Context, tx gdb.TX, groupcontinue}- // 提取目标联系人IDtargetContactIds := make([]int, len(targetContacts))for j, contact := range targetContacts {targetContactIds[j] = contact.Id}- // 查询已存在的标签关系,避免重复插入var existingTags []struct {ContactId int `json:"contact_id"`}@@ -356,13 +269,11 @@ func (c *ControllerV1) batchAddTagsExclude(ctx context.Context, tx gdb.TX, groupcontinue}- // 创建已存在标签的联系人ID集合existingTagContactIds := make(map[int]bool)for _, tag := range existingTags {existingTagContactIds[tag.ContactId] = true}- // 准备插入数据(仅插入未标记的联系人)var insertData []g.Mapfor _, contact := range targetContacts {if !existingTagContactIds[contact.Id] {@@ -375,7 +286,7 @@ func (c *ControllerV1) batchAddTagsExclude(ctx context.Context, tx gdb.TX, group}if len(insertData) > 0 {- // 批量插入标签关系+_, err = tx.Model("bm_contact_tags").InsertIgnore(insertData)if err != nil {g.Log().Error(ctx, "Failed to insert contact tags: %v", err)@@ -386,11 +297,9 @@ func (c *ControllerV1) batchAddTagsExclude(ctx context.Context, tx gdb.TX, group}}- // 计算跳过的联系人数量(已有标签的 + 被排除的)skippedInBatch := len(allContacts) - len(targetContacts) + len(existingTags)skipped += skippedInBatch- // 如果返回的联系人数量少于批量大小,说明已经处理完所有联系人if len(allContacts) < batchSize {break}@@ -402,24 +311,22 @@ func (c *ControllerV1) batchAddTagsExclude(ctx context.Context, tx gdb.TX, groupreturn processed, skipped, errors, nil}-// parseEmailList 解析邮箱列表func parseEmailList(data string) []string {if data == "" {return nil}- // 分割邮箱,支持换行符、逗号等分隔符lines := strings.FieldsFunc(data, func(r rune) bool {return r == '\n' || r == '\r' || r == ',' || r == ';'})var emails []string- emailMap := make(map[string]bool) // 用于去重+ emailMap := make(map[string]bool)for _, line := range lines {email := strings.TrimSpace(line)if email != "" && !emailMap[email] {- // 简单的邮箱格式验证+if strings.Contains(email, "@") && strings.Contains(email, ".") {emails = append(emails, strings.ToLower(email))emailMap[email] = truediff --git a/core/internal/controller/tags/tags_v1_tag_create.go b/core/internal/controller/tags/tags_v1_tag_create.goindex 463150d3..b687b089 100644--- a/core/internal/controller/tags/tags_v1_tag_create.go+++ b/core/internal/controller/tags/tags_v1_tag_create.go@@ -53,5 +53,6 @@ func (c *ControllerV1) TagCreate(ctx context.Context, req *v1.TagCreateReq) (resData: req,})+ res.SetSuccess(public.LangCtx(ctx, "Tag created successfully"))return}