-
Notifications
You must be signed in to change notification settings - Fork 16
/
postmark.go
234 lines (195 loc) · 7.38 KB
/
postmark.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package notifications
import (
"context"
"fmt"
"github.com/pkg/errors"
"strings"
"github.com/Boostport/mjml-go"
"github.com/aws/aws-sdk-go/aws"
awsSes "github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/mrz1836/postmark"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-common-module/notifications"
postgresEntity "github.com/openline-ai/openline-customer-os/packages/server/customer-os-postgres-repository/entity"
"github.com/openline-ai/openline-customer-os/packages/server/events-processing-platform-subscribers/logger"
"github.com/openline-ai/openline-customer-os/packages/server/events-processing-platform-subscribers/repository"
"github.com/openline-ai/openline-customer-os/packages/server/events-processing-platform-subscribers/tracing"
"github.com/opentracing/opentracing-go"
)
const (
PostmarkMessageStreamInvoice = "invoices"
)
type PostmarkEmail struct {
WorkflowId string `json:"workflowId"`
MessageStream string `json:"messageStream"`
TemplateData map[string]string `json:"templateData"`
From string `json:"from"`
To string `json:"to"`
CC []string `json:"cc"`
BCC []string `json:"bcc"`
Subject string `json:"subject"`
Attachments []PostmarkEmailAttachment
}
type PostmarkEmailAttachment struct {
Filename string
ContentEncoded string
ContentType string
ContentID string
}
type PostmarkProvider struct {
log logger.Logger
repository *repository.Repositories
}
func NewPostmarkProvider(log logger.Logger, repo *repository.Repositories) *PostmarkProvider {
return &PostmarkProvider{
log: log,
repository: repo,
}
}
func (np *PostmarkProvider) getPostmarkClient(ctx context.Context, tenant string) (*postmark.Client, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "PostmarkProvider.getPostmarkClient")
defer span.Finish()
p := np.repository.PostgresRepositories.PostmarkApiKeyRepository.GetPostmarkApiKey(tenant)
if p.Error != nil {
tracing.TraceErr(span, p.Error)
return nil, p.Error
}
if p.Result == nil {
err := errors.New("postmark api key not found")
tracing.TraceErr(span, err)
return nil, err
}
serverToken := p.Result.(*postgresEntity.PostmarkApiKey).Key
return postmark.NewClient(serverToken, ""), nil
}
func (np *PostmarkProvider) SendNotification(ctx context.Context, postmarkEmail PostmarkEmail, tenant string) error {
span, ctx := opentracing.StartSpanFromContext(ctx, "PostmarkProvider.SendNotification")
defer span.Finish()
span.SetTag(tracing.SpanTagTenant, tenant)
tracing.LogObjectAsJson(span, "postmarkEmail", postmarkEmail)
if postmarkEmail.From == "" {
np.log.Warnf("(PostmarkProvider.SendNotification) missing from email address")
return errors.New("missing from email address")
}
postmarkClient, err := np.getPostmarkClient(ctx, tenant)
if err != nil {
tracing.TraceErr(span, err)
np.log.Errorf("(PostmarkProvider.SendNotification) error: %s", err.Error())
return err
}
htmlContent, err := np.LoadEmailContent(ctx, postmarkEmail.WorkflowId, "mjml", postmarkEmail.TemplateData)
if err != nil {
tracing.TraceErr(span, err)
np.log.Errorf("(PostmarkProvider.SendNotification.LoadEmailContent) error: %s", err.Error())
return err
}
htmlContent, err = np.ConvertMjmlToHtml(ctx, htmlContent)
if err != nil {
tracing.TraceErr(span, err)
np.log.Errorf("(PostmarkProvider.SendNotification. ConvertMjmlToHtml) error: %s", err.Error())
return err
}
textContent, err := np.LoadEmailContent(ctx, postmarkEmail.WorkflowId, "txt", postmarkEmail.TemplateData)
if err != nil {
tracing.TraceErr(span, err)
np.log.Errorf("(PostmarkProvider.SendNotification.LoadEmailContent) error: %s", err.Error())
return err
}
email := postmark.Email{
From: postmarkEmail.From,
To: postmarkEmail.To,
Cc: strings.Join(postmarkEmail.CC, ","),
Bcc: strings.Join(postmarkEmail.BCC, ","),
Subject: postmarkEmail.Subject,
TextBody: textContent,
HTMLBody: htmlContent,
TrackOpens: true,
}
if postmarkEmail.MessageStream != "" {
email.MessageStream = postmarkEmail.MessageStream
}
if postmarkEmail.Attachments != nil {
for _, attachment := range postmarkEmail.Attachments {
email.Attachments = append(email.Attachments, postmark.Attachment{
Name: attachment.Filename,
Content: attachment.ContentEncoded,
ContentType: attachment.ContentType,
ContentID: attachment.ContentID,
})
}
}
_, err = postmarkClient.SendEmail(ctx, email)
if err != nil {
wrappedError := fmt.Errorf("(postmarkClient.SendEmail) error: %s", err.Error())
tracing.TraceErr(span, wrappedError)
np.log.Errorf("(PostmarkProvider.SendNotification) error: %s", err.Error())
return err
}
return nil
}
func (np *PostmarkProvider) LoadEmailContent(ctx context.Context, workflowId, fileExtension string, templateData map[string]string) (string, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "PostmarkProvider.LoadEmailContent")
defer span.Finish()
rawEmailTemplate, err := np.LoadEmailBody(ctx, workflowId, fileExtension)
if err != nil {
tracing.TraceErr(span, err)
return "", err
}
emailTemplate := np.FillTemplate(rawEmailTemplate, templateData)
return emailTemplate, nil
}
func (np *PostmarkProvider) GetFileName(workflowId, fileExtension string) string {
var fileName string
switch workflowId {
case notifications.WorkflowInvoicePaid:
fileName = "invoice.paid." + fileExtension
case notifications.WorkflowInvoicePaymentReceived:
fileName = "invoice.payment.received." + fileExtension
case notifications.WorkflowInvoiceReadyWithPaymentLink:
fileName = "invoice.ready." + fileExtension
case notifications.WorkflowInvoiceReadyNoPaymentLink:
fileName = "invoice.ready.nolink." + fileExtension
case notifications.WorkflowInvoiceVoided:
fileName = "invoice.voided." + fileExtension
}
return fileName
}
func (np *PostmarkProvider) LoadEmailBody(ctx context.Context, workflowId, fileExtension string) (string, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "PostmarkProvider.LoadEmailBody")
defer span.Finish()
fileName := np.GetFileName(workflowId, fileExtension)
session, err := awsSes.NewSession(&aws.Config{Region: aws.String("eu-west-1")})
if err != nil {
return "", err
}
downloader := s3manager.NewDownloader(session)
buffer := &aws.WriteAtBuffer{}
_, err = downloader.Download(buffer,
&s3.GetObjectInput{
Bucket: aws.String("openline-production-mjml-templates"),
Key: aws.String(fileName),
})
if err != nil {
return "", err
}
return string(buffer.Bytes()), nil
}
func (np *PostmarkProvider) FillTemplate(template string, replace map[string]string) string {
filledTemplate := template
for k, v := range replace {
filledTemplate = strings.Replace(filledTemplate, k, v, -1)
}
return filledTemplate
}
func (np *PostmarkProvider) ConvertMjmlToHtml(ctx context.Context, filledTemplate string) (string, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "PostmarkProvider.ConvertMjmlToHtml")
defer span.Finish()
html, err := mjml.ToHTML(context.Background(), filledTemplate)
var mjmlError mjml.Error
if errors.As(err, &mjmlError) {
tracing.TraceErr(span, err)
return "", fmt.Errorf("(PostmarkProvider.Template) error: %s", mjmlError.Message)
}
return html, err
}