Skip to content

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

Add Contacts controller

lotk9d15cb5ddc2b
diff --git a/core/internal/controller/contact/contact.go b/core/internal/controller/contact/contact.go
new file mode 100644
index 00000000..f0ce1685
--- /dev/null
+++ b/core/internal/controller/contact/contact.go
@@ -0,0 +1,359 @@
+// =================================================================================
+// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
+// =================================================================================
+
+package contact
+
+import (
+ "billionmail-core/internal/model/entity"
+ "bytes"
+ "encoding/csv"
+ "fmt"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/xuri/excelize/v2"
+ "strings"
+)
+
+const (
+ FileTypeCSV = "csv"
+ FileTypeExcel = "excel"
+ FileTypeTXT = "txt"
+)
+
+// Status constants
+const (
+ StatusSubscribe = "subscribe"
+ StatusUnsubscribe = "unsubscribe"
+)
+
+const (
+ DefaultPage = 1
+ DefaultPageSize = 10
+ 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
+func parseContactFile(fileContent []byte, fileType string) ([]*entity.Contact, error) {
+ switch strings.ToLower(fileType) {
+ case "csv", "txt":
+ return parseCSVFile(fileContent)
+ case "excel":
+ return parseExcelFile(fileContent)
+ default:
+ return nil, gerror.New("Unsupported file format")
+ }
+}
+
+// parseTXTFile Parse TXT file
+// Supported formats:
+// 1. One email per line
+// 2. Email,Status
+func parseTXTFile(fileContent []byte) ([]*entity.Contact, error) {
+ lines := strings.Split(string(fileContent), "\n")
+ var contacts []*entity.Contact
+
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
+ if line == "" {
+ continue
+ }
+
+ // Try to split by comma
+ parts := strings.Split(line, ",")
+ email := strings.TrimSpace(parts[0])
+ if !isValidEmail(email) {
+ continue
+ }
+
+ contact := &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)
+ }
+
+ 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
+func parseCSVFile(fileContent []byte) ([]*entity.Contact, error) {
+ reader := csv.NewReader(bytes.NewReader(fileContent))
+ reader.FieldsPerRecord = -1 // Allow different number of fields per line
+ reader.TrimLeadingSpace = true
+
+ records, err := reader.ReadAll()
+ if err != nil {
+ return nil, err
+ }
+
+ var contacts []*entity.Contact
+ var hasHeader bool
+
+ // Check if header exists
+ if len(records) > 0 {
+ firstRow := records[0]
+ if len(firstRow) >= 1 && strings.ToLower(firstRow[0]) == "email" {
+ hasHeader = true
+ }
+ }
+
+ // Start processing data
+ startIndex := 0
+ if hasHeader {
+ startIndex = 1
+ }
+
+ for i := startIndex; i < len(records); i++ {
+ record := records[i]
+ if len(record) == 0 || record[0] == "" {
+ continue
+ }
+
+ contact := &entity.Contact{
+ Email: strings.TrimSpace(record[0]),
+ Active: 1,
+ }
+
+ // If status field exists
+ if len(record) > 1 {
+ status := strings.ToLower(strings.TrimSpace(record[1]))
+ switch status {
+ case "0", StatusUnsubscribe:
+ contact.Active = 0
+ }
+ }
+
+ if !isValidEmail(contact.Email) {
+ continue
+ }
+
+ contacts = append(contacts, contact)
+ }
+
+ return contacts, nil
+}
+
+// parseExcelFile Parse Excel file
+func parseExcelFile(fileContent []byte) ([]*entity.Contact, error) {
+ // Create Excel file from byte data
+ f, err := excelize.OpenReader(bytes.NewReader(fileContent))
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ // Get first sheet
+ sheets := f.GetSheetList()
+ if len(sheets) == 0 {
+ return nil, gerror.New("Excel file has no sheets")
+ }
+
+ rows, err := f.GetRows(sheets[0])
+ if err != nil {
+ return nil, err
+ }
+
+ var contacts []*entity.Contact
+ var emailCol, statusCol int
+ var hasHeader bool
+
+ // Check for header and determine column positions
+ if len(rows) > 0 {
+ for i, cell := range rows[0] {
+ switch strings.ToLower(strings.TrimSpace(cell)) {
+ case "email":
+ emailCol = i
+ hasHeader = true
+ case "status":
+ statusCol = i
+ hasHeader = true
+ }
+ }
+ }
+
+ // If email column not found, assume first column is email
+ if !hasHeader {
+ emailCol = 0
+ }
+
+ startIndex := 0
+ if hasHeader {
+ startIndex = 1
+ }
+
+ for i := startIndex; i < len(rows); i++ {
+ row := rows[i]
+ if len(row) <= emailCol {
+ continue
+ }
+
+ email := strings.TrimSpace(row[emailCol])
+ if email == "" {
+ continue
+ }
+
+ contact := &entity.Contact{
+ Email: email,
+ Active: 1,
+ }
+
+ if statusCol < len(row) {
+ status := strings.ToLower(strings.TrimSpace(row[statusCol]))
+ switch status {
+ case "0", StatusUnsubscribe:
+ contact.Active = 0
+ }
+ }
+
+ if !isValidEmail(contact.Email) {
+ continue
+ }
+
+ contacts = append(contacts, contact)
+ }
+
+ return contacts, nil
+}
+
+// isValidEmail Validate email format
+func isValidEmail(email string) bool {
+
+ if !strings.Contains(email, "@") || !strings.Contains(email, ".") {
+ return false
+ }
+
+ parts := strings.Split(email, "@")
+ if len(parts) != 2 {
+ return false
+ }
+
+ localPart := parts[0]
+ domain := parts[1]
+
+ if localPart == "" || domain == "" {
+ return false
+ }
+
+ if !strings.Contains(domain, ".") {
+ return false
+ }
+
+ if len(email) > 254 {
+ return false
+ }
+
+ return true
+}
+
+// exportToCSV Export contacts to CSV file
+func exportToCSV(contacts []*entity.Contact) ([]byte, error) {
+ buf := new(bytes.Buffer)
+ writer := csv.NewWriter(buf)
+
+ // header
+ err := writer.Write([]string{"Email", "Status"})
+ if err != nil {
+ return nil, err
+ }
+
+ // data
+ for _, contact := range contacts {
+ status := StatusSubscribe
+ if contact.Active == 0 {
+ status = StatusUnsubscribe
+ }
+
+ err := writer.Write([]string{
+ contact.Email,
+ status,
+ })
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ writer.Flush()
+ if err := writer.Error(); err != nil {
+ return nil, err
+ }
+
+ return buf.Bytes(), nil
+}
+
+// exportToExcel Export contacts to Excel file
+func exportToExcel(contacts []*entity.Contact) ([]byte, error) {
+ f := excelize.NewFile()
+ defer f.Close()
+
+ // Create header
+ f.SetCellValue("Sheet1", "A1", "Email")
+ f.SetCellValue("Sheet1", "B1", "Status")
+
+ // Write data
+ for i, contact := range contacts {
+ row := i + 2 // Start writing data from second row
+ status := StatusSubscribe
+ if contact.Active == 0 {
+ status = StatusUnsubscribe
+ }
+
+ f.SetCellValue("Sheet1", fmt.Sprintf("A%d", row), contact.Email)
+ f.SetCellValue("Sheet1", fmt.Sprintf("B%d", row), status)
+ }
+
+ // Set column width
+ f.SetColWidth("Sheet1", "A", "A", 30)
+ f.SetColWidth("Sheet1", "B", "B", 15)
+ f.SetColWidth("Sheet1", "C", "C", 20)
+
+ // Export to byte array
+ buf, err := f.WriteToBuffer()
+ if err != nil {
+ return nil, err
+ }
+
+ return buf.Bytes(), nil
+}
diff --git a/core/internal/controller/contact/contact_new.go b/core/internal/controller/contact/contact_new.go
new file mode 100644
index 00000000..cc312e92
--- /dev/null
+++ b/core/internal/controller/contact/contact_new.go
@@ -0,0 +1,15 @@
+// =================================================================================
+// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
+// =================================================================================
+
+package contact
+
+import (
+ "billionmail-core/api/contact"
+)
+
+type ControllerV1 struct{}
+
+func NewV1() contact.IContactV1 {
+ return &ControllerV1{}
+}
diff --git a/core/internal/controller/contact/contact_v1_create_group.go b/core/internal/controller/contact/contact_v1_create_group.go
new file mode 100644
index 00000000..43b319f4
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_create_group.go
@@ -0,0 +1,99 @@
+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
+ }
+
+ // 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
+ }
+
+ // 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
+ }
+ }
+ 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
+ }
+
+ // Set group ID
+ for _, contactGroupId := range contacts {
+ contactGroupId.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
+ }
+ }
+ }
+ res.SetSuccess(public.LangCtx(ctx, "Group created successfully"))
+ return
+}
diff --git a/core/internal/controller/contact/contact_v1_delete_group.go b/core/internal/controller/contact/contact_v1_delete_group.go
new file mode 100644
index 00000000..3e1c52df
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_delete_group.go
@@ -0,0 +1,37 @@
+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) DeleteGroup(ctx context.Context, req *v1.DeleteGroupReq) (res *v1.DeleteGroupRes, err error) {
+ 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.DeleteGroup(ctx, groupId)
+ if err != nil {
+ res.Data.FailedCount++
+ continue
+ }
+ res.Data.SuccessCount++
+ }
+ if res.Data.SuccessCount == 0 && res.Data.FailedCount == 0 {
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "No groups were deleted")))
+ return
+ }
+ res.SetSuccess(public.LangCtx(ctx, "Groups deleted successfully"))
+
+ return
+}
diff --git a/core/internal/controller/contact/contact_v1_export_contacts.go b/core/internal/controller/contact/contact_v1_export_contacts.go
new file mode 100644
index 00000000..14cf70d9
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_export_contacts.go
@@ -0,0 +1,205 @@
+// core/internal/controller/contact/contact_v1_export_contacts.go
+package contact
+
+import (
+ "archive/zip"
+ "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"
+ "github.com/gogf/gf/v2/os/gfile"
+ "github.com/gogf/gf/v2/os/gtime"
+ "io"
+ "os"
+ "path/filepath"
+)
+
+func (c *ControllerV1) ExportContacts(ctx context.Context, req *v1.ExportContactsReq) (res *v1.ExportContactsRes, err error) {
+ res = &v1.ExportContactsRes{}
+
+ // Set default value for including inactive contacts
+ if req.IncludeInactive == false {
+ // Default to true if not explicitly set in request
+ req.IncludeInactive = true
+ }
+
+ // 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)
+ 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")
+ // Get contacts from all groups
+ var allContacts []*entity.Contact
+ for _, groupId := range req.GroupIds {
+ contacts, err := contact.GetContactsByGroup(ctx, groupId)
+ if err != nil {
+ continue
+ }
+ // Filter contacts based on IncludeInactive
+ for _, c := range contacts {
+ 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)
+ filePath := filepath.Join(tempDir, fileName)
+ fmt.Println("File path: ", filePath)
+
+ // Export file based on format
+ var fileContent []byte
+ fileContent, err = exportContactFile(allContacts, req.Format)
+ if err != nil {
+ fmt.Println("Export file error: ", err)
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to export contacts")))
+ return
+ }
+
+ // Write file
+ if err = gfile.PutBytes(filePath, fileContent); err != nil {
+ fmt.Println("Write file error: ", err)
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to save file")))
+ return
+ }
+
+ res.Data.FileUrl = filePath
+
+ } else { // Separate export
+ var files []ExportFile
+ totalContacts := 0
+
+ // Create file for each group
+ for _, groupId := range req.GroupIds {
+ group, err := contact.GetGroup(ctx, groupId)
+ if err != nil {
+ continue
+ }
+
+ contacts, err := contact.GetContactsByGroup(ctx, groupId)
+ if err != nil {
+ continue
+ }
+
+ // Filter contacts based on IncludeInactive
+ var filteredContacts []*entity.Contact
+ for _, c := range contacts {
+ if c.Active == 1 || req.IncludeInactive {
+ filteredContacts = append(filteredContacts, c)
+ }
+ }
+
+ if len(filteredContacts) == 0 {
+ continue
+ }
+
+ // Generate filename
+ fileName := fmt.Sprintf("%s.%s", group.Name, req.Format)
+ filePath := filepath.Join(tempDir, fileName)
+
+ // Export file
+ fileContent, err := exportContactFile(filteredContacts, req.Format)
+ if err != nil {
+ continue
+ }
+
+ // Write file
+ if err = gfile.PutBytes(filePath, fileContent); err != nil {
+ continue
+ }
+
+ files = append(files, ExportFile{
+ Path: filePath,
+ Name: fileName,
+ Contacts: len(filteredContacts),
+ })
+ totalContacts += len(filteredContacts)
+ }
+
+ if len(files) == 0 {
+ // fmt.Println("No contacts found")
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "No contacts to export")))
+ return
+ }
+
+ // Create ZIP file
+ timestamp := gtime.Now().Format("YmdHis")
+ zipFileName := fmt.Sprintf("contacts_export_%s.zip", timestamp)
+ zipPath := filepath.Join(tempDir, zipFileName)
+
+ if err = createZipFile(files, zipPath); err != nil {
+ fmt.Println("Create ZIP file error: ", err)
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create zip file")))
+ return
+ }
+
+ // Clean up temporary files
+ for _, file := range files {
+ os.Remove(file.Path)
+ }
+
+ res.Data.FileUrl = zipPath
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "Contacts exported successfully"))
+ return
+}
+
+// ExportFile Export file information
+type ExportFile struct {
+ Path string // File path
+ Name string // File name
+ Contacts int // Contact count
+}
+
+// createZipFile Create ZIP file
+func createZipFile(files []ExportFile, zipPath string) error {
+ // Create zip file
+ zipFile, err := os.Create(zipPath)
+ if err != nil {
+ return fmt.Errorf("failed to create zip file: %v", err)
+ }
+ defer zipFile.Close()
+
+ // Create zip writer
+ zipWriter := zip.NewWriter(zipFile)
+ defer zipWriter.Close()
+
+ // Iterate through source files
+ for _, file := range files {
+ // Open source file
+ srcFile, err := os.Open(file.Path)
+ if err != nil {
+ return fmt.Errorf("failed to open source file %s: %v", file.Path, err)
+ }
+ defer srcFile.Close()
+
+ // Create zip entry
+ zipEntry, err := zipWriter.Create(file.Name)
+ if err != nil {
+ return fmt.Errorf("failed to create zip entry for %s: %v", file.Name, err)
+ }
+
+ // Copy file content to zip
+ if _, err := io.Copy(zipEntry, srcFile); err != nil {
+ return fmt.Errorf("failed to copy file content to zip for %s: %v", file.Name, err)
+ }
+ }
+
+ return nil
+}
diff --git a/core/internal/controller/contact/contact_v1_import_contacts.go b/core/internal/controller/contact/contact_v1_import_contacts.go
new file mode 100644
index 00000000..7a0853f9
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_import_contacts.go
@@ -0,0 +1,98 @@
+// core/internal/controller/contact/contact_v1_import_contacts.go
+package contact
+
+import (
+ "billionmail-core/api/contact/v1"
+ "billionmail-core/internal/service/contact"
+ "billionmail-core/internal/service/public"
+ "context"
+ "fmt"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "os"
+)
+
+func (c *ControllerV1) ImportContacts(ctx context.Context, req *v1.ImportContactsReq) (res *v1.ImportContactsRes, err error) {
+ res = &v1.ImportContactsRes{}
+
+ // 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
+ }
+
+ // 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 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
+ }
+
+ // Set default status
+ for _, email := range contacts {
+ email.GroupId = groupId
+ if email.Active < 0 {
+ email.Active = req.DefaultActive
+ }
+ }
+
+ // 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())))
+ 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)
+ 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"))
+ }
+
+ 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()))
+ }
+ return groupId, nil
+
+ 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"))
+ }
+ return groupId, nil
+
+ default:
+ return 0, gerror.New(public.LangCtx(ctx, "Invalid import type"))
+ }
+}
diff --git a/core/internal/controller/contact/contact_v1_list_contacts.go b/core/internal/controller/contact/contact_v1_list_contacts.go
new file mode 100644
index 00000000..b01e1191
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_list_contacts.go
@@ -0,0 +1,52 @@
+package contact
+
+import (
+ "billionmail-core/internal/service/contact"
+ "billionmail-core/internal/service/public"
+ "context"
+ "fmt"
+ "github.com/gogf/gf/v2/errors/gerror"
+
+ "billionmail-core/api/contact/v1"
+)
+
+func (c *ControllerV1) ListContacts(ctx context.Context, req *v1.ListContactsReq) (res *v1.ListContactsRes, err error) {
+ res = &v1.ListContactsRes{}
+
+ if req.Page < 1 {
+ req.Page = DefaultPage
+ }
+ if req.PageSize < 1 || req.PageSize > MaxPageSize {
+ req.PageSize = DefaultPageSize
+ }
+ if req.Status < -1 || req.Status > 1 {
+ req.Status = 1 // Default get all status
+ }
+
+ // 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)
+ 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,
+ }
+ }
+
+ res.Data.Total = total
+ res.Data.List = apiList
+ res.SetSuccess(public.LangCtx(ctx, "Get contacts list successfully"))
+ return
+}
diff --git a/core/internal/controller/contact/contact_v1_list_contacts_groups.go b/core/internal/controller/contact/contact_v1_list_contacts_groups.go
new file mode 100644
index 00000000..db585167
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_list_contacts_groups.go
@@ -0,0 +1,22 @@
+package contact
+
+import (
+ "billionmail-core/internal/service/contact"
+ "billionmail-core/internal/service/public"
+ "context"
+
+ "billionmail-core/api/contact/v1"
+)
+
+func (c *ControllerV1) ListContactsGroups(ctx context.Context, req *v1.ListContactsGroupsReq) (res *v1.ListContactsGroupsRes, err error) {
+ res = &v1.ListContactsGroupsRes{}
+
+ groups, err := contact.GetAllGroups(ctx, req.Keyword)
+ if err != nil {
+ return nil, err
+ }
+
+ res.Data.List = groups
+ res.SetSuccess(public.LangCtx(ctx, "Get all contact groups successfully"))
+ return
+}
diff --git a/core/internal/controller/contact/contact_v1_list_groups.go b/core/internal/controller/contact/contact_v1_list_groups.go
new file mode 100644
index 00000000..48089222
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_list_groups.go
@@ -0,0 +1,66 @@
+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) ListGroups(ctx context.Context, req *v1.ListGroupsReq) (res *v1.ListGroupsRes, err error) {
+
+ res = &v1.ListGroupsRes{}
+ // Handle request parameters
+ page := req.Page
+ if page <= 0 {
+ page = DefaultPage
+ }
+
+ pageSize := req.PageSize
+ if pageSize <= 0 {
+ pageSize = DefaultPageSize
+ }
+
+ // Get group list
+ groups, total, err := contact.ContactsGroupWithPage(ctx, page, pageSize, req.Keyword)
+ if err != nil {
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to get group list {}", err.Error())))
+ return
+ }
+
+ // Convert group information
+ groupInfos := make([]*v1.ContactGroupInfo, 0, len(groups))
+ for _, group := range groups {
+ // Get statistics information
+ activeCount, err := contact.CountContactsByGroup(ctx, group.Id, 1)
+ if err != nil {
+ activeCount = 0
+ }
+
+ unsubscribeCount, err := contact.CountContactsByGroup(ctx, group.Id, 0)
+ if err != nil {
+ unsubscribeCount = 0
+ }
+
+ // Convert to group information
+ groupInfo := &v1.ContactGroupInfo{
+ Id: group.Id,
+ Name: group.Name,
+ Description: group.Description,
+ CreateTime: group.CreateTime,
+ UpdateTime: group.UpdateTime,
+ TotalCount: activeCount + unsubscribeCount,
+ ActiveCount: activeCount,
+ UnsubscribeCount: unsubscribeCount,
+ }
+ groupInfos = append(groupInfos, groupInfo)
+ }
+
+ res.Data.Total = total
+ res.Data.List = groupInfos
+ res.SetSuccess(public.LangCtx(ctx, "Group list retrieved successfully"))
+ return
+
+}
diff --git a/core/internal/controller/contact/contact_v1_merge_groups.go b/core/internal/controller/contact/contact_v1_merge_groups.go
new file mode 100644
index 00000000..32cb9e43
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_merge_groups.go
@@ -0,0 +1,46 @@
+// 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_group.go b/core/internal/controller/contact/contact_v1_update_group.go
new file mode 100644
index 00000000..402f69b9
--- /dev/null
+++ b/core/internal/controller/contact/contact_v1_update_group.go
@@ -0,0 +1,31 @@
+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"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+func (c *ControllerV1) UpdateGroup(ctx context.Context, req *v1.UpdateGroupReq) (res *v1.UpdateGroupRes, err error) {
+ res = &v1.UpdateGroupRes{}
+
+ data := g.Map{}
+ if req.Name != "" {
+ data["name"] = req.Name
+ }
+ if req.Description != "" {
+ data["description"] = req.Description
+ }
+
+ err = contact.UpdateGroup(ctx, req.GroupId, data)
+ if err != nil {
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to update group: {}", err.Error())))
+ return
+ }
+ res.SetSuccess(public.LangCtx(ctx, "Group updated successfully"))
+ return
+}