Skip to content

Commit fd0e22b

Browse files
committed
add mailer struct, fix download endpoint and make logo path generic
1 parent c59af84 commit fd0e22b

10 files changed

Lines changed: 50 additions & 43 deletions

File tree

server/app/admin_handler.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -523,7 +523,7 @@ func (a *App) CreateNewAnnouncementHandler(req *http.Request) (interface{}, Resp
523523
for _, user := range users {
524524
subject, body := internal.AdminAnnouncementMailContent(adminAnnouncement.Subject, adminAnnouncement.Body, a.config.Server.Host, user.Name())
525525

526-
err = internal.SendMail(a.config.MailSender.Email, a.config.MailSender.SendGridKey, user.Email, subject, body, "")
526+
err = a.mailer.SendMail(a.config.MailSender.Email, user.Email, subject, body)
527527
if err != nil {
528528
log.Error().Err(err).Send()
529529
return nil, InternalServerError(errors.New(internalServerErrorMsg))
@@ -585,7 +585,7 @@ func (a *App) SendEmailHandler(req *http.Request) (interface{}, Response) {
585585

586586
subject, body := internal.AdminMailContent(fmt.Sprintf("Hey! 📢 %s", emailUser.Subject), emailUser.Body, a.config.Server.Host, user.Name())
587587

588-
err = internal.SendMail(a.config.MailSender.Email, a.config.MailSender.SendGridKey, user.Email, subject, body, "")
588+
err = a.mailer.SendMail(a.config.MailSender.Email, user.Email, subject, body)
589589
if err != nil {
590590
log.Error().Err(err).Send()
591591
return nil, InternalServerError(errors.New(internalServerErrorMsg))
@@ -663,7 +663,7 @@ func (a *App) notifyAdmins() {
663663
subject, body := internal.NotifyAdminsMailContent(len(pending), a.config.Server.Host)
664664

665665
for _, admin := range admins {
666-
err = internal.SendMail(a.config.MailSender.Email, a.config.MailSender.SendGridKey, admin.Email, subject, body, "")
666+
err = a.mailer.SendMail(a.config.MailSender.Email, admin.Email, subject, body)
667667
if err != nil {
668668
log.Error().Err(err).Send()
669669
}
@@ -680,7 +680,7 @@ func (a *App) notifyAdmins() {
680680
subject, body := internal.NotifyAdminsMailLowBalanceContent(balance, a.config.Server.Host)
681681

682682
for _, admin := range admins {
683-
err = internal.SendMail(a.config.MailSender.Email, a.config.MailSender.SendGridKey, admin.Email, subject, body, "")
683+
err = a.mailer.SendMail(a.config.MailSender.Email, admin.Email, subject, body)
684684
if err != nil {
685685
log.Error().Err(err).Send()
686686
}

server/app/app.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ type App struct {
2626
db models.DB
2727
redis streams.RedisClient
2828
deployer c4sDeployer.Deployer
29+
mailer internal.Mailer
2930
}
3031

3132
// NewApp creates new server app all configurations
@@ -73,6 +74,7 @@ func NewApp(ctx context.Context, configFile string) (app *App, err error) {
7374
db: db,
7475
redis: redis,
7576
deployer: newDeployer,
77+
mailer: internal.NewMailer(config.MailSender.SendGridKey),
7678
}, nil
7779
}
7880

server/app/invoice_handler.go

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@ import (
55
"errors"
66
"fmt"
77
"net/http"
8-
"os"
9-
"path/filepath"
108
"strconv"
119
"strings"
1210
"time"
@@ -158,25 +156,9 @@ func (a *App) DownloadInvoiceHandler(req *http.Request) (interface{}, Response)
158156
return nil, NotFound(errors.New("invoice is not found"))
159157
}
160158

161-
// Get downloads dir
162-
homeDir, err := os.UserHomeDir()
163-
if err != nil {
164-
log.Error().Err(err).Send()
165-
return nil, InternalServerError(errors.New(internalServerErrorMsg))
166-
}
167-
168-
downloadsDir := filepath.Join(homeDir, "Downloads")
169-
pdfPath := filepath.Join(downloadsDir, fmt.Sprintf("invoice-%s-%d.pdf", invoice.UserID, invoice.ID))
170-
171-
err = os.WriteFile(pdfPath, invoice.FileData, 0644)
172-
if err != nil {
173-
log.Error().Err(err).Send()
174-
return nil, InternalServerError(errors.New(internalServerErrorMsg))
175-
}
176-
177-
return ResponseMsg{
178-
Message: fmt.Sprintf("Invoice is downloaded successfully at %s", pdfPath),
179-
}, Ok()
159+
return invoice.FileData, Ok().
160+
WithHeader("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fmt.Sprintf("invoice-%s-%d.pdf", invoice.UserID, invoice.ID))).
161+
WithHeader("Content-Type", "application/pdf")
180162
}
181163

182164
// PayInvoiceHandler pay user's invoice
@@ -524,9 +506,11 @@ func (a *App) sendInvoiceReminderToUser(userID, userEmail, userName string, now
524506
subject := "Unpaid Invoice Notification – Action Required"
525507
subject, body := internal.AdminMailContent(subject, mailBody, a.config.Server.Host, userName)
526508

527-
if err = internal.SendMail(
528-
a.config.MailSender.Email, a.config.MailSender.SendGridKey, userEmail, subject, body,
529-
fmt.Sprintf("invoice-%s-%d.pdf", invoice.UserID, invoice.ID), invoice.FileData,
509+
if err = a.mailer.SendMail(
510+
a.config.MailSender.Email, userEmail, subject, body, internal.Attachment{
511+
FileName: fmt.Sprintf("invoice-%s-%d.pdf", invoice.UserID, invoice.ID),
512+
Data: invoice.FileData,
513+
},
530514
); err != nil {
531515
log.Error().Err(err).Send()
532516
}

server/app/user_handler.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ func (a *App) SignUpHandler(req *http.Request) (interface{}, Response) {
145145
// send verification code if user is not verified or not exist
146146
code := internal.GenerateRandomCode()
147147
subject, body := internal.SignUpMailContent(code, a.config.MailSender.Timeout, fmt.Sprintf("%s %s", signUp.FirstName, signUp.LastName), a.config.Server.Host)
148-
err = internal.SendMail(a.config.MailSender.Email, a.config.MailSender.SendGridKey, signUp.Email, subject, body, "")
148+
err = a.mailer.SendMail(a.config.MailSender.Email, signUp.Email, subject, body)
149149
if err != nil {
150150
log.Error().Err(err).Send()
151151
return nil, InternalServerError(errors.New(internalServerErrorMsg))
@@ -245,7 +245,7 @@ func (a *App) VerifySignUpCodeHandler(req *http.Request) (interface{}, Response)
245245
middlewares.UserCreations.WithLabelValues(user.ID.String(), user.Email).Inc()
246246

247247
subject, body := internal.WelcomeMailContent(user.Name(), a.config.Server.Host)
248-
err = internal.SendMail(a.config.MailSender.Email, a.config.MailSender.SendGridKey, user.Email, subject, body, "")
248+
err = a.mailer.SendMail(a.config.MailSender.Email, user.Email, subject, body)
249249
if err != nil {
250250
log.Error().Err(err).Send()
251251
return nil, InternalServerError(errors.New(internalServerErrorMsg))
@@ -405,7 +405,7 @@ func (a *App) ForgotPasswordHandler(req *http.Request) (interface{}, Response) {
405405
// send verification code
406406
code := internal.GenerateRandomCode()
407407
subject, body := internal.ResetPasswordMailContent(code, a.config.MailSender.Timeout, user.Name(), a.config.Server.Host)
408-
err = internal.SendMail(a.config.MailSender.Email, a.config.MailSender.SendGridKey, email.Email, subject, body, "")
408+
err = a.mailer.SendMail(a.config.MailSender.Email, email.Email, subject, body)
409409

410410
if err != nil {
411411
log.Error().Err(err).Send()

server/app/voucher_handler.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ func (a *App) UpdateVoucherHandler(req *http.Request) (interface{}, Response) {
176176
subject, body = internal.RejectedVoucherMailContent(user.Name(), a.config.Server.Host)
177177
}
178178

179-
err = internal.SendMail(a.config.MailSender.Email, a.config.MailSender.SendGridKey, user.Email, subject, body, "")
179+
err = a.mailer.SendMail(a.config.MailSender.Email, user.Email, subject, body)
180180
if err != nil {
181181
log.Error().Err(err).Send()
182182
return nil, InternalServerError(errors.New(internalServerErrorMsg))
@@ -228,7 +228,7 @@ func (a *App) ApproveAllVouchersHandler(req *http.Request) (interface{}, Respons
228228
}
229229

230230
subject, body := internal.ApprovedVoucherMailContent(v.Voucher, user.Name(), a.config.Server.Host)
231-
err = internal.SendMail(a.config.MailSender.Email, a.config.MailSender.SendGridKey, user.Email, subject, body, "")
231+
err = a.mailer.SendMail(a.config.MailSender.Email, user.Email, subject, body)
232232
if err != nil {
233233
log.Error().Err(err).Send()
234234
return nil, InternalServerError(errors.New(internalServerErrorMsg))

server/app/wrapper.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,12 @@ func WrapFunc(a Handler) http.HandlerFunc {
6969
status = result.Status()
7070
}
7171

72+
if bytes, ok := object.([]byte); ok {
73+
if _, err := w.Write(bytes); err != nil {
74+
log.Error().Err(err).Msg("failed to write return object")
75+
}
76+
}
77+
7278
if err := json.NewEncoder(w).Encode(object); err != nil {
7379
log.Error().Err(err).Msg("failed to encode return object")
7480
}

server/internal/email_sender.go

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,23 @@ var (
4040
adminAnnouncement []byte
4141
)
4242

43+
type Mailer struct {
44+
client *sendgrid.Client
45+
}
46+
47+
type Attachment struct {
48+
FileName string
49+
Data []byte
50+
}
51+
52+
func NewMailer(sendGridKey string) Mailer {
53+
return Mailer{
54+
client: sendgrid.NewSendClient(sendGridKey),
55+
}
56+
}
57+
4358
// SendMail sends verification mails
44-
func SendMail(sender, sendGridKey, receiver, subject, body, attachmentName string, attachmentBytes ...[]byte) error {
59+
func (m *Mailer) SendMail(sender, receiver, subject, body string, attachments ...Attachment) error {
4560
from := mail.NewEmail("Cloud4All", sender)
4661

4762
err := validators.ValidMail(receiver)
@@ -53,18 +68,16 @@ func SendMail(sender, sendGridKey, receiver, subject, body, attachmentName strin
5368

5469
message := mail.NewSingleEmail(from, subject, to, "", body)
5570

56-
if len(attachmentBytes) > 0 {
71+
if len(attachments) > 0 {
5772
attachment := mail.NewAttachment()
58-
attachment = attachment.SetContent(base64.StdEncoding.EncodeToString(attachmentBytes[0]))
73+
attachment = attachment.SetContent(base64.StdEncoding.EncodeToString(attachments[0].Data))
5974
attachment = attachment.SetType("application/pdf")
60-
attachment = attachment.SetFilename(attachmentName)
75+
attachment = attachment.SetFilename(attachments[0].FileName)
6176
attachment = attachment.SetDisposition("attachment")
6277
message = message.AddAttachment(attachment)
6378
}
6479

65-
client := sendgrid.NewSendClient(sendGridKey)
66-
_, err = client.Send(message)
67-
80+
_, err = m.client.Send(message)
6881
return err
6982
}
7083

server/internal/email_sender_test.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,15 @@ import (
1111
)
1212

1313
func TestSendMail(t *testing.T) {
14+
m := NewMailer("1234")
15+
1416
t.Run("send valid mail", func(t *testing.T) {
15-
err := SendMail("sender@gmail.com", "1234", "receiver@gmail.com", "subject", "body", "")
17+
err := m.SendMail("sender@gmail.com", "receiver@gmail.com", "subject", "body")
1618
assert.NoError(t, err)
1719
})
1820

1921
t.Run("send invalid mail", func(t *testing.T) {
20-
err := SendMail("sender@gmail.com", "1234", "receiver", "subject", "body", "")
22+
err := m.SendMail("sender@gmail.com", "receiver", "subject", "body")
2123
assert.Error(t, err)
2224
})
2325
}

server/internal/pdf_generator.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ const (
1616
startX float64 = 25
1717
startY float64 = 30
1818

19-
logoPath = "internal/img/codescalers.png"
19+
logoPath = "internal/img/logo.png"
2020
fontPath = "internal/fonts/Arial.ttf"
2121
boldFontPath = "internal/fonts/Arial-Bold.ttf"
2222
italicFontPath = "internal/fonts/Arial-Italic.ttf"

0 commit comments

Comments
 (0)