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

Improve the functions related to contacts

lotk5fe4378fcebd
diff --git a/core/api/contact/contact.go b/core/api/contact/contact.go
index b7ed3456..0227e31b 100644
--- a/core/api/contact/contact.go
+++ b/core/api/contact/contact.go
@@ -17,7 +17,10 @@ type IContactV1 interface {
DeleteGroup(ctx context.Context, req *v1.DeleteGroupReq) (res *v1.DeleteGroupRes, err error)
UpdateGroup(ctx context.Context, req *v1.UpdateGroupReq) (res *v1.UpdateGroupRes, err error)
ListGroups(ctx context.Context, req *v1.ListGroupsReq) (res *v1.ListGroupsRes, err error)
- MergeGroups(ctx context.Context, req *v1.MergeGroupsReq) (res *v1.MergeGroupsRes, 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)
+ MergeContactsGroups(ctx context.Context, req *v1.MergeContactsGroupsReq) (res *v1.MergeContactsGroupsRes, err error)
+ DeleteContacts(ctx context.Context, req *v1.DeleteContactsReq) (res *v1.DeleteContactsRes, err error)
+ UpdateContactsGroup(ctx context.Context, req *v1.UpdateContactsGroupReq) (res *v1.UpdateContactsGroupRes, err error)
+ GetContactsTrend(ctx context.Context, req *v1.GetContactsTrendReq) (res *v1.GetContactsTrendRes, err error)
}
diff --git a/core/api/contact/v1/contact.go b/core/api/contact/v1/contact.go
index dcf6b7e4..d766c852 100644
--- a/core/api/contact/v1/contact.go
+++ b/core/api/contact/v1/contact.go
@@ -24,44 +24,54 @@ type ContactGroupInfo struct {
UnsubscribeCount int `json:"unsubscribe_count" dc:"Unsubscribed Contacts"`
}
+type GroupInfo struct {
+ Id int `json:"id" dc:"Group ID"`
+ Name string `json:"name" dc:"Group Name"`
+}
+
type Contact struct {
- Id int `json:"id" dc:"Contact ID"`
- Email string `json:"email" dc:"Email Address"`
- GroupId int `json:"group_id" dc:"Group ID"`
- Active int `json:"active" dc:"Status(1:Subscribed 0:Unsubscribed)"`
- TaskId int `json:"task_id" dc:"Bulk Mail Task ID"`
- CreateTime int `json:"create_time" dc:"Create Time"`
+ Id int `json:"id" dc:"Contact ID"`
+ Email string `json:"email" dc:"Email Address"`
+ GroupId int `json:"group_id" dc:"Group ID"`
+ Active int `json:"active" dc:"Status(1:Subscribed 0:Unsubscribed)"`
+ TaskId int `json:"task_id" dc:"Bulk Mail Task ID"`
+ CreateTime int `json:"create_time" dc:"Create Time"`
+ Groups []GroupInfo `json:"groups" dc:"Contact Groups"`
}
type CreateGroupReq struct {
g.Meta `path:"/contact/group/create" method:"post" tags:"Contact" summary:"Create new contact group"`
- Authorization string `json:"authorization" dc:"Authorization" in:"header"`
- Name string `json:"name" v:"required" dc:"Group Name"`
- Description string `json:"description" dc:"Description"`
- Contacts []string `json:"contacts" dc:"Email List"`
- ImportFile string `json:"import_file" dc:"Import File"`
- FileType string `json:"file_type" dc:"File Type(csv/excel/txt)"`
- CreateType int `json:"create_type" v:"required|in:1,2,3" dc:"Create Type(1:Group Only 2:Group with Contacts 3:Group with Import)"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ GroupId int `json:"group_id" dc:"GroupID to import contacts into"`
+ Name string `json:"name" dc:"name"`
+ Description string `json:"description" dc:"description"`
+ FileData string `json:"file_data" dc:"file data"`
+ FileType string `json:"file_type" v:"in:csv,excel,txt" dc:"file type, default:txt"`
+ CreateType int `json:"create_type" v:"required|in:1,2,3" dc:"Create type (1: Create group only 2: Create new group and import contacts 3: Import files into existing groups)"`
}
type CreateGroupRes struct {
api_v1.StandardRes
}
+// ImportContactsReq Import contacts request
type ImportContactsReq struct {
g.Meta `path:"/contact/group/import" method:"post" tags:"Contact" summary:"Import contacts"`
Authorization string `json:"authorization" dc:"Authorization" in:"header"`
- GroupId int `json:"group_id" dc:"Group ID(Not required for new group)"`
- Name string `json:"name" dc:"Group Name(Required for new group)"`
- Description string `json:"description" dc:"Description(Required for new group)"`
- File string `json:"file" dc:"Contact File"`
- FileType string `json:"file_type" v:"in:csv,excel,txt" dc:"File Type"`
- ImportType int `json:"import_type" v:"required|in:1,2,3" dc:"Import Type(1:New Group 2:Existing Group 3:Group Only)"`
- DefaultActive int `json:"default_active" v:"in:0,1" dc:"Default Status(1:Subscribed 0:Unsubscribed) Default:1"`
+ GroupIds []int `json:"group_ids" v:"required" dc:"Group IDs to import contacts into"`
+ FileData string `json:"file_data" dc:"file data"`
+ FileType string `json:"file_type" v:"in:csv,excel,txt" dc:"file type, default:txt"`
+ Contacts string `json:"contacts" dc:"paste content, one email per line, optional with subscription status, format: email[,status]"`
+ ImportType int `json:"import_type" v:"required|in:1,2" dc:"Import type (1: Upload file content 2: Paste content)"`
+ DefaultActive int `json:"default_active" v:"in:0,1" dc:"Default subscription status (1: Subscribed 0: Unsubscribed) Default:1"`
}
+// ImportContactsRes Import contacts response
type ImportContactsRes struct {
api_v1.StandardRes
+ Data struct {
+ ImportedCount int `json:"imported_count" dc:"Number of successfully imported contacts"`
+ } `json:"data"`
}
type ExportContactsReq struct {
@@ -84,7 +94,6 @@ type DeleteGroupReq struct {
g.Meta `path:"/contact/group/delete" method:"post" tags:"Contact" summary:"Delete contact group"`
Authorization string `json:"authorization" dc:"Authorization" in:"header"`
GroupIds []int `json:"group_ids" v:"required" dc:"Group IDs"`
- DeleteType int `json:"delete_type" v:"required|in:1,2" dc:"Delete Type(1:With Contacts 2:Keep Contacts)"`
}
type DeleteGroupRes struct {
@@ -123,21 +132,6 @@ type ListGroupsRes struct {
} `json:"data"`
}
-type MergeGroupsReq struct {
- g.Meta `path:"/contact/group/merge" method:"post" tags:"Contact" summary:"Merge contact groups"`
- Authorization string `json:"authorization" dc:"Authorization" in:"header"`
- SourceGroupIds []int `json:"source_group_ids" v:"required" dc:"Source Group IDs"`
- TargetGroupId int `json:"target_group_id" v:"required" dc:"Target Group ID"`
-}
-
-type MergeGroupsRes struct {
- api_v1.StandardRes
- Data struct {
- TotalMerged int `json:"total_merged" dc:"Total Merged Contacts"`
- Duplicate int `json:"duplicate" dc:"Duplicate Contacts"`
- } `json:"data"`
-}
-
type ListContactsReq struct {
g.Meta `path:"/contact/list" method:"get" tags:"Contact" summary:"List all contacts"`
Authorization string `json:"authorization" dc:"Authorization" in:"header"`
@@ -145,7 +139,7 @@ type ListContactsReq struct {
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"`
- Status int `json:"status" dc:"Status(1:Subscribed 0:Unsubscribed -1:All)" default:"1"`
+ Status int `json:"status" v:"required|in:0,1" dc:"Status(1:Subscribed 0:Unsubscribed)" default:"1"`
}
type ListContactsRes struct {
@@ -168,3 +162,67 @@ type ListContactsGroupsRes struct {
List []*ContactGroup `json:"list" dc:"Group List"`
} `json:"data"`
}
+
+type MergeContactsGroupsReq struct {
+ g.Meta `path:"/contact/group/merge_contacts" method:"post" tags:"Contact" summary:"Merge contact groups"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ SourceGroups []int `json:"source_groups" v:"required" dc:"Source Group IDs"`
+ TargetGroup int `json:"target_group" v:"required" dc:"Target Group ID"`
+}
+
+type MergeContactsGroupsRes struct {
+ api_v1.StandardRes
+}
+
+type DeleteContactsReq struct {
+ g.Meta `path:"/contact/delete" method:"post" tags:"Contact" summary:"Delete contacts"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ Emails []string `json:"emails" v:"required" dc:"Email Addresses"`
+ Status int `json:"status" v:"required|in:0,1" dc:"Status to Delete(1:Subscribed 0:Unsubscribed)"`
+}
+
+type DeleteContactsRes struct {
+ api_v1.StandardRes
+ Data struct {
+ DeletedCount int `json:"deleted_count" dc:"Number of Deleted Contacts"`
+ } `json:"data"`
+}
+
+type UpdateContactsGroupReq struct {
+ g.Meta `path:"/contact/update_group" method:"post" tags:"Contact" summary:"Update contact group"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ Emails []string `json:"emails" v:"required" dc:"Email Addresses"`
+ Status int `json:"status" v:"required|in:0,1" dc:"Contact Status(1:Subscribed 0:Unsubscribed)"`
+ GroupIds []int `json:"group_ids" v:"required" dc:"New Group IDs"`
+}
+
+type UpdateContactsGroupRes struct {
+ api_v1.StandardRes
+ Data struct {
+ UpdatedCount int `json:"updated_count" dc:"Number of Updated Contacts"`
+ } `json:"data"`
+}
+
+type GetContactsTrendReq struct {
+ g.Meta `path:"/contact/trend" method:"get" tags:"Contact" summary:"Get contact trend"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+}
+
+type MonthlyTrend struct {
+ Month string `json:"month" dc:"Month Format: YYYY-MM"`
+ SubscribeCount int `json:"subscribe_count" dc:"Subscribe Count"`
+ UnsubscribeCount int `json:"unsubscribe_count" dc:"Unsubscribe Count"`
+}
+
+type GetContactsTrendRes struct {
+ api_v1.StandardRes
+ Data struct {
+ Subscribe []*MonthlyCount `json:"subscribe" dc:"Subscribe Trend"`
+ Unsubscribe []*MonthlyCount `json:"unsubscribe" dc:"Unsubscribe Trend"`
+ } `json:"data"`
+}
+
+type MonthlyCount struct {
+ Month string `json:"month" dc:"Month Format: YYYY-MM"`
+ Count int `json:"count" dc:"Count"`
+}
diff --git a/core/internal/controller/contact/contact.go b/core/internal/controller/contact/contact.go
index f0ce1685..5641fb21 100644
--- a/core/internal/controller/contact/contact.go
+++ b/core/internal/controller/contact/contact.go
@@ -32,101 +32,70 @@ const (
MaxPageSize = 100
)
-// parseContactFile Parse contact file
-// Supported formats:
-// 1. CSV/TXT: One email per line, optional status (subscribe/unsubscribe)
-// 2. Excel: Table with headers, including email and status columns
+// parseContactFile parses contact file content based on file type
func parseContactFile(fileContent []byte, fileType string) ([]*entity.Contact, error) {
- switch strings.ToLower(fileType) {
- case "csv", "txt":
+
+ // if txt format, split by line
+ if fileType == "txt" {
+ return parseTXTFile(fileContent)
+ }
+ // CSV format
+ if fileType == "csv" {
return parseCSVFile(fileContent)
- case "excel":
+ }
+ // Excel format
+ if fileType == "excel" {
return parseExcelFile(fileContent)
- default:
- return nil, gerror.New("Unsupported file format")
}
+ return nil, fmt.Errorf("unsupported file type: %s", fileType)
}
-// parseTXTFile Parse TXT file
-// Supported formats:
-// 1. One email per line
-// 2. Email,Status
+// parseTXTFile parses txt file content, one email per line
func parseTXTFile(fileContent []byte) ([]*entity.Contact, error) {
- lines := strings.Split(string(fileContent), "\n")
+ //fmt.Printf("parseTXTFile - Content length: %d bytes\n", len(fileContent))
+ //fmt.Printf("parseTXTFile - Content as string: %s\n", string(fileContent))
+
var contacts []*entity.Contact
+ lines := bytes.Split(fileContent, []byte("\n"))
for _, line := range lines {
- line = strings.TrimSpace(line)
- if line == "" {
+ // remove whitespace characters
+ email := strings.TrimSpace(string(line))
+
+ if email == "" {
continue
}
- // Try to split by comma
- parts := strings.Split(line, ",")
- email := strings.TrimSpace(parts[0])
- if !isValidEmail(email) {
+ // validate email format
+ if !validateEmail(email) {
+ fmt.Printf("parseTXTFile - Invalid email format: %s\n", email)
continue
}
- contact := &entity.Contact{
+ contacts = append(contacts, &entity.Contact{
Email: email,
- Active: 1, // Default to subscribed
- }
-
- // If status information exists
- if len(parts) > 1 {
- status := strings.ToLower(strings.TrimSpace(parts[1]))
- switch status {
- case "0", StatusUnsubscribe:
- contact.Active = 0
- }
- }
-
- contacts = append(contacts, contact)
+ Active: 1, // default subscription status
+ })
}
+ //fmt.Printf("parseTXTFile - Total valid contacts: %d\n", len(contacts))
return contacts, nil
}
-// exportContactFile Export contact file
-func exportContactFile(contacts []*entity.Contact, fileType string) ([]byte, error) {
- switch strings.ToLower(fileType) {
- case FileTypeCSV:
- return exportToCSV(contacts)
- case FileTypeExcel:
- return exportToExcel(contacts)
- case FileTypeTXT:
- return exportToTXT(contacts)
- default:
- return nil, gerror.New("Unsupported file format")
- }
-}
-
-// exportToTXT Export to TXT file
-func exportToTXT(contacts []*entity.Contact) ([]byte, error) {
- var lines []string
- for _, contact := range contacts {
- status := StatusSubscribe
- if contact.Active == 0 {
- status = StatusUnsubscribe
- }
- lines = append(lines, fmt.Sprintf("%s,%s", contact.Email, status))
- }
- return []byte(strings.Join(lines, "\n")), nil
-}
-
-// parseCSVFile Parse CSV/TXT file
-// Supported formats:
-// 1. email,status
-// 2. email
+// parseCSVFile parses CSV file content
func parseCSVFile(fileContent []byte) ([]*entity.Contact, error) {
+ // handle possible BOM
+ fileContent = bytes.TrimPrefix(fileContent, []byte("\xef\xbb\xbf"))
+
reader := csv.NewReader(bytes.NewReader(fileContent))
reader.FieldsPerRecord = -1 // Allow different number of fields per line
reader.TrimLeadingSpace = true
+ reader.LazyQuotes = true // Allow non-strict quotes
+ reader.ReuseRecord = true // Reuse record to improve performance
records, err := reader.ReadAll()
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("error reading CSV file: %v", err)
}
var contacts []*entity.Contact
@@ -140,7 +109,7 @@ func parseCSVFile(fileContent []byte) ([]*entity.Contact, error) {
}
}
- // Start processing data
+ // Process records
startIndex := 0
if hasHeader {
startIndex = 1
@@ -148,34 +117,69 @@ func parseCSVFile(fileContent []byte) ([]*entity.Contact, error) {
for i := startIndex; i < len(records); i++ {
record := records[i]
- if len(record) == 0 || record[0] == "" {
+ if len(record) == 0 {
continue
}
- contact := &entity.Contact{
- Email: strings.TrimSpace(record[0]),
- Active: 1,
+ email := strings.TrimSpace(record[0])
+ if email == "" {
+ continue
}
- // If status field exists
- if len(record) > 1 {
- status := strings.ToLower(strings.TrimSpace(record[1]))
- switch status {
- case "0", StatusUnsubscribe:
- contact.Active = 0
- }
+ // validate email format
+ if !validateEmail(email) {
+ continue
}
- if !isValidEmail(contact.Email) {
- continue
+ active := 1 // Default to active
+ if len(record) > 1 {
+ if status := strings.TrimSpace(record[1]); status == "0" {
+ active = 0
+ }
}
- contacts = append(contacts, contact)
+ contacts = append(contacts, &entity.Contact{
+ Email: email,
+ Active: active,
+ })
}
return contacts, nil
}
+// validateEmail validates email format
+func validateEmail(email string) bool {
+ // simple email format validation
+ return strings.Contains(email, "@") && strings.Contains(email, ".")
+}
+
+// exportContactFile Export contact file
+func exportContactFile(contacts []*entity.Contact, fileType string) ([]byte, error) {
+ switch strings.ToLower(fileType) {
+ case FileTypeCSV:
+ return exportToCSV(contacts)
+ case FileTypeExcel:
+ return exportToExcel(contacts)
+ case FileTypeTXT:
+ return exportToTXT(contacts)
+ default:
+ return nil, gerror.New("Unsupported file format")
+ }
+}
+
+// exportToTXT Export to TXT file
+func exportToTXT(contacts []*entity.Contact) ([]byte, error) {
+ var lines []string
+ for _, contact := range contacts {
+ status := StatusSubscribe
+ if contact.Active == 0 {
+ status = StatusUnsubscribe
+ }
+ lines = append(lines, fmt.Sprintf("%s,%s", contact.Email, status))
+ }
+ return []byte(strings.Join(lines, "\n")), nil
+}
+
// parseExcelFile Parse Excel file
func parseExcelFile(fileContent []byte) ([]*entity.Contact, error) {
// Create Excel file from byte data
diff --git a/core/internal/controller/contact/contact_v1_create_group.go b/core/internal/controller/contact/contact_v1_create_group.go
index 43b319f4..94921aff 100644
--- a/core/internal/controller/contact/contact_v1_create_group.go
+++ b/core/internal/controller/contact/contact_v1_create_group.go
@@ -2,98 +2,95 @@ package contact
import (
"billionmail-core/api/contact/v1"
- "billionmail-core/internal/model/entity"
"billionmail-core/internal/service/contact"
"billionmail-core/internal/service/public"
"context"
- "fmt"
"github.com/gogf/gf/v2/errors/gerror"
- "os"
)
func (c *ControllerV1) CreateGroup(ctx context.Context, req *v1.CreateGroupReq) (res *v1.CreateGroupRes, err error) {
res = &v1.CreateGroupRes{}
- // Check if group name exists
- exists, err := contact.CheckGroupNameExists(ctx, req.Name)
- if err != nil {
- res.Code = 500
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to check group name existence {}", err.Error())))
- return
- }
- if exists {
- res.Code = 400
- res.SetError(gerror.New(public.LangCtx(ctx, "The group name already exists")))
- return
- }
+ var groupId int
+ switch req.CreateType {
+ case 1, 2: // create new group
+ // check if group name exists
+ exists, err := contact.CheckGroupNameExists(ctx, req.Name)
+ if err != nil {
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to check group name existence {}", err.Error())))
+ return res, err
+ }
+ if exists {
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "The group name already exists")))
+ return res, err
+ }
+
+ // create new group
+ groupId, err = contact.CreateGroup(ctx, req.Name, req.Description)
+ if err != nil {
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create group {}", err.Error())))
+ return res, err
+ }
+
+ case 3: // import to existing group
+ // validate group id
+ if req.GroupId <= 0 {
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "Group ID is required for importing to existing group")))
+ return
+ }
- // Create contact group
- groupId, err := contact.CreateGroup(ctx, req.Name, req.Description)
- if err != nil {
- res.Code = 500
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create group {}", err.Error())))
- return
+ // check if group exists
+ _, err = contact.GetGroup(ctx, req.GroupId)
+ if err != nil {
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "Group {} does not exist", req.GroupId)))
+ return
+ }
+ groupId = req.GroupId
}
- // Handle contacts based on creation type
- switch req.CreateType {
- case 1: // Create group only
- break
- case 2: // Create group and add contacts
- if len(req.Contacts) > 0 {
- var contacts []*entity.Contact
- for _, email := range req.Contacts {
- contacts = append(contacts, &entity.Contact{
- Email: email,
- GroupId: groupId,
- Active: 1, // Default subscription status
- })
- }
- // Batch create contacts, ignore duplicate entries
- err = contact.BatchCreateContacts(ctx, contacts)
- if err != nil {
- res.Code = 500
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create contacts {}", err.Error())))
- return
- }
+ // if type 2 or 3, need to handle file import
+ if req.CreateType == 2 || req.CreateType == 3 {
+ if req.FileData == "" {
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "File content cannot be empty")))
+ return
}
- case 3: // Create group and import contacts
- if len(req.ImportFile) > 0 {
- fmt.Println("Creating group and importing contacts")
- // Read file content
- var fileContent []byte
- fileContent, err = os.ReadFile(req.ImportFile)
- if err != nil {
- fmt.Printf("Failed to read file: %v, file path: %s\n", err, req.ImportFile)
- res.Code = 500
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to read file {}", err.Error())))
- return
- }
- // Parse file and import contacts
- var contacts []*entity.Contact
- contacts, err = parseContactFile(fileContent, req.FileType)
- if err != nil {
- fmt.Printf("Failed to parse file: %v, file type: %s, content length: %d\n", err, req.FileType, len(fileContent))
- res.Code = 500
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to parse contact file {}", err.Error())))
- return
- }
+ // parse contacts from file content
+ contacts := parseEmailContent(req.FileData)
+ if len(contacts) == 0 {
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "No valid contacts found in file")))
+ return
+ }
- // Set group ID
- for _, contactGroupId := range contacts {
- contactGroupId.GroupId = groupId
- }
+ // set group id
+ for _, contactInfo := range contacts {
+ contactInfo.GroupId = groupId
+ }
- fmt.Printf("File parsed successfully, contact count: %d\n", len(contacts))
- err = contact.BatchCreateContacts(ctx, contacts)
- if err != nil {
- res.Code = 500
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to import contacts {}", err.Error())))
- return
- }
+ err = contact.BatchCreateContacts(ctx, contacts)
+ if err != nil {
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to import contacts {}", err.Error())))
+ return
}
}
- res.SetSuccess(public.LangCtx(ctx, "Group created successfully"))
+
+ // set success message according to different situations
+ switch req.CreateType {
+ case 1:
+ res.SetSuccess(public.LangCtx(ctx, "Group created successfully"))
+ case 2:
+ res.SetSuccess(public.LangCtx(ctx, "Group created and contacts imported successfully"))
+ case 3:
+ res.SetSuccess(public.LangCtx(ctx, "Contacts imported to existing group successfully"))
+ }
+
return
}
diff --git a/core/internal/controller/contact/contact_v1_delete_contacts.go b/core/internal/controller/contact/contact_v1_delete_contacts.go
new file mode 100644
index 00000000..48a4ee15
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_delete_contacts.go
@@ -0,0 +1,56 @@
+package contact
+
+import (
+ "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"
+
+ "billionmail-core/api/contact/v1"
+)
+
+func (c *ControllerV1) DeleteContacts(ctx context.Context, req *v1.DeleteContactsReq) (res *v1.DeleteContactsRes, err error) {
+ res = &v1.DeleteContactsRes{}
+
+ if len(req.Emails) == 0 {
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "The Emails field is required")))
+ return
+ }
+
+ if req.Status != 0 && req.Status != 1 {
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "The Status must be 0 or 1")))
+ return
+ }
+
+ // Start a transaction
+ err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
+
+ result, err := g.DB().Model("contacts").
+ Where("email IN(?)", req.Emails).
+ Where("active", req.Status).
+ Delete()
+ if err != nil {
+ return err
+ }
+
+ affected, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+
+ res.Data.DeletedCount = int(affected)
+ return nil
+ })
+
+ if err != nil {
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to delete contacts: {}", err.Error())))
+ return
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "Contacts deleted successfully"))
+ return
+}
diff --git a/core/internal/controller/contact/contact_v1_delete_group.go b/core/internal/controller/contact/contact_v1_delete_group.go
index 3e1c52df..ac1d80b2 100644
--- a/core/internal/controller/contact/contact_v1_delete_group.go
+++ b/core/internal/controller/contact/contact_v1_delete_group.go
@@ -12,11 +12,10 @@ func (c *ControllerV1) DeleteGroup(ctx context.Context, req *v1.DeleteGroupReq)
res = &v1.DeleteGroupRes{}
for _, groupId := range req.GroupIds {
- if req.DeleteType == 1 { // Delete contacts and group
- err = contact.DeleteContactsByGroupId(ctx, groupId)
- if err != nil {
- continue
- }
+
+ err = contact.DeleteContactsByGroupId(ctx, groupId)
+ if err != nil {
+ continue
}
err = contact.DeleteGroup(ctx, groupId)
diff --git a/core/internal/controller/contact/contact_v1_export_contacts.go b/core/internal/controller/contact/contact_v1_export_contacts.go
index 14cf70d9..8476908d 100644
--- a/core/internal/controller/contact/contact_v1_export_contacts.go
+++ b/core/internal/controller/contact/contact_v1_export_contacts.go
@@ -29,16 +29,17 @@ func (c *ControllerV1) ExportContacts(ctx context.Context, req *v1.ExportContact
// Create temporary directory
tempDir := filepath.Join(gfile.MainPkgPath(), "temp", "exports")
if err = gfile.Mkdir(tempDir); err != nil {
- fmt.Printf("Failed to create directory: %v, path: %s\n", err, tempDir)
+ //fmt.Printf("Failed to create directory: %v, path: %s\n", err, tempDir)
res.Code = 500
res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create temp directory")))
return
}
if req.ExportType == 1 { // Merged export
- //fmt.Println("Exporting merged contacts")
+ // Use map to handle duplicate contact status
+ contactMap := make(map[string]*entity.Contact)
+
// Get contacts from all groups
- var allContacts []*entity.Contact
for _, groupId := range req.GroupIds {
contacts, err := contact.GetContactsByGroup(ctx, groupId)
if err != nil {
@@ -46,12 +47,26 @@ func (c *ControllerV1) ExportContacts(ctx context.Context, req *v1.ExportContact
}
// Filter contacts based on IncludeInactive
for _, c := range contacts {
- if c.Active == 1 || req.IncludeInactive {
- allContacts = append(allContacts, c)
+ if existing, ok := contactMap[c.Email]; ok {
+ // If there is a status conflict (one subscribed, one unsubscribed), use the unsubscribed status
+ if existing.Active != c.Active {
+ existing.Active = 0
+ }
+ // If the status is the same, keep the original status
+ } else {
+ contactMap[c.Email] = c
}
}
}
+ // Convert to slice and apply IncludeInactive filter
+ var allContacts []*entity.Contact
+ for _, c := range contactMap {
+ if c.Active == 1 || req.IncludeInactive {
+ allContacts = append(allContacts, c)
+ }
+ }
+
// Generate filename
timestamp := gtime.Now().Format("YmdHis")
fileName := fmt.Sprintf("contacts_export_%s.%s", timestamp, req.Format)
diff --git a/core/internal/controller/contact/contact_v1_get_contacts_trend.go b/core/internal/controller/contact/contact_v1_get_contacts_trend.go
new file mode 100644
index 00000000..92608029
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_get_contacts_trend.go
@@ -0,0 +1,67 @@
+package contact
+
+import (
+ "billionmail-core/internal/service/contact"
+ "billionmail-core/internal/service/public"
+ "context"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "time"
+
+ "billionmail-core/api/contact/v1"
+)
+
+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
+ now := time.Now()
+ trends, err := contact.GetContactsTrend(ctx, now.AddDate(0, -11, 0), now)
+ if err != nil {
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to get contacts trend: {}", err.Error())))
+ return
+ }
+
+ 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
+ }
+ }
+
+ // No data, Add 0
+ if !found {
+ subscribeTrend = append(subscribeTrend, &v1.MonthlyCount{
+ Month: monthStr,
+ Count: 0,
+ })
+ unsubscribeTrend = append(unsubscribeTrend, &v1.MonthlyCount{
+ Month: monthStr,
+ Count: 0,
+ })
+ }
+ }
+
+ res.Data.Subscribe = subscribeTrend
+ res.Data.Unsubscribe = unsubscribeTrend
+ res.SetSuccess(public.LangCtx(ctx, "Get contacts trend successfully"))
+ return
+}
diff --git a/core/internal/controller/contact/contact_v1_import_contacts.go b/core/internal/controller/contact/contact_v1_import_contacts.go
index 7a0853f9..74c61993 100644
--- a/core/internal/controller/contact/contact_v1_import_contacts.go
+++ b/core/internal/controller/contact/contact_v1_import_contacts.go
@@ -3,96 +3,122 @@ package contact
import (
"billionmail-core/api/contact/v1"
+ "billionmail-core/internal/model/entity"
"billionmail-core/internal/service/contact"
"billionmail-core/internal/service/public"
"context"
- "fmt"
"github.com/gogf/gf/v2/errors/gerror"
- "os"
+ "strings"
)
-func (c *ControllerV1) ImportContacts(ctx context.Context, req *v1.ImportContactsReq) (res *v1.ImportContactsRes, err error) {
- res = &v1.ImportContactsRes{}
+// parseEmailContent parse email content
+func parseEmailContent(content string) []*entity.Contact {
+ var contacts []*entity.Contact
+ lines := strings.Split(strings.TrimSpace(content), "\n")
- // Handle group-related logic
- groupId, err := c.handleGroup(ctx, req)
- if err != nil {
- return res, err
- }
-
- // Return directly if only creating new group
- if req.ImportType == 3 {
- res.SetSuccess(public.LangCtx(ctx, "Group created successfully"))
- return res, nil
- }
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
+ if line == "" {
+ continue
+ }
- // Read file content
- fileContent, err := os.ReadFile(req.File)
- if err != nil {
- fmt.Println("Failed to read file: ", err.Error(), "Path: ", req.File, "File type: ", req.FileType, "Group ID: ", groupId)
- res.Code = 500
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to read file: {}", err.Error())))
- return
- }
+ // parse email and status
+ parts := strings.Split(line, ",")
+ email := strings.TrimSpace(parts[0])
+ active := 1 // default subscription status
- // Parse file content
- contacts, err := parseContactFile(fileContent, req.FileType)
- if err != nil {
- fmt.Println("Failed to parse file: ", err.Error(), "Path: ", req.File, "File type: ", req.FileType, "Group ID: ", groupId)
- res.Code = 500
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to parse contact file: {}", err.Error())))
- return res, nil
- }
+ // if there is status information
+ if len(parts) > 1 {
+ status := strings.TrimSpace(parts[1])
+ if status == "0" {
+ active = 0
+ }
+ }
- // Set default status
- for _, email := range contacts {
- email.GroupId = groupId
- if email.Active < 0 {
- email.Active = req.DefaultActive
+ if email != "" {
+ contacts = append(contacts, &entity.Contact{
+ Email: email,
+ Active: active,
+ })
}
}
+ return contacts
+}
+
+func (c *ControllerV1) ImportContacts(ctx context.Context, req *v1.ImportContactsReq) (res *v1.ImportContactsRes, err error) {
+ res = &v1.ImportContactsRes{}
- // Import contacts
- err = contact.BatchCreateContacts(ctx, contacts)
- if err != nil {
- res.Code = 500
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to import contacts: {}", err.Error())))
+ if len(req.GroupIds) == 0 {
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "Group IDs cannot be empty")))
return
}
- res.SetSuccess(public.LangCtx(ctx, "Contacts imported successfully"))
- return res, nil
-}
-
-// handleGroup Process group-related logic
-func (c *ControllerV1) handleGroup(ctx context.Context, req *v1.ImportContactsReq) (groupId int, err error) {
- switch req.ImportType {
- case 1, 3: // Create new group and import OR Create group only
- // Check if group name exists
- exists, err := contact.CheckGroupNameExists(ctx, req.Name)
+ for _, groupId := range req.GroupIds {
+ _, err = contact.GetGroup(ctx, groupId)
if err != nil {
- return 0, gerror.New(public.LangCtx(ctx, "Failed to check group name: {}", err.Error()))
- }
- if exists {
- return 0, gerror.New(public.LangCtx(ctx, "The group name already exists"))
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "Group {} does not exist", groupId)))
+ return
}
+ }
- groupId, err = contact.CreateGroup(ctx, req.Name, req.Description)
- if err != nil {
- return 0, gerror.New(public.LangCtx(ctx, "Failed to create group: {}", err.Error()))
+ var contactList []*entity.Contact
+
+ // handle content according to import type
+ switch req.ImportType {
+ case 1: // file upload
+ if req.FileData == "" {
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "File content cannot be empty")))
+ return
}
- return groupId, nil
+ contactList = parseEmailContent(req.FileData)
- case 2: // Import to existing group
- groupId = req.GroupId
- // Check if group exists
- _, err = contact.GetGroup(ctx, groupId)
- if err != nil {
- return 0, gerror.New(public.LangCtx(ctx, "Group does not exist"))
+ case 2: // paste content
+ if req.Contacts == "" {
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "Contacts content cannot be empty")))
+ return
}
- return groupId, nil
+ contactList = parseEmailContent(req.Contacts)
default:
- return 0, gerror.New(public.LangCtx(ctx, "Invalid import type"))
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "Invalid import type")))
+ return
}
+
+ if len(contactList) == 0 {
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "No valid contacts found")))
+ return
+ }
+
+ // import contacts to each group
+ successCount := 0
+ for _, groupId := range req.GroupIds {
+ // prepare contacts data for current group
+ var groupContacts []*entity.Contact
+ for _, c := range contactList {
+ contactInfo := *c // create a copy
+ contactInfo.GroupId = groupId
+ groupContacts = append(groupContacts, &contactInfo)
+ }
+
+ // batch create new contacts, ignore duplicate data
+ if len(groupContacts) > 0 {
+ count, err := contact.BatchCreateContactsIgnoreDuplicate(ctx, groupContacts)
+ if err != nil {
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to import contacts: {}", err.Error())))
+ return nil, err
+ }
+ successCount += count
+ }
+ }
+
+ res.Data.ImportedCount = successCount
+ res.SetSuccess(public.LangCtx(ctx, "Successfully imported {} contacts", successCount))
+ return
}
diff --git a/core/internal/controller/contact/contact_v1_list_contacts.go b/core/internal/controller/contact/contact_v1_list_contacts.go
index b01e1191..995111f5 100644
--- a/core/internal/controller/contact/contact_v1_list_contacts.go
+++ b/core/internal/controller/contact/contact_v1_list_contacts.go
@@ -4,8 +4,8 @@ import (
"billionmail-core/internal/service/contact"
"billionmail-core/internal/service/public"
"context"
- "fmt"
"github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
"billionmail-core/api/contact/v1"
)
@@ -19,29 +19,53 @@ func (c *ControllerV1) ListContacts(ctx context.Context, req *v1.ListContactsReq
if req.PageSize < 1 || req.PageSize > MaxPageSize {
req.PageSize = DefaultPageSize
}
- if req.Status < -1 || req.Status > 1 {
- req.Status = 1 // Default get all status
+ if req.Status < 0 || req.Status > 1 {
+ req.Status = 1 // Default to active
}
// Get contacts list
total, list, err := contact.GetContactsWithPage(ctx, req.Page, req.PageSize, req.GroupId, req.Keyword, req.Status)
if err != nil {
- fmt.Printf("Failed to get contacts list: %v, group ID: %d, keyword: %s, status: %d\n", err, req.GroupId, req.Keyword, req.Status)
+ g.Log().Errorf(ctx, "Failed to get contacts list: %v, group ID: %d, keyword: %s, status: %d", err, req.GroupId, req.Keyword, req.Status)
res.Code = 500
res.SetError(gerror.New(public.LangCtx(ctx, "Failed to get contacts list: {}", err.Error())))
return
}
- // Convert to API response format
- apiList := make([]*v1.Contact, len(list))
- for i, contactOne := range list {
- apiList[i] = &v1.Contact{
- Id: contactOne.Id,
- Email: contactOne.Email,
- GroupId: contactOne.GroupId,
- Active: contactOne.Active,
- TaskId: contactOne.TaskId,
- CreateTime: contactOne.CreateTime,
+ apiList := make([]*v1.Contact, 0)
+ emailMap := make(map[string]*v1.Contact)
+
+ // filter out duplicate emails
+ for _, contactOne := range list {
+ if _, exists := emailMap[contactOne.Email]; !exists {
+ contactInfo := &v1.Contact{
+ Id: contactOne.Id,
+ Email: contactOne.Email,
+ GroupId: contactOne.GroupId,
+ Active: contactOne.Active,
+ TaskId: contactOne.TaskId,
+ CreateTime: contactOne.CreateTime,
+ Groups: make([]v1.GroupInfo, 0),
+ }
+ emailMap[contactOne.Email] = contactInfo
+ apiList = append(apiList, contactInfo)
+ }
+ }
+
+ // Get groups for each contact
+ for email, contactInfo := range emailMap {
+ groups, err := contact.GetContactGroupsInfo(ctx, email, req.Status)
+ if err != nil {
+ g.Log().Warningf(ctx, "Failed to get groups for contact %s: %v", email, err)
+ continue
+ }
+
+ // Add group information to the contact
+ for _, group := range groups {
+ contactInfo.Groups = append(contactInfo.Groups, v1.GroupInfo{
+ Id: group.Id,
+ Name: group.Name,
+ })
}
}
diff --git a/core/internal/controller/contact/contact_v1_merge_contacts_groups.go b/core/internal/controller/contact/contact_v1_merge_contacts_groups.go
new file mode 100644
index 00000000..c0c176ab
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_merge_contacts_groups.go
@@ -0,0 +1,147 @@
+package contact
+
+import (
+ "billionmail-core/internal/model/entity"
+ "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"
+ "time"
+
+ "billionmail-core/api/contact/v1"
+)
+
+func (c *ControllerV1) MergeContactsGroups(ctx context.Context, req *v1.MergeContactsGroupsReq) (res *v1.MergeContactsGroupsRes, err error) {
+ res = &v1.MergeContactsGroupsRes{}
+
+ const batchSize = 1000 // Batch size
+
+ err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
+
+ _, err := contact.GetGroup(ctx, req.TargetGroup)
+ if err != nil {
+ return gerror.New(public.LangCtx(ctx, "Target group not found"))
+ }
+
+ for _, sourceId := range req.SourceGroups {
+ if _, err := contact.GetGroup(ctx, sourceId); err != nil {
+ return gerror.New(public.LangCtx(ctx, "Source group {} not found", sourceId))
+ }
+ }
+
+ // Batch process data
+ offset := 0
+ emailStatusMap := make(map[string]int)
+
+ for {
+ // 1. Batch get source group contacts
+ var contacts []*entity.Contact
+ err = g.DB().Model("contacts").
+ Where("group_id IN(?)", req.SourceGroups).
+ Limit(batchSize).
+ Offset(offset).
+ Scan(&contacts)
+
+ if err != nil {
+ return err
+ }
+
+ // If there is no more data, exit the loop
+ if len(contacts) == 0 {
+ break
+ }
+
+ // 2. Process the status of this batch of contacts
+ for _, contactInfo := range contacts {
+ key := contactInfo.Email
+ if existingStatus, ok := emailStatusMap[key]; ok {
+ // Only use unsubscribed status when the status is different
+ if contactInfo.Active != existingStatus {
+ emailStatusMap[key] = 0
+ }
+ } else {
+ emailStatusMap[key] = contactInfo.Active
+ }
+ }
+
+ offset += batchSize
+
+ // If this batch of data is less than batchSize, it is the last batch
+ if len(contacts) < batchSize {
+ break
+ }
+ }
+
+ // 3. Batch check existing contacts in the target group
+ var existingEmails []string
+ err = g.DB().Model("contacts").
+ Fields("email").
+ Where("group_id = ?", req.TargetGroup).
+ Where("email IN (?)", getMapKeys(emailStatusMap)).
+ Scan(&existingEmails)
+
+ if err != nil {
+ return err
+ }
+
+ // Convert existing emails to map for quick lookup
+ existingEmailMap := make(map[string]bool)
+ for _, email := range existingEmails {
+ existingEmailMap[email] = true
+ }
+
+ // 4. Prepare data for insertion
+ now := time.Now().Unix()
+ var insertData []g.Map
+
+ for email, status := range emailStatusMap {
+ // If the email is not in the target group, add it to the insertion list
+ if !existingEmailMap[email] {
+ insertData = append(insertData, g.Map{
+ "email": email,
+ "group_id": req.TargetGroup,
+ "active": status,
+ "create_time": now,
+ })
+ }
+ }
+
+ // 5. Batch insert data
+ for i := 0; i < len(insertData); i += batchSize {
+ end := i + batchSize
+ if end > len(insertData) {
+ end = len(insertData)
+ }
+
+ _, err = g.DB().Model("contacts").
+ Data(insertData[i:end]).
+ Insert()
+
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to merge contact groups: {}", err.Error())))
+ return
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "Contact groups merged successfully"))
+ return
+}
+
+// getMapKeys Get all keys of map
+func getMapKeys(m map[string]int) []string {
+ keys := make([]string, 0, len(m))
+ for k := range m {
+ keys = append(keys, k)
+ }
+ return keys
+}
diff --git a/core/internal/controller/contact/contact_v1_merge_groups.go b/core/internal/controller/contact/contact_v1_merge_groups.go
deleted file mode 100644
index 32cb9e43..00000000
--- a/core/internal/controller/contact/contact_v1_merge_groups.go
+++ /dev/null
@@ -1,46 +0,0 @@
-// core/internal/controller/contact/contact_v1_merge_groups.go
-package contact
-
-import (
- "billionmail-core/api/contact/v1"
- "billionmail-core/internal/service/contact"
- "billionmail-core/internal/service/public"
- "context"
- "github.com/gogf/gf/v2/errors/gerror"
-)
-
-func (c *ControllerV1) MergeGroups(ctx context.Context, req *v1.MergeGroupsReq) (res *v1.MergeGroupsRes, err error) {
- res = &v1.MergeGroupsRes{}
-
- // Get target group
- targetGroup, err := contact.GetGroup(ctx, req.TargetGroupId)
- if err != nil {
- res.Code = 400
- res.SetError(gerror.New(public.LangCtx(ctx, "Target group not found")))
- return
- }
-
- // Merge contacts from each source group
- for _, sourceGroupId := range req.SourceGroupIds {
- // Get contacts from source group
- contacts, err := contact.GetContactsByGroup(ctx, sourceGroupId)
- if err != nil {
- continue
- }
-
- // Update contact group ID
- for _, email := range contacts {
- email.GroupId = targetGroup.Id
- }
-
- // Batch update contacts
- err = contact.BatchCreateContacts(ctx, contacts)
- if err != nil {
- res.Data.Duplicate += len(contacts)
- continue
- }
-
- res.Data.TotalMerged += len(contacts)
- }
- return
-}
diff --git a/core/internal/controller/contact/contact_v1_update_contacts_group.go b/core/internal/controller/contact/contact_v1_update_contacts_group.go
new file mode 100644
index 00000000..540da63a
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_update_contacts_group.go
@@ -0,0 +1,44 @@
+package contact
+
+import (
+ "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"
+
+ "billionmail-core/api/contact/v1"
+)
+
+func (c *ControllerV1) UpdateContactsGroup(ctx context.Context, req *v1.UpdateContactsGroupReq) (res *v1.UpdateContactsGroupRes, err error) {
+ res = &v1.UpdateContactsGroupRes{}
+
+ // Start transaction
+ err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
+ // Verify if all target groups exist
+ for _, groupId := range req.GroupIds {
+ if _, err := contact.GetGroup(ctx, groupId); err != nil {
+ return gerror.New(public.LangCtx(ctx, "Group {} not found", groupId))
+ }
+ }
+
+ // Update contact group
+ updatedCount, err := contact.UpdateContactsGroups(ctx, req.Emails, req.Status, req.GroupIds)
+ if err != nil {
+ return err
+ }
+
+ res.Data.UpdatedCount = updatedCount
+ return nil
+ })
+
+ if err != nil {
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to update contacts group: {}", err.Error())))
+ return
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "Contacts group updated successfully"))
+ return
+}
diff --git a/core/internal/service/contact/contact.go b/core/internal/service/contact/contact.go
index ca1ed9eb..6016931e 100644
--- a/core/internal/service/contact/contact.go
+++ b/core/internal/service/contact/contact.go
@@ -53,7 +53,6 @@ func UpdateGroup(ctx context.Context, id int, data g.Map) error {
return err
}
-// DeleteContactsByGroupId
func DeleteContactsByGroupId(ctx context.Context, groupId int) error {
_, err := g.DB().Model("contacts").Ctx(ctx).Where("group_id", groupId).Delete()
return err
@@ -64,22 +63,9 @@ func DeleteGroup(ctx context.Context, id int) error {
return err
}
-func CreateContacts(ctx context.Context, contact *entity.Contact) error {
- now := time.Now().Unix()
- data := g.Map{
- "email": contact.Email,
- "group_id": contact.GroupId,
- "active": contact.Active,
- "task_id": contact.TaskId,
- "create_time": int(now),
- }
- _, err := g.DB().Model("contacts").Ctx(ctx).Data(data).InsertAndGetId()
- return err
-}
-
-func BatchCreateContacts(ctx context.Context, contacts []*entity.Contact) error {
+func BatchCreateContactsIgnoreDuplicate(ctx context.Context, contacts []*entity.Contact) (int, error) {
if len(contacts) == 0 {
- return nil
+ return 0, nil
}
now := time.Now().Unix()
var data []g.Map
@@ -93,14 +79,18 @@ func BatchCreateContacts(ctx context.Context, contacts []*entity.Contact) error
})
}
- _, err := g.DB().Model("contacts").Ctx(ctx).Data(data).InsertIgnore()
- return err
+ result, err := g.DB().Model("contacts").Ctx(ctx).Data(data).InsertIgnore()
+ if err != nil {
+ return 0, err
+ }
+
+ affected, err := result.RowsAffected()
+ return int(affected), err
}
-func GetContact(ctx context.Context, id int) (*entity.Contact, error) {
- var contact entity.Contact
- err := g.DB().Model("contacts").Ctx(ctx).Where("id", id).Scan(&contact)
- return &contact, err
+func BatchCreateContacts(ctx context.Context, contacts []*entity.Contact) error {
+ _, err := BatchCreateContactsIgnoreDuplicate(ctx, contacts)
+ return err
}
func GetContactsByGroup(ctx context.Context, groupId int) ([]*entity.Contact, error) {
@@ -109,21 +99,6 @@ func GetContactsByGroup(ctx context.Context, groupId int) ([]*entity.Contact, er
return contacts, err
}
-func UpdateContact(ctx context.Context, id int, data g.Map) error {
- _, err := g.DB().Model("contacts").Ctx(ctx).Data(data).Where("id", id).Update()
- return err
-}
-
-func DeleteContact(ctx context.Context, id int) error {
- _, err := g.DB().Model("contacts").Ctx(ctx).Where("id", id).Delete()
- return err
-}
-
-func BatchDeleteContacts(ctx context.Context, ids []int) error {
- _, err := g.DB().Model("contacts").Ctx(ctx).Where("id", ids).Delete()
- return err
-}
-
func CountContactsByGroup(ctx context.Context, groupId int, active int) (int, error) {
model := g.DB().Model("contacts").Ctx(ctx).Where("group_id", groupId)
if active >= 0 {
@@ -140,7 +115,6 @@ func CheckGroupNameExists(ctx context.Context, name string) (bool, error) {
return count > 0, nil
}
-// Get contact list (with pagination and search)
func ContactsGroupWithPage(ctx context.Context, page, pageSize int, keyword string) ([]*entity.ContactGroup, int, error) {
if page <= 0 {
@@ -173,32 +147,6 @@ func ContactsGroupWithPage(ctx context.Context, page, pageSize int, keyword stri
return groups, total, err
}
-// Get contacts in group (with pagination)
-func GetContactsByGroupWithPage(ctx context.Context, groupId int, page, pageSize int) ([]*entity.Contact, int, error) {
- model := g.DB().Model("contacts").Ctx(ctx).Where("group_id", groupId)
-
- // Get total
- total, err := model.Count()
- if err != nil {
- return nil, 0, err
- }
-
- // Pagination query
- var contacts []*entity.Contact
- err = model.Page(page, pageSize).Scan(&contacts)
- return contacts, total, err
-}
-
-// Batch update contact status
-func BatchUpdateContactStatus(ctx context.Context, groupId int, active int) error {
- _, err := g.DB().Model("contacts").Ctx(ctx).
- Where("group_id", groupId).
- Data(g.Map{"active": active}).
- Update()
- return err
-}
-
-// GetContactsWithPage
func GetContactsWithPage(ctx context.Context, page, pageSize int, groupId int, keyword string, status int) (total int, list []*entity.Contact, err error) {
model := g.DB().Model("contacts").Safe()
@@ -209,28 +157,52 @@ func GetContactsWithPage(ctx context.Context, page, pageSize int, groupId int, k
if len(keyword) > 0 {
keywordPattern := "%" + keyword + "%"
- model = model.WhereLike("email", keywordPattern).WhereOrLike("full_name", keywordPattern)
+ model = model.WhereLike("email", keywordPattern)
}
if status != -1 {
model = model.Where("active", status)
}
- // Get total
- total, err = model.Count()
+ // Get total with distinct email
+ value, err := model.Fields("COUNT(DISTINCT email) as count").Value()
if err != nil {
return 0, nil, err
}
+ total = value.Int()
// If no data, return directly
if total == 0 {
return 0, make([]*entity.Contact, 0), nil
}
- // Pagination query, create time descending
+ // Construct the query conditions
+ conditions := g.Map{}
+ if groupId > 0 {
+ conditions["group_id"] = groupId
+ }
+ if status != -1 {
+ conditions["active"] = status
+ }
+
+ subQuery := g.DB().Model("contacts").
+ Fields("DISTINCT ON (email) id")
+
+ if len(conditions) > 0 {
+ subQuery = subQuery.Where(conditions)
+ }
+ if len(keyword) > 0 {
+ keywordPattern := "%" + keyword + "%"
+ subQuery = subQuery.WhereLike("email", keywordPattern)
+ }
+
+ subQuery = subQuery.Order("email, create_time DESC")
+
list = make([]*entity.Contact, 0)
- err = model.Page(page, pageSize).
- Order("create_time desc").
+ err = g.DB().Model("contacts c").
+ Where("c.id IN (?)", subQuery).
+ Order("c.create_time DESC").
+ Page(page, pageSize).
Scan(&list)
if err != nil {
return 0, nil, err
@@ -238,3 +210,85 @@ func GetContactsWithPage(ctx context.Context, page, pageSize int, groupId int, k
return total, list, nil
}
+
+// Gets the group information to which the contact belongs
+func GetContactGroupsInfo(ctx context.Context, email string, status int) ([]*entity.ContactGroup, error) {
+ var groups []*entity.ContactGroup
+
+ err := g.DB().Model("contacts c").
+ LeftJoin("contact_groups g", "c.group_id = g.id").
+ Fields("DISTINCT g.id, g.name, g.description, g.create_time, g.update_time").
+ Where("c.email", email).
+ Where("c.active", status).
+ Scan(&groups)
+
+ if err != nil {
+ return nil, err
+ }
+
+ return groups, nil
+}
+
+func GetContactsTrend(ctx context.Context, startTime, endTime time.Time) ([]*struct {
+ Month string `json:"month"`
+ SubscribeCount int `json:"subscribe_count"`
+ UnsubscribeCount int `json:"unsubscribe_count"`
+}, error) {
+ var trends []*struct {
+ Month string `json:"month"`
+ SubscribeCount int `json:"subscribe_count"`
+ UnsubscribeCount int `json:"unsubscribe_count"`
+ }
+
+ err := g.DB().Model("contacts").
+ Fields(
+ "to_char(to_timestamp(create_time), 'YYYY-MM') as month",
+ "SUM(CASE WHEN active = 1 THEN 1 ELSE 0 END) as subscribe_count",
+ "SUM(CASE WHEN active = 0 THEN 1 ELSE 0 END) as unsubscribe_count",
+ ).
+ Where("create_time BETWEEN ? AND ?", startTime.Unix(), endTime.Unix()).
+ Group("month").
+ Order("month ASC").
+ Scan(&trends)
+
+ return trends, err
+}
+
+func UpdateContactsGroups(ctx context.Context, emails []string, status int, newGroupIds []int) (int, error) {
+ // 1. delete old group relations
+ _, err := g.DB().Model("contacts").
+ Where("email IN(?)", emails).
+ Where("active", status).
+ Delete()
+ if err != nil {
+ return 0, err
+ }
+
+ // 2. create new group relations
+ now := time.Now().Unix()
+ var data []g.Map
+ for _, email := range emails {
+ for _, groupId := range newGroupIds {
+ data = append(data, g.Map{
+ "email": email,
+ "group_id": groupId,
+ "active": status,
+ "create_time": now,
+ })
+ }
+ }
+
+ if len(data) == 0 {
+ return 0, nil
+ }
+
+ result, err := g.DB().Model("contacts").
+ Data(data).
+ Insert()
+ if err != nil {
+ return 0, err
+ }
+
+ affected, err := result.RowsAffected()
+ return int(affected), err
+}