Passport/pkg/internal/services/preferences.go

80 lines
2.2 KiB
Go
Raw Normal View History

2024-09-17 06:50:05 +00:00
package services
import (
"errors"
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"github.com/samber/lo"
"gorm.io/datatypes"
"gorm.io/gorm"
)
func GetNotificationPreference(account models.Account) (models.PreferenceNotification, error) {
var notification models.PreferenceNotification
if err := database.C.Where("account_id = ?", account.ID).First(&notification).Error; err != nil {
return notification, err
}
return notification, nil
}
func UpdateNotificationPreference(account models.Account, config map[string]bool) (models.PreferenceNotification, error) {
var notification models.PreferenceNotification
var err error
if notification, err = GetNotificationPreference(account); err != nil {
notification = models.PreferenceNotification{
AccountID: account.ID,
Config: datatypes.JSONMap(
lo.MapValues(config, func(v bool, k string) any { return v }),
),
}
} else {
notification.Config = datatypes.JSONMap(
lo.MapValues(config, func(v bool, k string) any { return v }),
)
2024-09-17 06:50:05 +00:00
}
err = database.C.Save(&notification).Error
return notification, err
}
func CheckNotificationNotifiable(account models.Account, topic string) bool {
var notification models.PreferenceNotification
if err := database.C.Where("account_id = ?", account.ID).First(&notification).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return true
}
return false
}
if val, ok := notification.Config[topic]; ok {
if status, ok := val.(bool); ok {
return status
2024-09-17 06:50:05 +00:00
}
}
return true
}
func CheckNotificationNotifiableBatch(accounts []models.Account, topic string) []bool {
var notifications []models.PreferenceNotification
if err := database.C.Where("account_id IN ?", lo.Map(accounts, func(item models.Account, index int) uint {
return item.ID
})).Find(&notifications).Error; err != nil {
2024-09-17 06:50:05 +00:00
return lo.Map(accounts, func(item models.Account, index int) bool {
return false
})
}
2024-09-21 14:54:54 +00:00
var notifiable = make([]bool, len(accounts))
for idx, notification := range notifications {
2024-09-17 06:50:05 +00:00
if val, ok := notification.Config[topic]; ok {
if status, ok := val.(bool); ok {
2024-09-21 14:54:54 +00:00
notifiable[idx] = status
2024-09-17 06:50:05 +00:00
continue
}
}
2024-09-21 14:54:54 +00:00
notifiable[idx] = true
2024-09-17 06:50:05 +00:00
}
return notifiable
}