-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcampaign_service.go
337 lines (277 loc) · 7.51 KB
/
campaign_service.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package service
import (
"context"
"errors"
"fmt"
"io"
"path"
"strings"
"time"
"github.com/fahmifan/mailmerger"
"github.com/fahmifan/ulids"
"github.com/rs/zerolog/log"
"gorm.io/gorm"
"gorm.io/gorm/utils"
)
var ErrNotFound = errors.New("not found error")
type Audit struct {
CreatedAt time.Time `gorm:"type:datetime"`
UpdatedAt time.Time `gorm:"type:datetime"`
DeletedAt gorm.DeletedAt `gorm:"index;type:datetime"`
}
type Campaign struct {
ID ulids.ULID `gorm:"primary_key"`
FileID *ulids.ULID
Name string
Body string
Subject string
TemplateID *ulids.ULID
Audit
File File
Events []Event
Template *Template `gorm:"->;foreignKey:TemplateID"`
}
func (c Campaign) HasNoTemplate() bool {
return c.TemplateID == nil || c.Template == nil
}
func (c *Campaign) BeforeCreate(tx *gorm.DB) error {
omitFields := []string{"Events"}
gormOmit(tx, omitFields...)
return nil
}
func (c *Campaign) BeforeUpdate(tx *gorm.DB) error {
omitFields := []string{"Events"}
gormOmit(tx, omitFields...)
return nil
}
func gormOmit(tx *gorm.DB, columns ...string) {
if len(columns) == 1 && strings.ContainsRune(columns[0], ',') {
tx.Statement.Omits = strings.FieldsFunc(columns[0], utils.IsValidDBNameChar)
} else {
tx.Statement.Omits = columns
}
}
func (c Campaign) IsNoEvent() bool {
return len(c.Events) == 0
}
func (c Campaign) RenderTemplate() (io.Reader, error) {
if c.HasNoTemplate() {
return strings.NewReader(c.Body), nil
}
return NewCampaignRenderer(c.Body, c.Template).Render()
}
type File struct {
ID ulids.ULID `gorm:"primary_key"`
Folder string
FileName string
Audit
}
type EventStatus string
const (
EventStatusSuccess EventStatus = "success"
EventStatusFailed EventStatus = "failed"
)
type Event struct {
ID ulids.ULID
CampaignID ulids.ULID `gorm:"references:CampaignID"`
Detail string
CreatedAt time.Time
Status EventStatus
}
type BlastEmailConfig struct {
Sender string
Concurrency uint
Transporter mailmerger.Transporter
}
type CampaignService struct {
cfg *Config
}
const CampaignBucket = "campaigns"
type CreateCampaignRequest struct {
Name string `form:"name"`
BodyTemplate string `form:"body"`
SubjectTemplate string `form:"subject"`
CSV io.Reader `form:"-"`
TemplateID *ulids.ULID `form:"-"`
}
func (c *CampaignService) Create(ctx context.Context, req CreateCampaignRequest) (campaign Campaign, err error) {
tx := c.cfg.db.WithContext(ctx)
campaign = Campaign{
ID: ulids.New(),
Name: req.Name,
TemplateID: req.TemplateID,
}
if req.CSV != nil {
file, err := c.createFileIfAny(ctx, req.CSV)
if err != nil {
return Campaign{}, err
}
campaign.FileID = &file.ID
}
campaign.Body = req.BodyTemplate
campaign.Subject = req.SubjectTemplate
if err = tx.Create(&campaign).Error; err != nil {
return Campaign{}, err
}
return campaign, nil
}
const csvFolder = "csvs"
func (c *CampaignService) createFileIfAny(ctx context.Context, csvFile io.Reader) (_ File, err error) {
id := ulids.New()
fileName := id.String() + ".csv"
filePath := path.Join(csvFolder, fileName)
err = c.cfg.localStorage.Save(ctx, filePath, csvFile)
if err != nil {
return File{}, err
}
file := File{
ID: id,
Folder: filePath,
FileName: fileName,
}
if err = c.cfg.db.Create(&file).Error; err != nil {
return File{}, err
}
return file, nil
}
func (c *CampaignService) List(ctx context.Context) (campaigns []Campaign, err error) {
if err = c.cfg.db.Model(&Campaign{}).
Preload("Events").
Preload("File").
Order("created_at desc").
Find(&campaigns).
Error; err != nil {
return
}
return
}
func (c *CampaignService) Find(ctx context.Context, id ulids.ULID) (campaign Campaign, err error) {
if err = c.cfg.db.
Preload("Template").
Preload("File").
Preload("Events").
Take(&campaign, "id = ?", id).
Error; err != nil {
return
}
return campaign, nil
}
type UpdateCampaignRequest struct {
ID ulids.ULID `form:"id"`
Name string `form:"name"`
Body string `form:"body"`
Subject string `form:"subject"`
CSV io.Reader `form:"-"`
TemplateID *ulids.ULID `form:"-"`
}
func (c *CampaignService) Update(ctx context.Context, req UpdateCampaignRequest) (_ Campaign, err error) {
campaign, err := c.Find(ctx, req.ID)
if err != nil {
return
}
campaign.Name = req.Name
campaign.Body = req.Body
campaign.Subject = req.Subject
campaign.TemplateID = req.TemplateID
if req.CSV != nil {
campaign.File, err = c.createFileIfAny(ctx, req.CSV)
if err != nil {
return Campaign{}, err
}
campaign.FileID = &campaign.File.ID
}
payload := map[string]interface{}{
"name": campaign.Name,
"body": campaign.Body,
"subject": campaign.Subject,
"template_id": campaign.TemplateID,
"updated_at": "now()",
}
if err = c.cfg.db.Model(&campaign).Updates(payload).Error; err != nil {
return Campaign{}, err
}
return campaign, nil
}
type CreateBlastEmailEventRequest struct {
CampaignID ulids.ULID `form:"campaign_id"`
}
// CreateBlastEmailEvent create an event
func (c *CampaignService) CreateBlastEmailEvent(ctx context.Context, req CreateBlastEmailEventRequest) (event Event, err error) {
campaign, err := c.Find(ctx, req.CampaignID)
if err != nil {
return
}
body, err := campaign.RenderTemplate()
if err != nil {
return Event{}, fmt.Errorf("render: %w", err)
}
csvFile, err := c.cfg.localStorage.Seek(ctx, campaign.File.Folder)
if err != nil {
return
}
defer csvFile.Close()
mailer := mailmerger.NewMailer(&mailmerger.MailerConfig{
SenderEmail: c.cfg.blastEmailCfg.Sender,
CsvSrc: csvFile,
BodyTemplate: body,
SubjectTemplate: strings.NewReader(campaign.Subject),
Concurrency: 2,
Transporter: c.cfg.blastEmailCfg.Transporter,
})
if err = mailer.Parse(); err != nil {
return
}
event = Event{
ID: ulids.New(),
CampaignID: campaign.ID,
Status: EventStatusSuccess,
}
if err = mailer.SendAll(ctx); err != nil {
log.Err(err).Msg("sendAll")
event.Status = EventStatusFailed
event.Detail = err.Error()
}
err = c.cfg.db.Create(&event).Error
if err != nil {
return Event{}, err
}
return event, nil
}
func (c *CampaignService) Delete(ctx context.Context, id ulids.ULID) (campaign Campaign, err error) {
if campaign, err = c.Find(ctx, id); err != nil {
return Campaign{}, fmt.Errorf("find old campaign: %w", err)
}
if err = c.cfg.db.WithContext(ctx).Delete(&campaign).Error; err != nil {
return Campaign{}, fmt.Errorf("delete: %w", err)
}
return campaign, nil
}
func (c *CampaignService) RenderBytes(campaign Campaign) ([]byte, error) {
buf, err := campaign.RenderTemplate()
if err != nil {
return nil, fmt.Errorf("render bytes: %w", err)
}
return io.ReadAll(buf)
}
func (c *CampaignService) RenderByBodyAndTemplate(ctx context.Context, templateID ulids.ULID, body string) (result []byte, err error) {
template, err := c.findTemplateByID(ctx, templateID)
if err != nil {
return nil, fmt.Errorf("find template: %w", err)
}
rendered, err := NewCampaignRenderer(body, &template).Render()
if err != nil {
return nil, fmt.Errorf("render: %w", err)
}
buf, err := io.ReadAll(rendered)
if err != nil {
return nil, fmt.Errorf("read rendered")
}
return buf, nil
}
func (c *CampaignService) findTemplateByID(ctx context.Context, templateID ulids.ULID) (tpl Template, err error) {
err = c.cfg.db.WithContext(ctx).Take(&tpl, "id = ?", templateID).Error
if err != nil {
return Template{}, unwrapErr(err)
}
return tpl, nil
}