Badges and states added
This commit is contained in:
@@ -1,16 +1,35 @@
|
||||
package SuMoC.backend.user.stats;
|
||||
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
import SuMoC.backend.gamification.badges.BadgeService;
|
||||
import SuMoC.backend.user.dtos.StatScope;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@Service
|
||||
public class StatsService {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
private final BadgeService badgeService;
|
||||
private final CurrentUserService currentUserService;
|
||||
|
||||
public StatsService(CurrentUserService currentUserService,
|
||||
UserRepository userRepository,
|
||||
BadgeService badgeService) {
|
||||
this.currentUserService = currentUserService;
|
||||
this.userRepository = userRepository;
|
||||
this.badgeService = badgeService;
|
||||
}
|
||||
|
||||
@Scheduled(cron = "0 0 0 ? * MON")
|
||||
public void resetWeeklyStats() {
|
||||
@@ -29,4 +48,45 @@ public class StatsService {
|
||||
|
||||
System.out.println("###### Monthly stats have been reset. ######");
|
||||
}
|
||||
|
||||
private static final Set<String> ALLOWED_STATS = Set.of(
|
||||
"XP",
|
||||
"CO2_SAVED",
|
||||
"KM_CYCLED",
|
||||
"KM_WALKED",
|
||||
"KM_PUBLIC_TRANSPORT",
|
||||
"KM_DRIVEN"
|
||||
);
|
||||
|
||||
@Transactional
|
||||
public void addStatsToCurrentUser(String statField, long value, StatScope scope, boolean awardBadges) {
|
||||
if (!ALLOWED_STATS.contains(statField)) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
"Unknown stat field: " + statField + " (allowed: " + ALLOWED_STATS + ")"
|
||||
);
|
||||
}
|
||||
|
||||
User user = currentUserService.get();
|
||||
|
||||
|
||||
if (user.getStats() == null) {
|
||||
user.setStats(new StatsList(user));
|
||||
}
|
||||
|
||||
StatScope effectiveScope = (scope == null) ? StatScope.ALL : scope;
|
||||
|
||||
switch (effectiveScope) {
|
||||
case ALL -> user.getStats().addToAllStats(statField, value);
|
||||
case TOTAL -> user.getStats().addToStat(Timeframe.TOTAL, statField, value);
|
||||
case MONTHLY -> user.getStats().addToStat(Timeframe.MONTHLY, statField, value);
|
||||
case WEEKLY -> user.getStats().addToStat(Timeframe.WEEKLY, statField, value);
|
||||
}
|
||||
|
||||
userRepository.save(user);
|
||||
|
||||
if (awardBadges) {
|
||||
badgeService.checkAndAwardBadges();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user