diff --git a/repositories/leaderboard.go b/repositories/leaderboard.go index d39c700..9922218 100644 --- a/repositories/leaderboard.go +++ b/repositories/leaderboard.go @@ -61,6 +61,15 @@ func (r *LeaderboardRepository) GetAggregatedByUserAndInterval(userId string, ke return items, nil } +func (r *LeaderboardRepository) DeleteByUser(userId string) error { + if err := r.db. + Where("user_id = ?", userId). + Delete(models.LeaderboardItem{}).Error; err != nil { + return err + } + return nil +} + func (r *LeaderboardRepository) DeleteByUserAndInterval(userId string, key *models.IntervalKey) error { if err := r.db. Where("user_id = ?", userId). diff --git a/repositories/repositories.go b/repositories/repositories.go index 24da1e4..a78639e 100644 --- a/repositories/repositories.go +++ b/repositories/repositories.go @@ -90,6 +90,7 @@ type IUserRepository interface { type ILeaderboardRepository interface { InsertBatch([]*models.LeaderboardItem) error CountAllByUser(string) (int64, error) + DeleteByUser(string) error DeleteByUserAndInterval(string, *models.IntervalKey) error GetAllAggregatedByInterval(*models.IntervalKey, *uint8) ([]*models.LeaderboardItem, error) GetAggregatedByUserAndInterval(string, *models.IntervalKey, *uint8) ([]*models.LeaderboardItem, error) diff --git a/services/leaderboard.go b/services/leaderboard.go index 1eaebf2..b47c01b 100644 --- a/services/leaderboard.go +++ b/services/leaderboard.go @@ -39,17 +39,22 @@ func NewLeaderboardService(leaderboardRepo repositories.ILeaderboardRepository, // generate leaderboard for updated user, if leaderboard enabled and none present, yet user := m.Fields[config.FieldPayload].(*models.User) - if user.PublicLeaderboard { - exists, err := srv.ExistsAnyByUser(user.ID) - if err != nil { - config.Log().Error("failed to check existing leaderboards upon user update - %v", err) - } - if !exists { - logbuch.Info("generating leaderboard for '%s' after settings update", user.ID) - srv.Run([]*models.User{user}, models.IntervalPast7Days, []uint8{models.SummaryLanguage}) - } + + exists, err := srv.ExistsAnyByUser(user.ID) + if err != nil { + config.Log().Error("failed to check existing leaderboards upon user update - %v", err) } + if user.PublicLeaderboard && !exists { + logbuch.Info("generating leaderboard for '%s' after settings update", user.ID) + srv.Run([]*models.User{user}, models.IntervalPast7Days, []uint8{models.SummaryLanguage}) + } else if !user.PublicLeaderboard && exists { + logbuch.Info("clearing leaderboard for '%s' after settings update", user.ID) + if err := srv.repository.DeleteByUser(user.ID); err != nil { + config.Log().Error("failed to clear leaderboard for user '%s' - %v", user.ID, err) + } + srv.cache.Flush() + } } }(&onUserUpdate)