stuve-it-backend/eventEntriesNotifier/main.go

88 lines
2.4 KiB
Go

package eventEntriesNotifier
import (
"git.stuve.uni-ulm.de/stuve-it/stuve-it-backend/logger"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/mailer"
"github.com/pocketbase/pocketbase/tools/template"
"net/mail"
)
// sendEmailNotification sends an email notification to the user
func sendEmailNotification(app *pocketbase.PocketBase, recordId string, STATUS string) error {
registry := template.NewRegistry()
record, err := app.Dao().FindRecordById("eventListSlotEntriesWithUser", recordId)
if err != nil {
return err
}
user, err := app.Dao().FindRecordById("users", record.GetString("user"))
if err != nil {
return err
}
// render email template
html, err := registry.LoadFiles(
"html/eventEntryNotification.html",
).Render(map[string]any{
"STATUS": STATUS,
"EVENT_NAME": record.GetString("eventName"),
"APP_URL": app.Settings().Meta.AppUrl,
})
if err != nil {
return err
}
// send email
email := &mailer.Message{
From: mail.Address{
Address: app.Settings().Meta.SenderAddress,
Name: app.Settings().Meta.SenderName,
},
To: []mail.Address{{Address: user.GetString("email")}},
Subject: "[StuVe IT] Info zu einer Event Anmeldung",
HTML: html,
}
if err := app.NewMailClient().Send(email); err != nil {
return err
}
return nil
}
// InitEventEntriesNotifier initializes the eventEntriesNotifier email notifier
func InitEventEntriesNotifier(app *pocketbase.PocketBase, e *core.ServeEvent) error {
logger.LogInfoF("Adding eventEntriesNotifier email notifier")
app.OnModelAfterCreate("eventListSlotEntries").Add(func(e *core.ModelEvent) error {
// send email notification
err := sendEmailNotification(app, e.Model.GetId(), "created")
if err != nil {
logger.LogErrorF("Error sending eventEntry email notification: %v", err)
}
return nil
})
app.OnModelAfterUpdate("eventListSlotEntries").Add(func(e *core.ModelEvent) error {
// send email notification
err := sendEmailNotification(app, e.Model.GetId(), "updated")
if err != nil {
logger.LogErrorF("Error sending eventEntry email notification: %v", err)
}
return nil
})
app.OnModelAfterDelete("eventListSlotEntries").Add(func(e *core.ModelEvent) error {
// send email notification
err := sendEmailNotification(app, e.Model.GetId(), "deleted")
if err != nil {
logger.LogErrorF("Error sending eventEntry email notification: %v", err)
}
return nil
})
return nil
}