1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00

feat: email reports (resolve #124)

This commit is contained in:
Ferdinand Mütsch
2021-04-30 14:07:14 +02:00
parent 1beca82875
commit 29c04c3ac5
23 changed files with 913 additions and 468 deletions

View File

@@ -16,7 +16,7 @@ const (
aggregateIntervalDays int = 1
)
var lock = sync.Mutex{}
var aggregationLock = sync.Mutex{}
type AggregationService struct {
config *config.Config
@@ -157,8 +157,8 @@ func (srv *AggregationService) trigger(jobs chan<- *AggregationJob, userIds map[
}
func (srv *AggregationService) lockUsers(userIds map[string]bool) error {
lock.Lock()
defer lock.Unlock()
aggregationLock.Lock()
defer aggregationLock.Unlock()
for uid := range userIds {
if _, ok := srv.inProgress[uid]; ok {
return errors.New("aggregation already in progress for at least of the request users")
@@ -171,8 +171,8 @@ func (srv *AggregationService) lockUsers(userIds map[string]bool) error {
}
func (srv *AggregationService) unlockUsers(userIds map[string]bool) {
lock.Lock()
defer lock.Unlock()
aggregationLock.Lock()
defer aggregationLock.Unlock()
for uid := range userIds {
delete(srv.inProgress, uid)
}

View File

@@ -3,8 +3,10 @@ package mail
import (
"bytes"
"fmt"
"github.com/muety/wakapi/models"
"github.com/muety/wakapi/routes"
"html/template"
"io/ioutil"
"text/template"
conf "github.com/muety/wakapi/config"
"github.com/muety/wakapi/services"
@@ -14,8 +16,10 @@ import (
const (
tplNamePasswordReset = "reset_password"
tplNameImportNotification = "import_finished"
tplNameReport = "report"
subjectPasswordReset = "Wakapi Password Reset"
subjectImportNotification = "Wakapi Data Import Finished"
subjectReport = "Wakapi Your Latest Report"
)
type PasswordResetTplData struct {
@@ -28,6 +32,10 @@ type ImportNotificationTplData struct {
NumHeartbeats int
}
type ReportTplData struct {
Report *models.Report
}
// Factory
func NewMailService() services.IMailService {
config := conf.Get()
@@ -65,6 +73,18 @@ func getImportNotificationTemplate(data ImportNotificationTplData) (*bytes.Buffe
return &rendered, nil
}
func getReportTemplate(data ReportTplData) (*bytes.Buffer, error) {
tpl, err := loadTemplate(tplNameReport)
if err != nil {
return nil, err
}
var rendered bytes.Buffer
if err := tpl.Execute(&rendered, data); err != nil {
return nil, err
}
return &rendered, nil
}
func loadTemplate(tplName string) (*template.Template, error) {
tplFile, err := views.TemplateFiles.Open(fmt.Sprintf("mail/%s.tpl.html", tplName))
if err != nil {
@@ -77,5 +97,8 @@ func loadTemplate(tplName string) (*template.Template, error) {
return nil, err
}
return template.New(tplName).Parse(string(tplData))
return template.
New(tplName).
Funcs(routes.DefaultTemplateFuncs()).
Parse(string(tplData))
}

View File

@@ -56,6 +56,14 @@ func (s *MailWhaleMailService) SendImportNotification(recipient *models.User, du
return s.send(recipient.Email, subjectImportNotification, template.String(), true)
}
func (s *MailWhaleMailService) SendReport(recipient *models.User, report *models.Report) error {
template, err := getReportTemplate(ReportTplData{report})
if err != nil {
return err
}
return s.send(recipient.Email, subjectReport, template.String(), true)
}
func (s *MailWhaleMailService) send(to, subject, body string, isHtml bool) error {
if to == "" {
return errors.New("not sending mail as recipient mail address seems to be invalid")

View File

@@ -8,12 +8,19 @@ import (
type NoopMailService struct{}
const notImplemented = "noop mail service doing nothing instead of sending password reset mail to %s"
func (n *NoopMailService) SendReport(recipient *models.User, report *models.Report) error {
logbuch.Info(notImplemented, recipient.ID)
return nil
}
func (n *NoopMailService) SendPasswordReset(recipient *models.User, resetLink string) error {
logbuch.Info("noop mail service doing nothing instead of sending password reset mail to %s", recipient.ID)
logbuch.Info(notImplemented, recipient.ID)
return nil
}
func (n *NoopMailService) SendImportNotification(recipient *models.User, duration time.Duration, numHeartbeats int) error {
logbuch.Info("noop mail service doing nothing instead of sending import notification mail to %s", recipient.ID)
logbuch.Info(notImplemented, recipient.ID)
return nil
}

View File

@@ -17,6 +17,10 @@ type SMTPMailService struct {
auth sasl.Client
}
func (s *SMTPMailService) SendReport(recipient *models.User, report *models.Report) error {
panic("implement me") // TODO
}
func NewSMTPMailService(config conf.SMTPMailConfig, publicUrl string) *SMTPMailService {
return &SMTPMailService{
publicUrl: publicUrl,

96
services/report.go Normal file
View File

@@ -0,0 +1,96 @@
package services
import (
"github.com/emvi/logbuch"
"github.com/go-co-op/gocron"
"github.com/muety/wakapi/config"
"github.com/muety/wakapi/models"
"sync"
"time"
)
var reportLock = sync.Mutex{}
type ReportService struct {
config *config.Config
summaryService ISummaryService
userService IUserService
mailService IMailService
schedulersWeekly map[string]*gocron.Scheduler // user id -> scheduler
}
func NewReportService(summaryService ISummaryService, userService IUserService, mailService IMailService) *ReportService {
return &ReportService{
config: config.Get(),
summaryService: summaryService,
userService: userService,
mailService: mailService,
schedulersWeekly: map[string]*gocron.Scheduler{},
}
}
func (srv *ReportService) Schedule() {
logbuch.Info("initializing report service")
users, err := srv.userService.GetAllByReports(true)
if err != nil {
config.Log().Fatal("%v", err)
}
logbuch.Info("scheduling reports for %d users", len(users))
for _, u := range users {
srv.UpdateUserSchedule(u)
}
}
func (srv *ReportService) UpdateUserSchedule(u *models.User) {
reportLock.Lock()
defer reportLock.Unlock()
// unschedule
if s, ok := srv.schedulersWeekly[u.ID]; ok && !u.ReportsWeekly {
s.Stop()
s.Clear()
delete(srv.schedulersWeekly, u.ID)
return
}
// schedule
if _, ok := srv.schedulersWeekly[u.ID]; !ok && u.ReportsWeekly {
s := gocron.NewScheduler(u.TZ())
s.
Every(1).
Week().
Weekday(srv.config.App.GetWeeklyReportDay()).
At(srv.config.App.GetWeeklyReportTime()).
Do(srv.Run, u, 7*24*time.Hour)
s.StartAsync()
srv.schedulersWeekly[u.ID] = s
}
}
func (srv *ReportService) Run(user *models.User, duration time.Duration) error {
end := time.Now().In(user.TZ())
start := time.Now().Add(-1 * duration)
summary, err := srv.summaryService.Aliased(start, end, user, srv.summaryService.Retrieve, false)
if err != nil {
config.Log().Error("failed to generate report for '%s' %v", user.ID, err)
return err
}
report := &models.Report{
From: start,
To: end,
User: user,
Summary: summary,
}
if err := srv.mailService.SendReport(user, report); err != nil {
config.Log().Error("failed to send report for '%s' %v", user.ID, err)
return err
}
logbuch.Info("sent report to user '%s'", user.ID)
return nil
}

View File

@@ -53,6 +53,12 @@ type ILanguageMappingService interface {
Delete(mapping *models.LanguageMapping) error
}
type IMailService interface {
SendPasswordReset(*models.User, string) error
SendImportNotification(*models.User, time.Duration, int) error
SendReport(*models.User, *models.Report) error
}
type ISummaryService interface {
Aliased(time.Time, time.Time, *models.User, SummaryRetriever, bool) (*models.Summary, error)
Retrieve(time.Time, time.Time, *models.User) (*models.Summary, error)
@@ -62,12 +68,19 @@ type ISummaryService interface {
Insert(*models.Summary) error
}
type IReportService interface {
Schedule()
UpdateUserSchedule(user *models.User)
Run(*models.User, time.Duration) error
}
type IUserService interface {
GetUserById(string) (*models.User, error)
GetUserByKey(string) (*models.User, error)
GetUserByEmail(string) (*models.User, error)
GetUserByResetToken(string) (*models.User, error)
GetAll() ([]*models.User, error)
GetAllByReports(bool) ([]*models.User, error)
GetActive() ([]*models.User, error)
Count() (int64, error)
CreateOrGet(*models.Signup, bool) (*models.User, bool, error)
@@ -79,8 +92,3 @@ type IUserService interface {
GenerateResetToken(*models.User) (*models.User, error)
FlushCache()
}
type IMailService interface {
SendPasswordReset(*models.User, string) error
SendImportNotification(*models.User, time.Duration, int) error
}

View File

@@ -64,6 +64,10 @@ func (srv *UserService) GetAll() ([]*models.User, error) {
return srv.repository.GetAll()
}
func (srv *UserService) GetAllByReports(reportsEnabled bool) ([]*models.User, error) {
return srv.repository.GetAllByReports(reportsEnabled)
}
func (srv *UserService) GetActive() ([]*models.User, error) {
minDate := time.Now().Add(-24 * time.Hour * time.Duration(srv.Config.App.InactiveDays))
return srv.repository.GetByLastActiveAfter(minDate)