-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
196 lines (159 loc) · 4.43 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package main
import (
"bytes"
"encoding/csv"
"fmt"
"html/template"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/dustin/go-humanize"
"gopkg.in/gomail.v2"
)
type Transaction struct {
ID int
Date time.Time
Transaction float64
}
func main() {
// Read the input file
filePath := "files/example_transactions.csv"
transactions, err := readTransactions(filePath)
if err != nil {
log.Fatal(err)
}
// Calculate summary information
totalBalance := calculateTotalBalance(transactions)
transactionCounts := groupTransactionsByMonth(transactions)
averageDebit, averageCredit := calculateAverageAmounts(transactions)
// Generate the email body
emailBody, err := generateEmailBody(totalBalance, transactionCounts, averageDebit, averageCredit)
if err != nil {
fmt.Println("Error generating email body:", err)
return
}
// Send the email
if err := sendEmail(emailBody); err != nil {
log.Fatal(err)
}
fmt.Println("Email sent successfully!")
}
func readTransactions(filePath string) ([]Transaction, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
reader := csv.NewReader(file)
reader.FieldsPerRecord = 3
records, err := reader.ReadAll()
if err != nil {
return nil, err
}
var transactions []Transaction
for i, record := range records {
// Skip the header row
if i == 0 {
continue
}
id, err := strconv.Atoi(record[0])
if err != nil {
return nil, err
}
date, err := time.Parse("1/2", record[1])
if err != nil {
return nil, err
}
transaction, err := strconv.ParseFloat(strings.TrimPrefix(record[2], "+"), 64)
if err != nil {
return nil, err
}
transactions = append(transactions, Transaction{
ID: id,
Date: date,
Transaction: transaction,
})
}
return transactions, nil
}
func calculateTotalBalance(transactions []Transaction) float64 {
var totalBalance float64
for _, transaction := range transactions {
totalBalance += transaction.Transaction
}
return totalBalance
}
func groupTransactionsByMonth(transactions []Transaction) map[string]int {
transactionCounts := make(map[string]int)
for _, transaction := range transactions {
month := transaction.Date.Format("January")
transactionCounts[month]++
}
return transactionCounts
}
func calculateAverageAmounts(transactions []Transaction) (float64, float64) {
var debitSum, creditSum float64
var debitCount, creditCount int
for _, transaction := range transactions {
if transaction.Transaction < 0 {
debitSum += transaction.Transaction
debitCount++
} else {
creditSum += transaction.Transaction
creditCount++
}
}
averageDebit := debitSum / float64(debitCount)
averageCredit := creditSum / float64(creditCount)
return averageDebit, averageCredit
}
func generateEmailBody(totalBalance float64, transactionCounts map[string]int, averageDebit, averageCredit float64) (string, error) {
// Read the HTML template from the external file
templateFile := "email/email_template.html"
templateContent, err := os.ReadFile(templateFile)
if err != nil {
return "", err
}
// Prepare the data for the email template
emailData := struct {
TotalBalance string
TransactionCounts map[string]int
AverageDebit string
AverageCredit string
}{
TotalBalance: fmt.Sprintf("$%s", humanize.FormatFloat("#,###.##", totalBalance)),
TransactionCounts: transactionCounts,
AverageDebit: fmt.Sprintf("$%s", humanize.FormatFloat("#,###.##", averageDebit)),
AverageCredit: fmt.Sprintf("$%s", humanize.FormatFloat("#,###.##", averageCredit)),
}
// Create a new template and parse the email template content
tmpl := template.New("emailTemplate")
tmpl, err = tmpl.Parse(string(templateContent))
if err != nil {
return "", err
}
// Generate the email body by executing the template with the email data
var emailBody bytes.Buffer
err = tmpl.Execute(&emailBody, emailData)
if err != nil {
return "", err
}
return emailBody.String(), nil
}
func sendEmail(body string) error {
sender := os.Getenv("SENDER_MAIL")
password := os.Getenv("PASSWORD")
recipient := os.Getenv("RECIPIENT_MAIL")
mailer := gomail.NewMessage()
mailer.SetHeader("From", sender)
mailer.SetHeader("To", recipient)
mailer.SetHeader("Subject", "Transaction Summary")
mailer.SetBody("text/html", body)
dialer := gomail.NewDialer("smtp.gmail.com", 587, sender, password)
if err := dialer.DialAndSend(mailer); err != nil {
return err
}
return nil
}