78 lines
2.6 KiB
Go
78 lines
2.6 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/gochat/gochat/internal/model"
|
|
)
|
|
|
|
// NotificationPreferenceRepo implements GORM repository for NotificationPreference.
|
|
// Reference: Chatwoot app/models/notification_preference.rb
|
|
type NotificationPreferenceRepo struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewNotificationPreferenceRepo creates a new NotificationPreference repository.
|
|
func NewNotificationPreferenceRepo(db *gorm.DB) *NotificationPreferenceRepo {
|
|
return &NotificationPreferenceRepo{db: db}
|
|
}
|
|
|
|
// FindByID retrieves a notification preference by primary key.
|
|
func (r *NotificationPreferenceRepo) FindByID(ctx context.Context, id uint) (*model.NotificationPreference, error) {
|
|
var pref model.NotificationPreference
|
|
err := r.db.WithContext(ctx).First(&pref, id).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &pref, nil
|
|
}
|
|
|
|
// ListByUserAndAccount retrieves all notification preferences for a user within an account.
|
|
func (r *NotificationPreferenceRepo) ListByUserAndAccount(ctx context.Context, userID uint, accountID uint) ([]model.NotificationPreference, error) {
|
|
var prefs []model.NotificationPreference
|
|
err := r.db.WithContext(ctx).
|
|
Where("user_id = ? AND account_id = ?", userID, accountID).
|
|
Find(&prefs).Error
|
|
return prefs, err
|
|
}
|
|
|
|
// Upsert creates or updates a notification preference (unique constraint on user+account+channel+event).
|
|
func (r *NotificationPreferenceRepo) Upsert(ctx context.Context, pref *model.NotificationPreference) error {
|
|
result := r.db.WithContext(ctx).
|
|
Where("user_id = ? AND account_id = ? AND channel = ? AND event_type = ?",
|
|
pref.UserID, pref.AccountID, pref.Channel, pref.EventType).
|
|
Assign(map[string]interface{}{
|
|
"enabled": pref.Enabled,
|
|
"preferences": pref.Preferences,
|
|
}).
|
|
FirstOrCreate(pref)
|
|
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
|
|
if result.RowsAffected == 0 {
|
|
// Record already existed, update it
|
|
return r.db.WithContext(ctx).Save(pref).Error
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// BatchUpsert creates or updates multiple notification preferences at once.
|
|
func (r *NotificationPreferenceRepo) BatchUpsert(ctx context.Context, prefs []model.NotificationPreference) error {
|
|
for i := range prefs {
|
|
if err := r.Upsert(ctx, &prefs[i]); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DeleteByUserAndAccount removes all notification preferences for a user within an account.
|
|
func (r *NotificationPreferenceRepo) DeleteByUserAndAccount(ctx context.Context, userID uint, accountID uint) error {
|
|
return r.db.WithContext(ctx).
|
|
Where("user_id = ? AND account_id = ?", userID, accountID).
|
|
Delete(&model.NotificationPreference{}).Error
|
|
} |