Merge branch 'main' into route_alternatives
# Conflicts: # src/main/java/SuMoC/backend/security/SecurityConfiguration.java # src/main/java/SuMoC/backend/user/models/User.java # src/main/resources/application.properties
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
package SuMoC.backend.gamification;
|
||||
|
||||
public enum Timeframe {
|
||||
TOTAL("totalStats"),
|
||||
MONTHLY("monthlyStats"),
|
||||
WEEKLY("weeklyStats");
|
||||
|
||||
private final String statsField;
|
||||
|
||||
Timeframe(String statsField) {
|
||||
this.statsField = statsField;
|
||||
}
|
||||
|
||||
public String getStatsField() {
|
||||
return statsField;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
|
||||
import SuMoC.backend.gamification.badges.models.Badge;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import jakarta.annotation.security.RolesAllowed;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/badges")
|
||||
public class BadgeController {
|
||||
private BadgeService badgeService;
|
||||
|
||||
@Autowired
|
||||
public BadgeController(BadgeService badgeService) {
|
||||
this.badgeService = badgeService;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Operation(summary = "Create a new badge")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "201", description = "Badge created successfully"),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid input data"),
|
||||
@ApiResponse(responseCode = "409", description = "Badge already exists")
|
||||
})
|
||||
@PostMapping("/createBadge")
|
||||
public ResponseEntity<Badge> createBadge(@RequestBody @Valid Badge badge) {
|
||||
Badge createdBadge = badgeService.createBadge(badge);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(createdBadge);
|
||||
}
|
||||
|
||||
|
||||
@Operation(summary = "Delete a badge by ID")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Badge deleted successfully"),
|
||||
@ApiResponse(responseCode = "404", description = "Badge not found")
|
||||
})
|
||||
@DeleteMapping("/deleteBadge/{badgeId}")
|
||||
public ResponseEntity<Void> deleteBadgeById(@PathVariable Long badgeId) {
|
||||
badgeService.deleteBadge(badgeId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Operation(summary = "Modify a badge by ID")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Badge modified successfully"),
|
||||
@ApiResponse(responseCode = "404", description = "Badge not found"),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid input data")
|
||||
})
|
||||
@PutMapping("/modifyBadge")
|
||||
public ResponseEntity<Badge> modifyBadgeById(
|
||||
@RequestBody @Valid Badge badge) {
|
||||
Badge modifiedBadge = badgeService.modifyBadge(badge);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(modifiedBadge);
|
||||
}
|
||||
|
||||
|
||||
@Operation(summary = "Get a badge by ID")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Badge retrieved successfully"),
|
||||
@ApiResponse(responseCode = "404", description = "Badge not found")
|
||||
})
|
||||
@GetMapping("/getBadge/{badgeId}")
|
||||
public ResponseEntity<Badge> getBadgeById(@PathVariable Long badgeId) {
|
||||
Badge badge = badgeService.getBadgeById(badgeId);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(badge);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Operation(summary = "Get all badges")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Badges retrieved successfully"),
|
||||
@ApiResponse(responseCode = "404", description = "No badges found")
|
||||
})
|
||||
@GetMapping("/getAllBadges")
|
||||
public ResponseEntity<List<Badge>> getAllBadges(){
|
||||
List<Badge> badges = badgeService.getAllBadges();
|
||||
return ResponseEntity.status(HttpStatus.OK).body(badges);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
|
||||
import SuMoC.backend.gamification.badges.models.Badge;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface BadgeRepository extends JpaRepository<Badge, Long> {
|
||||
Optional<Badge> findByName(String name);
|
||||
|
||||
List<Badge> getBadgeById(Long id);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
import SuMoC.backend.gamification.badges.models.Badge;
|
||||
import SuMoC.backend.gamification.badges.models.UserBadge;
|
||||
import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import SuMoC.backend.user.service.PrivacyService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
public class BadgeService {
|
||||
|
||||
private final CurrentUserService currentUser;
|
||||
|
||||
private final BadgeRepository badgeRepository;
|
||||
|
||||
private final UserBadgeRepository userBadgeRepository;
|
||||
private final PrivacyService privacyService;
|
||||
|
||||
public BadgeService(CurrentUserService currentUser, BadgeRepository badgeRepository, UserBadgeRepository userBadgeRepository, PrivacyService privacyService) {
|
||||
this.currentUser = currentUser;
|
||||
this.badgeRepository = badgeRepository;
|
||||
this.userBadgeRepository = userBadgeRepository;
|
||||
this.privacyService = privacyService;
|
||||
}
|
||||
|
||||
public Badge createBadge(Badge badge) {
|
||||
badgeRepository.findByName(badge.getName())
|
||||
.ifPresent(b -> {
|
||||
throw new ResponseStatusException(HttpStatus.CONFLICT, "Badge existiert bereits");
|
||||
});
|
||||
return badgeRepository.save(badge);
|
||||
}
|
||||
|
||||
|
||||
public void checkAndAwardBadges(User user) {
|
||||
List<Badge> badges = badgeRepository.findAll();
|
||||
|
||||
for (Badge badge : badges) {
|
||||
// Prüfe, ob Nutzer schon den Badge hat
|
||||
boolean alreadyHas = user.getBadges().stream()
|
||||
.anyMatch(ub -> ub.getBadge().equals(badge));
|
||||
if (alreadyHas) continue;
|
||||
|
||||
// Nur prüfen, wenn es überhaupt Kriterien gibt
|
||||
Map<String, Integer> criteria = badge.getCriteria();
|
||||
boolean qualifies = criteria != null && !criteria.isEmpty() &&
|
||||
criteria.entrySet().stream()
|
||||
.allMatch(entry ->
|
||||
user.getStats().getStatValue(Timeframe.TOTAL, entry.getKey()) >= entry.getValue()
|
||||
);
|
||||
|
||||
if (qualifies) {
|
||||
UserBadge userBadge = new UserBadge();
|
||||
userBadge.setUser(user);
|
||||
userBadge.setBadge(badge);
|
||||
userBadge.setAwardedAt(LocalDateTime.now());
|
||||
userBadgeRepository.save(userBadge);
|
||||
user.getBadges().add(userBadge);
|
||||
|
||||
// TODO: Remove in production
|
||||
System.out.println("Badge " + badge.getName() + " vergeben an " + user.getPrivateName() + ". Mit Condition: " + badge.getCriteria().toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Badge modifyBadge(Badge modifiedBadge) {
|
||||
Badge badge = badgeRepository.findById(modifiedBadge.getId())
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Badge nicht gefunden"));
|
||||
|
||||
badge.setName(modifiedBadge.getName());
|
||||
badge.setDescription(modifiedBadge.getDescription());
|
||||
badge.setCriteria(modifiedBadge.getCriteria());
|
||||
|
||||
return badgeRepository.save(badge);
|
||||
}
|
||||
|
||||
public void deleteBadge(Long id) {
|
||||
Badge badge = badgeRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Badge nicht gefunden"));
|
||||
badgeRepository.delete(badge);
|
||||
}
|
||||
|
||||
public Badge getBadgeById(Long badgeId) {
|
||||
return badgeRepository.findById(badgeId)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Badge nicht gefunden"));
|
||||
}
|
||||
|
||||
|
||||
public List<Badge> getAllBadges() {
|
||||
return badgeRepository.findAll();
|
||||
}
|
||||
|
||||
public List<UserBadgeDTO> getUserBadges(Long id) {
|
||||
User sender = currentUser.get();
|
||||
List<UserBadge> badges = new ArrayList<>();
|
||||
if(Objects.equals(id, sender.getId())) {
|
||||
badges = userBadgeRepository.findByUserId(sender.getId());
|
||||
} else {
|
||||
if(privacyService.checkVisibility(sender, id)) {
|
||||
badges = userBadgeRepository.findByUserId(id);
|
||||
}
|
||||
}
|
||||
|
||||
return badges.stream()
|
||||
.map(UserBadgeMapper::toDTO)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
|
||||
import SuMoC.backend.gamification.badges.models.Badge;
|
||||
import SuMoC.backend.gamification.badges.models.UserBadge;
|
||||
import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public class UserBadgeMapper {
|
||||
|
||||
public static UserBadgeDTO toDTO(UserBadge userBadge) {
|
||||
UserBadgeDTO dto = new UserBadgeDTO();
|
||||
|
||||
Badge badge = userBadge.getBadge();
|
||||
|
||||
dto.setBadgeId(badge.getId());
|
||||
dto.setName(badge.getName());
|
||||
dto.setDescription(badge.getDescription());
|
||||
dto.setCriteria(badge.getCriteria());
|
||||
dto.setAwardedAt(userBadge.getAwardedAt());
|
||||
|
||||
return dto;
|
||||
}
|
||||
|
||||
public static List<UserBadgeDTO> toDTO(List<UserBadge> userBadges) {
|
||||
List<UserBadgeDTO> dtos = new ArrayList<>();
|
||||
for(UserBadge badge : userBadges ) {
|
||||
dtos.add(UserBadgeMapper.toDTO(badge));
|
||||
}
|
||||
return dtos;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
|
||||
import SuMoC.backend.gamification.badges.models.UserBadge;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface UserBadgeRepository extends JpaRepository<UserBadge, Long> {
|
||||
List<UserBadge> findByUserId(Long userId);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package SuMoC.backend.gamification.badges.models;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Entity
|
||||
public class Badge {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
private String description;
|
||||
|
||||
@ElementCollection
|
||||
@CollectionTable(name = "badge_criteria", joinColumns = @JoinColumn(name = "badge_id"))
|
||||
@MapKeyColumn(name = "criteria_name")
|
||||
@Column(name = "criteria_value")
|
||||
private Map<String, Integer> criteria = new HashMap<>();
|
||||
|
||||
// Constructor
|
||||
|
||||
/**
|
||||
* Badge without criteria - if the Badge shouldn't be reachable by now
|
||||
* @param name name of the badge
|
||||
* @param description a short description
|
||||
*/
|
||||
public Badge(String name, String description) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
/**
|
||||
* Badge with criteria
|
||||
* @param name name of the badge
|
||||
* @param description a short description
|
||||
* @param criteria criteria Mapping StatField-Long
|
||||
*/
|
||||
public Badge(String name, String description, Map<String, Integer> criteria) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.criteria = criteria;
|
||||
}
|
||||
|
||||
public Badge() {}
|
||||
|
||||
// Getter & Setter
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
|
||||
public Map<String, Integer> getCriteria() { return criteria; }
|
||||
public void setCriteria(Map<String, Integer> criteria) { this.criteria = criteria; }
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package SuMoC.backend.gamification.badges.models;
|
||||
|
||||
import SuMoC.backend.user.models.User;
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
public class UserBadge {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
// TODO: Discuss if this Duplex Joint really makes sense
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private User user;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "badge_id", nullable = false)
|
||||
private Badge badge;
|
||||
|
||||
private LocalDateTime awardedAt;
|
||||
|
||||
|
||||
// Getter & Setter
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
|
||||
public User getUser() { return user; }
|
||||
public void setUser(User user) { this.user = user; }
|
||||
|
||||
public Badge getBadge() { return badge; }
|
||||
public void setBadge(Badge badge) { this.badge = badge; }
|
||||
|
||||
public LocalDateTime getAwardedAt() { return awardedAt; }
|
||||
public void setAwardedAt(LocalDateTime awardedAt) { this.awardedAt = awardedAt; }
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package SuMoC.backend.gamification.badges.models;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
public class UserBadgeDTO {
|
||||
|
||||
private Long badgeId;
|
||||
private String name;
|
||||
private String description;
|
||||
private Map<String, Integer> criteria;
|
||||
private LocalDateTime awardedAt;
|
||||
|
||||
// Getter & Setter
|
||||
|
||||
|
||||
public Long getBadgeId() {
|
||||
return badgeId;
|
||||
}
|
||||
|
||||
public void setBadgeId(Long badgeId) {
|
||||
this.badgeId = badgeId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getCriteria() {
|
||||
return criteria;
|
||||
}
|
||||
|
||||
public void setCriteria(Map<String, Integer> criteria) {
|
||||
this.criteria = criteria;
|
||||
}
|
||||
|
||||
public LocalDateTime getAwardedAt() {
|
||||
return awardedAt;
|
||||
}
|
||||
|
||||
public void setAwardedAt(LocalDateTime awardedAt) {
|
||||
this.awardedAt = awardedAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package SuMoC.backend.gamification.scoretable;
|
||||
|
||||
import SuMoC.backend.gamification.scoretable.models.Leaderboard;
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/leaderboard")
|
||||
class LeaderboardController {
|
||||
private LeaderboardService leaderboardService;
|
||||
|
||||
@Autowired
|
||||
public LeaderboardController(LeaderboardService leaderboardService) {
|
||||
this.leaderboardService = leaderboardService;
|
||||
}
|
||||
|
||||
@Operation(summary = "Get the global score table")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Successfully retrieved global score table"),
|
||||
@ApiResponse(responseCode = "400", description = "Bad request")
|
||||
|
||||
})
|
||||
@GetMapping("/getLeaderboard")
|
||||
public ResponseEntity<Leaderboard> getLeaderboard(@AuthenticationPrincipal User user,
|
||||
@RequestParam Timeframe timeframe,
|
||||
@RequestParam String field) {
|
||||
Leaderboard leaderboard = this.leaderboardService.getLeaderboard(user, timeframe, field);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(leaderboard);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get the friend score table")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Successfully retrieved friend score table"),
|
||||
@ApiResponse(responseCode = "400", description = "Bad request")
|
||||
})
|
||||
@GetMapping("/getFriendLeaderboard")
|
||||
public ResponseEntity<Leaderboard> getFriendLeaderboard(@AuthenticationPrincipal User user,
|
||||
@RequestParam Timeframe timeframe,
|
||||
@RequestParam String field) {
|
||||
Leaderboard leaderboard = this.leaderboardService.getFriendLeaderboard(user, timeframe, field);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(leaderboard);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package SuMoC.backend.gamification.scoretable;
|
||||
|
||||
import SuMoC.backend.gamification.scoretable.models.Leaderboard;
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
import SuMoC.backend.gamification.scoretable.models.LeaderboardEntry;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.service.FriendshipService;
|
||||
import SuMoC.backend.user.stats.*;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class LeaderboardService {
|
||||
private final FriendshipService friendshipService;
|
||||
private final StatsListRepository statsListRepository;
|
||||
|
||||
public LeaderboardService(
|
||||
FriendshipService friendshipService,
|
||||
StatsListRepository statsListRepository
|
||||
) {
|
||||
|
||||
this.friendshipService = friendshipService;
|
||||
this.statsListRepository = statsListRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method Overload to get the score table with a default limit of 30.
|
||||
* @param user
|
||||
* @param timeframe
|
||||
* @param field
|
||||
* @return
|
||||
*/
|
||||
public Leaderboard getLeaderboard(User user, Timeframe timeframe, String field) {
|
||||
return getLeaderboard(user, timeframe, field, 30);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the global score table for a given user, timeframe, score type, and limit.
|
||||
* @param user
|
||||
* @param timeframe
|
||||
* @param field
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
public Leaderboard getLeaderboard(User user, Timeframe timeframe, String field, int limit) {
|
||||
List<StatsList> topStats = getTopStats(timeframe, field, limit);
|
||||
|
||||
List<Long> topUserIds = topStats.stream()
|
||||
.map(stats -> stats.getUser().getId())
|
||||
.toList();
|
||||
|
||||
Map<Long, FriendshipService.NameWithFriendship> nameMap =
|
||||
friendshipService.getPrivateNameIfFriendshipAccepted(user, topUserIds)
|
||||
.stream()
|
||||
.collect(Collectors.toMap(FriendshipService.NameWithFriendship::id, n -> n));
|
||||
|
||||
Leaderboard leaderboard = new Leaderboard();
|
||||
leaderboard.setEntries(new ArrayList<>());
|
||||
|
||||
for (StatsList statsList : topStats) {
|
||||
User topUser = statsList.getUser();
|
||||
FriendshipService.NameWithFriendship nwf = nameMap.get(topUser.getId());
|
||||
|
||||
String displayName = (nwf != null) ? nwf.name() : topUser.getPublicName();
|
||||
boolean friendship = (nwf != null) && nwf.friendship();
|
||||
|
||||
LeaderboardEntry entry = new LeaderboardEntry(
|
||||
topUser.getId(),
|
||||
displayName,
|
||||
friendship,
|
||||
statsList.getStatValue(timeframe, field)
|
||||
);
|
||||
|
||||
leaderboard.getEntries().add(entry);
|
||||
}
|
||||
|
||||
if (leaderboard.getEntries().stream().noneMatch(e -> e.getUserId().equals(user.getId()))) {
|
||||
LeaderboardEntry userEntry = new LeaderboardEntry(
|
||||
user.getId(),
|
||||
user.getPrivateName(),
|
||||
true,
|
||||
user.getStats().getStatValue(timeframe, field)
|
||||
);
|
||||
leaderboard.getEntries().add(userEntry);
|
||||
}
|
||||
|
||||
leaderboard.getEntries().sort(
|
||||
Comparator.comparingLong(LeaderboardEntry::getScore).reversed()
|
||||
);
|
||||
|
||||
return leaderboard;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Method Overload to get the friend score table with a default limit of 30.
|
||||
* @param user
|
||||
* @param timeframe
|
||||
* @param field
|
||||
* @return
|
||||
*/
|
||||
public Leaderboard getFriendLeaderboard(User user, Timeframe timeframe, String field) {
|
||||
return getFriendLeaderboard(user, timeframe, field, 30);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the friend score table for a given user, timeframe, score type, and limit.
|
||||
* @param user
|
||||
* @param timeframe
|
||||
* @param field
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
public Leaderboard getFriendLeaderboard(User user, Timeframe timeframe, String field, int limit) {
|
||||
List<User> friends = friendshipService.getAcceptedFriends(user);
|
||||
|
||||
Leaderboard leaderboard = new Leaderboard();
|
||||
leaderboard.setEntries(new ArrayList<>()); // Initialize list
|
||||
|
||||
for (User friend : friends) {
|
||||
StatsList statsList = friend.getStats();
|
||||
if (statsList != null) {
|
||||
Long statValue = statsList.getStatValue(timeframe, field);
|
||||
if (statValue != null) {
|
||||
LeaderboardEntry entry = new LeaderboardEntry(
|
||||
friend.getId(),
|
||||
friend.getPrivateName(),
|
||||
true,
|
||||
statValue
|
||||
);
|
||||
leaderboard.getEntries().add(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (leaderboard.getEntries().stream().noneMatch(e -> e.getUserId().equals(user.getId()))) {
|
||||
leaderboard.getEntries().add(new LeaderboardEntry(
|
||||
user.getId(),
|
||||
user.getPrivateName(),
|
||||
true,
|
||||
user.getStats().getStatValue(timeframe, field)
|
||||
));
|
||||
}
|
||||
|
||||
leaderboard.getEntries().sort(
|
||||
Comparator.comparingLong(LeaderboardEntry::getScore).reversed()
|
||||
);
|
||||
return leaderboard;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the top stats for a given timeframe and stat field.
|
||||
* @param timeframe
|
||||
* @param statField
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
public List<StatsList> getTopStats(
|
||||
Timeframe timeframe,
|
||||
String statField,
|
||||
int limit
|
||||
) {
|
||||
Pageable pageable = PageRequest.of(0, limit);
|
||||
|
||||
return statsListRepository
|
||||
.findAll(
|
||||
StatsListSpecifications.orderByStat(timeframe, statField),
|
||||
pageable
|
||||
)
|
||||
.getContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the rank of a specific value for a given timeframe and stat field.
|
||||
* @param timeframe
|
||||
* @param statField
|
||||
* @param value
|
||||
* @return
|
||||
*/
|
||||
public long getRank(
|
||||
Timeframe timeframe,
|
||||
String statField,
|
||||
long value
|
||||
) {
|
||||
return statsListRepository.count(
|
||||
StatsListSpecifications
|
||||
.higherThan(timeframe, statField, value)
|
||||
) + 1;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package SuMoC.backend.gamification.scoretable.models;
|
||||
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Leaderboard {
|
||||
|
||||
private Timeframe timeframe;
|
||||
|
||||
private LeaderboardType leaderboardType;
|
||||
|
||||
private List<LeaderboardEntry> entries;
|
||||
|
||||
|
||||
// Constructor
|
||||
|
||||
public Leaderboard(Timeframe timeframe, LeaderboardType leaderboardType, List<LeaderboardEntry> entries) {
|
||||
this.timeframe = timeframe;
|
||||
this.leaderboardType = leaderboardType;
|
||||
this.entries = entries;
|
||||
}
|
||||
|
||||
public Leaderboard() {}
|
||||
|
||||
|
||||
// Getter & Setter
|
||||
|
||||
public Timeframe getTimeframe() { return timeframe; }
|
||||
public void setTimeframe(Timeframe timeframe) { this.timeframe = timeframe; }
|
||||
|
||||
public LeaderboardType getScoreType() { return leaderboardType; }
|
||||
public void setScoreType(LeaderboardType leaderboardType) { this.leaderboardType = leaderboardType; }
|
||||
|
||||
public List<LeaderboardEntry> getEntries() { return entries; }
|
||||
public void setEntries(List<LeaderboardEntry> entries) { this.entries = entries; }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package SuMoC.backend.gamification.scoretable.models;
|
||||
|
||||
public class LeaderboardEntry {
|
||||
private Long userId;
|
||||
private String username;
|
||||
private Boolean isFriend;
|
||||
private Long score;
|
||||
|
||||
public LeaderboardEntry(Long userId, String username, Boolean isFriend, Long score) {
|
||||
this.userId = userId;
|
||||
this.username = username;
|
||||
this.isFriend = isFriend;
|
||||
this.score = score;
|
||||
}
|
||||
|
||||
public LeaderboardEntry() {}
|
||||
|
||||
// Getter & Setter
|
||||
public Long getUserId() { return userId; }
|
||||
public void setUserId(Long userId) { this.userId = userId; }
|
||||
|
||||
public String getUsername() { return username; }
|
||||
public void setUsername(String username) { this.username = username; }
|
||||
|
||||
public Boolean getIsFriend() { return isFriend; }
|
||||
public void setIsFriend(Boolean isFriend) { this.isFriend = isFriend; }
|
||||
|
||||
public Long getScore() { return score; }
|
||||
public void setScore(Long score) { this.score = score; }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package SuMoC.backend.gamification.scoretable.models;
|
||||
|
||||
public enum LeaderboardType {
|
||||
XP,
|
||||
CO2,
|
||||
KM
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class CartaLocationClient implements GeocodingClient {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CartaLocationClient.class);
|
||||
|
||||
private final WebClient cartaLocationClient;
|
||||
|
||||
public CartaLocationClient(WebClient cartaLocationClient) {
|
||||
this.cartaLocationClient = cartaLocationClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GeocodingResponse> reverse(double lat, double lon) {
|
||||
String query = lat + "," + lon;
|
||||
logger.debug("Calling Carta location API with query: {}, type: BUILDING, limit: 3", query);
|
||||
|
||||
return cartaLocationClient.get()
|
||||
.uri(uriBuilder -> {
|
||||
var uri = uriBuilder.path("/location/search")
|
||||
.queryParam("q", query)
|
||||
.queryParam("type", "BUILDING")
|
||||
.queryParam("limit", 3)
|
||||
.build();
|
||||
logger.debug("Full Carta location API URL: {}", uri);
|
||||
return uri;
|
||||
})
|
||||
.retrieve()
|
||||
.bodyToMono(CartaLocationResponse[].class)
|
||||
.doOnNext(responses -> logger.debug("Received {} results from Carta location API",
|
||||
responses != null ? responses.length : 0))
|
||||
.map(responses -> {
|
||||
if (responses == null || responses.length == 0) {
|
||||
logger.error("Carta location API returned empty response for coordinates: lat={}, lon={}", lat, lon);
|
||||
return new GeocodingResponse(null);
|
||||
}
|
||||
logger.debug("Using first result: {}", responses[0]);
|
||||
return mapToGeocodingResponse(responses[0]);
|
||||
})
|
||||
.onErrorResume(error -> {
|
||||
logger.error("Error calling Carta location API for coordinates: lat={}, lon={}", lat, lon, error);
|
||||
return Mono.just(new GeocodingResponse(null));
|
||||
});
|
||||
}
|
||||
|
||||
private GeocodingResponse mapToGeocodingResponse(CartaLocationResponse response) {
|
||||
Map<String, String> addressMap = new HashMap<>();
|
||||
|
||||
// Map Carta fields to Nominatim-style address format
|
||||
if (response.building() != null) {
|
||||
addressMap.put("house_number", response.building());
|
||||
}
|
||||
if (response.street() != null) {
|
||||
addressMap.put("road", response.street());
|
||||
}
|
||||
if (response.suburb() != null) {
|
||||
addressMap.put("suburb", response.suburb());
|
||||
}
|
||||
if (response.city() != null) {
|
||||
addressMap.put("city", response.city());
|
||||
}
|
||||
if (response.state() != null) {
|
||||
addressMap.put("state", response.state());
|
||||
}
|
||||
if (response.postcode() != null) {
|
||||
addressMap.put("postcode", response.postcode());
|
||||
}
|
||||
if (response.country() != null) {
|
||||
addressMap.put("country", response.country());
|
||||
}
|
||||
|
||||
return new GeocodingResponse(addressMap);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record CartaLocationResponse(
|
||||
Double longitude,
|
||||
Double latitude,
|
||||
String country,
|
||||
String state,
|
||||
String county,
|
||||
String city,
|
||||
String suburb,
|
||||
String neighborhood,
|
||||
String locality,
|
||||
String street,
|
||||
String building,
|
||||
String postcode,
|
||||
String name
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -1,26 +1,27 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import SuMoC.backend.nominatim.NominatimClient;
|
||||
import SuMoC.backend.nominatim.ReverseResponse;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Service
|
||||
public class GeoCodingService {
|
||||
|
||||
private final NominatimClient nominatimClient;
|
||||
private final GeocodingClient geocodingClient;
|
||||
|
||||
public GeoCodingService(NominatimClient nominatimClient) {
|
||||
this.nominatimClient = nominatimClient;
|
||||
public GeoCodingService(GeocodingClient geocodingClient) {
|
||||
this.geocodingClient = geocodingClient;
|
||||
}
|
||||
|
||||
public Mono<AddressDTO> getAddress(double lat, double lon) {
|
||||
return nominatimClient.reverse(lat, lon)
|
||||
return geocodingClient.reverse(lat, lon)
|
||||
.map(this::mapToAddressDTO);
|
||||
}
|
||||
|
||||
private AddressDTO mapToAddressDTO(ReverseResponse response) {
|
||||
private AddressDTO mapToAddressDTO(GeocodingResponse response) {
|
||||
var addressMap = response.address();
|
||||
if (addressMap == null) {
|
||||
return new AddressDTO(null, null, null, null, null, null, null, null, null, null);
|
||||
}
|
||||
return new AddressDTO(
|
||||
addressMap.get("house_number"),
|
||||
addressMap.get("road"),
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public interface GeocodingClient {
|
||||
Mono<GeocodingResponse> reverse(double lat, double lon);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(GeocodingProperties.class)
|
||||
public class GeocodingConfig {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(name = "geocoding.provider", havingValue = "docker", matchIfMissing = true)
|
||||
public WebClient nominatimWebClient(GeocodingProperties properties) {
|
||||
return WebClient.builder()
|
||||
.baseUrl(properties.nominatim().baseUrl())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean(name = "geocodingClient")
|
||||
@ConditionalOnProperty(name = "geocoding.provider", havingValue = "docker", matchIfMissing = true)
|
||||
public GeocodingClient nominatimClient(WebClient nominatimWebClient) {
|
||||
return new NominatimClient(nominatimWebClient);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(name = "geocoding.provider", havingValue = "carta")
|
||||
public WebClient cartaLocationWebClient(GeocodingProperties properties) {
|
||||
return WebClient.builder()
|
||||
.baseUrl(properties.carta().baseUrl())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean(name = "geocodingClient")
|
||||
@ConditionalOnProperty(name = "geocoding.provider", havingValue = "carta")
|
||||
public GeocodingClient cartaLocationClient(WebClient cartaLocationWebClient) {
|
||||
return new CartaLocationClient(cartaLocationWebClient);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "geocoding")
|
||||
public record GeocodingProperties(
|
||||
String provider,
|
||||
NominatimConfig nominatim,
|
||||
CartaConfig carta
|
||||
) {
|
||||
public record NominatimConfig(
|
||||
String baseUrl
|
||||
) {
|
||||
}
|
||||
|
||||
public record CartaConfig(
|
||||
String baseUrl
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record GeocodingResponse(
|
||||
Map<String, String> address
|
||||
) {
|
||||
}
|
||||
|
||||
+8
-8
@@ -1,20 +1,18 @@
|
||||
package SuMoC.backend.nominatim;
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Service
|
||||
public class NominatimClient {
|
||||
public class NominatimClient implements GeocodingClient {
|
||||
|
||||
private final WebClient nominatimClient;
|
||||
|
||||
public NominatimClient(@Qualifier("nominatimWebClient") WebClient nominatimClient) {
|
||||
public NominatimClient(WebClient nominatimClient) {
|
||||
this.nominatimClient = nominatimClient;
|
||||
}
|
||||
|
||||
public Mono<ReverseResponse> reverse(double lat, double lon) {
|
||||
@Override
|
||||
public Mono<GeocodingResponse> reverse(double lat, double lon) {
|
||||
return nominatimClient.get()
|
||||
.uri(uriBuilder -> uriBuilder.path("/reverse")
|
||||
.queryParam("lat", lat)
|
||||
@@ -22,6 +20,8 @@ public class NominatimClient {
|
||||
.queryParam("format", "jsonv2")
|
||||
.build())
|
||||
.retrieve()
|
||||
.bodyToMono(ReverseResponse.class);
|
||||
.bodyToMono(ReverseResponse.class)
|
||||
.map(response -> new GeocodingResponse(response.address()));
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,4 +1,4 @@
|
||||
package SuMoC.backend.nominatim;
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
@@ -15,3 +15,4 @@ public record ReverseResponse(
|
||||
@JsonProperty("address") Map<String, String> address
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
package SuMoC.backend.nominatim;
|
||||
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(NominatimProperties.class)
|
||||
public class NominatimClientConfig {
|
||||
|
||||
@Bean
|
||||
public WebClient nominatimWebClient(NominatimProperties properties) {
|
||||
return WebClient.builder()
|
||||
.baseUrl(properties.baseUrl())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package SuMoC.backend.nominatim;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "nominatim")
|
||||
public record NominatimProperties(
|
||||
String baseUrl
|
||||
) {
|
||||
}
|
||||
@@ -98,6 +98,11 @@ public class SecurityConfiguration {
|
||||
auth.requestMatchers("/friendship/**").hasAnyRole("ADMIN", "USER");
|
||||
auth.requestMatchers("/trip/**").hasAnyRole("USER", "ADMIN");
|
||||
auth.requestMatchers("/geocoding/**").hasAnyRole("USER", "ADMIN");
|
||||
|
||||
// gamification
|
||||
auth.requestMatchers("/badges/**").hasAnyRole("ADMIN", "USER");
|
||||
auth.requestMatchers("/leaderboard/**").hasAnyRole("ADMIN", "USER");
|
||||
|
||||
auth.requestMatchers("/notifications/**").hasAnyRole("USER", "ADMIN");
|
||||
//auth.requestMatchers("/error").permitAll();
|
||||
auth.anyRequest().authenticated();
|
||||
|
||||
@@ -39,7 +39,7 @@ public class UserAuthenticationController {
|
||||
@Operation(summary = "Registriert einen neuen Benutzer", description = "Erstellt einen neuen Benutzer und gibt die Benutzerdaten zurück")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Benutzer erfolgreich registriert",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = LoginResponseDTO.class))),
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = RegistrationResponseDTO.class))),
|
||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
|
||||
@@ -33,6 +33,8 @@ public class UserController {
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Nutzerprofil erfolgreich abgerufen",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = MinimalUserDTO.class))),
|
||||
@ApiResponse(responseCode = "403", description = "Nutzerprofil darf nicht aufgerufen werden",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "404", description = "Nutzerprofil nicht gefunden",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@@ -44,8 +46,8 @@ public class UserController {
|
||||
@Operation(summary = "Nutzer fragt sein eigenes Profil an", description = "Ein Nutzer kann sein eigenes Profil anfragen, um dessen Informationen einzusehen.")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Nutzerprofil erfolgreich abgerufen",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = MinimalUserDTO.class))),
|
||||
@ApiResponse(responseCode = "404", description = "Nutzerprofil nicht gefunden",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = MaximalUserDTO.class))),
|
||||
@ApiResponse(responseCode = "404", description = "Der Nutzer existiert nicht",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@GetMapping("/profile")
|
||||
@@ -55,10 +57,9 @@ public class UserController {
|
||||
|
||||
@Operation(summary = "Nutzer löscht sein eigenes Profil", description = "Ein Nutzer kann sein eigenes Profil löschen. Dies entfernt alle seine Daten aus dem System.")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Nutzerprofil erfolgreich gelöscht",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "404", description = "Nutzerprofil nicht gefunden",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
@ApiResponse(responseCode = "200", description = "Nutzerprofil erfolgreich gelöscht"),
|
||||
@ApiResponse(responseCode = "403", description = "Keine Berechtigung, fremdes Profil zu löschen"),
|
||||
@ApiResponse(responseCode = "404", description = "Der Nutzer existiert nicht")
|
||||
})
|
||||
@DeleteMapping("/delete/{id}")
|
||||
public ResponseEntity<Object> deleteUser(@PathVariable @NotNull Long id) {
|
||||
@@ -71,6 +72,16 @@ public class UserController {
|
||||
}
|
||||
|
||||
@Operation(summary = "Update a users private name.", description = "A user can change it's own private name that is shown to friends.")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Passwort erfolgreich geändert",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "403", description = "Nur autorisierte Personen dürfen das Passwort ändern",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "404", description = "Der Nutzer existiert nicht",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/setPrivateName/{id}")
|
||||
public ResponseEntity<Void> setPrivateName(@PathVariable @NotNull Long id,
|
||||
@RequestParam @NotBlank String newPrivateName) {
|
||||
@@ -81,8 +92,12 @@ public class UserController {
|
||||
@Operation(summary = "Nutzer ändert sein Passwort", description = "Ein Nutzer kann sein Passwort ändern, um die Sicherheit seines Kontos zu gewährleisten.")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Passwort erfolgreich geändert",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = LoginResponseDTO.class))),
|
||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "403", description = "Nur autorisierte Personen dürfen das Passwort ändern",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "404", description = "Der Nutzer existiert nicht",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/setPassword/{id}")
|
||||
@@ -94,8 +109,14 @@ public class UserController {
|
||||
@Operation(summary = "Nutzer ändert seine E-Mail-Adresse", description = "Ein Nutzer kann seine E-Mail-Adresse ändern, um sicherzustellen, dass seine Kontaktdaten aktuell sind.")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "E-Mail-Adresse erfolgreich geändert",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = LoginResponseDTO.class))),
|
||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "403", description = "Nur autorisierte Personen dürfen die Email ändern",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "404", description = "Der Nutzer existiert nicht",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "409", description = "Die Email wurde bereits vergeben",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/setEmail/{id}")
|
||||
@@ -109,6 +130,10 @@ public class UserController {
|
||||
@ApiResponse(responseCode = "200", description = "Sichtbarkeits- und Datenschutzeinstellungen erfolgreich geändert",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "403", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "409", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/setVisibilityPrivacy")
|
||||
|
||||
@@ -2,6 +2,7 @@ package SuMoC.backend.user.mapper;
|
||||
|
||||
|
||||
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
||||
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||
import SuMoC.backend.user.dtos.UserDTO;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import org.mapstruct.Mapper;
|
||||
@@ -13,6 +14,8 @@ public interface UserMapper {
|
||||
User toUser(UserDTO userDTO);
|
||||
|
||||
MaximalUserDTO toMaximalUserDTO(User user);
|
||||
|
||||
MinimalUserDTO toMinimalUserDTO(User user);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
package SuMoC.backend.user.models;
|
||||
|
||||
import SuMoC.backend.notification.models.NotificationToken;
|
||||
import SuMoC.backend.gamification.badges.models.UserBadge;
|
||||
import SuMoC.backend.trip.models.Trip;
|
||||
import SuMoC.backend.user.enums.RoleName;
|
||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||
import SuMoC.backend.user.stats.StatsList;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
@Getter
|
||||
@Setter
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@@ -63,6 +59,13 @@ public class User {
|
||||
|
||||
public User() {
|
||||
}
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
|
||||
private Set<UserBadge> badges = new HashSet<>();
|
||||
|
||||
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private StatsList statsList;
|
||||
|
||||
public User() {}
|
||||
|
||||
// public User(Long id, String publicName, String privateName, String email, String password, VisibilityPrivacy visibilityPrivacy, String friendCode, Set<Trip> trips, Set<Friendship> friendships, Set<RoleName> roles) {
|
||||
// this.id = id;
|
||||
@@ -86,5 +89,94 @@ public class User {
|
||||
this.friendCode = java.util.UUID.randomUUID().toString(); // generate unique friend code
|
||||
this.roles = new HashSet<>();
|
||||
this.roles.add(RoleName.USER);
|
||||
this.statsList = new StatsList(this);
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getPublicName() {
|
||||
return publicName;
|
||||
}
|
||||
|
||||
public void setPublicName(String publicName) {
|
||||
this.publicName = publicName;
|
||||
}
|
||||
|
||||
public String getPrivateName() {
|
||||
return privateName;
|
||||
}
|
||||
|
||||
public void setPrivateName(String privateName) {
|
||||
this.privateName = privateName;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public VisibilityPrivacy getVisibilityPrivacy() {
|
||||
return visibilityPrivacy;
|
||||
}
|
||||
|
||||
public void setVisibilityPrivacy(VisibilityPrivacy visibilityPrivacy) {
|
||||
this.visibilityPrivacy = visibilityPrivacy;
|
||||
}
|
||||
|
||||
public String getFriendCode() {
|
||||
return friendCode;
|
||||
}
|
||||
|
||||
public void setFriendCode(String friendCode) {
|
||||
this.friendCode = friendCode;
|
||||
}
|
||||
|
||||
public Set<Trip> getTrips() {
|
||||
return trips;
|
||||
}
|
||||
|
||||
public void setTrips(Set<Trip> trips) {
|
||||
this.trips = trips;
|
||||
}
|
||||
|
||||
public Set<Friendship> getFriendships() {
|
||||
return friendships;
|
||||
}
|
||||
|
||||
public void setFriendships(Set<Friendship> friendships) {
|
||||
this.friendships = friendships;
|
||||
}
|
||||
|
||||
public Set<RoleName> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(Set<RoleName> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public Set<UserBadge> getBadges() { return badges; }
|
||||
|
||||
public void setBadges(Set<UserBadge> badges) { this.badges = badges; }
|
||||
|
||||
public StatsList getStats() { return statsList;}
|
||||
|
||||
public void setStats(StatsList statsList) { this.statsList = statsList; }
|
||||
}
|
||||
|
||||
@@ -17,4 +17,6 @@ public interface FriendshipRepository extends JpaRepository<Friendship, Long> {
|
||||
List<Friendship> findByFriendIdAndStatus(Long friendId, FriendShipStatus status);
|
||||
|
||||
Friendship findByUserAndFriend(User user, User friend);
|
||||
|
||||
Friendship findByUserIdAndFriendIdAndStatus(Long id, Long otherUserId, FriendShipStatus friendShipStatus);
|
||||
}
|
||||
|
||||
@@ -13,4 +13,6 @@ public interface UserRepository extends JpaRepository<User, Long> {
|
||||
boolean existsByPublicName(String username);
|
||||
|
||||
boolean existsByEmail(String email);
|
||||
|
||||
Optional<User> findById(Long id);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package SuMoC.backend.user.service;
|
||||
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
@Component
|
||||
public class CurrentUserService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public CurrentUserService(UserRepository userRepository) {
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
public User get() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (auth == null || !auth.isAuthenticated()) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
"Nicht authentifiziert");
|
||||
}
|
||||
|
||||
return userRepository.findByEmail(auth.getName())
|
||||
.orElseThrow(() -> new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND,
|
||||
"Der Nutzer existiert nicht"));
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
@@ -270,4 +271,56 @@ public class FriendshipService {
|
||||
|
||||
return dtoList;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public record NameWithFriendship(
|
||||
Long id,
|
||||
String name,
|
||||
boolean friendship
|
||||
) {}
|
||||
|
||||
public List<NameWithFriendship> getPrivateNameIfFriendshipAccepted(User user, List<Long> otherUserIds) {
|
||||
List<NameWithFriendship> result = new ArrayList<>();
|
||||
|
||||
for (Long otherUserId : otherUserIds) {
|
||||
|
||||
Friendship friendship =
|
||||
friendshipRepository.findByUserIdAndFriendIdAndStatus(
|
||||
user.getId(),
|
||||
otherUserId,
|
||||
FriendShipStatus.ACCEPTED
|
||||
);
|
||||
|
||||
if (friendship != null) {
|
||||
User target = friendship.getFriend();
|
||||
result.add(new NameWithFriendship(
|
||||
target.getId(),
|
||||
target.getPrivateName(),
|
||||
true
|
||||
));
|
||||
} else {
|
||||
User target = userRepository.findById(otherUserId)
|
||||
.orElseThrow(() -> new RuntimeException("User not found"));
|
||||
result.add(new NameWithFriendship(
|
||||
target.getId(),
|
||||
target.getPublicName(),
|
||||
false
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public List<User> getAcceptedFriends(User user) {
|
||||
List<Friendship> friendships = friendshipRepository.findByUserIdAndStatus(user.getId(), FriendShipStatus.ACCEPTED);
|
||||
List<User> friends = new ArrayList<>();
|
||||
|
||||
for (Friendship friendship : friendships) {
|
||||
friends.add(friendship.getFriend());
|
||||
}
|
||||
|
||||
return friends;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package SuMoC.backend.user.service;
|
||||
|
||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||
import SuMoC.backend.user.models.Friendship;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class PrivacyService {
|
||||
|
||||
private final FriendshipService friendshipService;
|
||||
private UserRepository userRepository;
|
||||
|
||||
public PrivacyService(FriendshipService friendshipService, UserRepository userRepository) {
|
||||
this.friendshipService = friendshipService;
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
public boolean checkVisibility(User sender, User requested) {
|
||||
|
||||
if(requested.getVisibilityPrivacy().equals(VisibilityPrivacy.NONE)) { return false; }
|
||||
|
||||
if(friendshipService.getBlockedUsers(requested.getId()).stream()
|
||||
.anyMatch(dto -> Objects.equals(dto.getId(), sender.getId()))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(requested.getVisibilityPrivacy().equals(VisibilityPrivacy.PUBLIC)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return friendshipService.getAcceptedFriends(requested).stream().anyMatch(user ->
|
||||
user.getId().equals(sender.getId()));
|
||||
}
|
||||
|
||||
public boolean checkVisibility(User sender, Long id) {
|
||||
User requested = userRepository.findById(id).orElseThrow(() -> new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND,
|
||||
"Nutzer existiert nicht"
|
||||
));
|
||||
return checkVisibility(sender, requested);
|
||||
}
|
||||
}
|
||||
@@ -5,98 +5,88 @@ import SuMoC.backend.security.services.TokenService;
|
||||
import SuMoC.backend.trip.TripMapper;
|
||||
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
||||
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||
import SuMoC.backend.user.enums.RoleName;
|
||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||
import SuMoC.backend.user.mapper.FriendshipMapper;
|
||||
import SuMoC.backend.user.mapper.UserMapper;
|
||||
import SuMoC.backend.user.models.Friendship;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class UserService {
|
||||
|
||||
private final CurrentUserService currentUser;
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
private final UserMapper userMapper;
|
||||
private final FriendshipMapper friendshipMapper;
|
||||
private final TripMapper tripMapper;
|
||||
|
||||
private final TokenService tokenService;;
|
||||
private final PrivacyService privacyService;
|
||||
private final FriendshipService friendshipService;
|
||||
|
||||
@Autowired
|
||||
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, UserMapper userMapper, FriendshipMapper friendshipMapper, TripMapper tripMapper, TokenService tokenService) {
|
||||
public UserService(CurrentUserService currentUser, UserRepository userRepository, PasswordEncoder passwordEncoder, UserMapper userMapper, TokenService tokenService, PrivacyService privacyService, FriendshipService friendshipService) {
|
||||
this.currentUser = currentUser;
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.userMapper = userMapper;
|
||||
this.friendshipMapper = friendshipMapper;
|
||||
this.tripMapper = tripMapper;
|
||||
this.tokenService = tokenService;
|
||||
this.privacyService = privacyService;
|
||||
this.friendshipService = friendshipService;
|
||||
}
|
||||
|
||||
|
||||
public MinimalUserDTO getUser(long id) {
|
||||
User sender = getSender();
|
||||
|
||||
User requested = userRepository.findById(id).get();
|
||||
|
||||
FriendShipStatus status;
|
||||
// Prüfen, ob eine Freundschaft zum Sender existiert
|
||||
if(sender.equals(requested)) {
|
||||
status = FriendShipStatus.ACCEPTED;
|
||||
} else {
|
||||
status = requested.getFriendships().stream()
|
||||
.filter(f -> sender.equals(f.getFriend()) || sender.equals(f.getUser()))
|
||||
.map(Friendship::getStatus)
|
||||
.findFirst()
|
||||
.orElse(null); // nimmt die erste gefundene Freundschaft
|
||||
User sender = currentUser.get();
|
||||
User requested = userRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND, "Nutzer existiert nicht"
|
||||
));
|
||||
// TODO: Check tomorrow if this makes sense
|
||||
// TODO: Can Users see the minimalDTO if they are blocked?
|
||||
if(friendshipService.getBlockedUsers(id).stream().anyMatch(blocked -> blocked.getId().equals(requested.getId()))) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.FORBIDDEN,
|
||||
"Der Nutzer hat dich blockiert."
|
||||
);
|
||||
}
|
||||
if (FriendShipStatus.BLOCKED.equals(status)) throw new RuntimeException("Kein Zugriff auf dieses Profil");
|
||||
|
||||
//TODO: Think about private profile visibility heuristics
|
||||
// if (requested.getVisibilityPrivacy() == VisibilityPrivacy.NONE && !status.equals(FriendShipStatus.ACCEPTED)) {
|
||||
// throw new RuntimeException("Kein Zugriff auf dieses Profil");
|
||||
// }
|
||||
|
||||
if (status == null) {
|
||||
if (privacyService.checkVisibility(sender, id)) {
|
||||
return new MinimalUserDTO(requested.getId(), requested.getPrivateName());
|
||||
} else {
|
||||
return new MinimalUserDTO(requested.getId(), requested.getPublicName());
|
||||
}
|
||||
|
||||
switch (status) {
|
||||
case ACCEPTED -> {
|
||||
return new MinimalUserDTO(requested.getId(), requested.getPrivateName());
|
||||
}
|
||||
|
||||
default -> {
|
||||
return new MinimalUserDTO(requested.getId(), requested.getPublicName());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
public void deleteUser(Long id) {
|
||||
User sender = getSender();
|
||||
User sender = currentUser.get();
|
||||
|
||||
boolean isAdmin = sender.getRoles().contains(RoleName.ADMIN);
|
||||
boolean isOwnProfile = sender.getId().equals(id);
|
||||
|
||||
if (!isAdmin && !isOwnProfile) {
|
||||
throw new RuntimeException("Ein Nutzer kann nur sein eigenes Profil löschen.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.FORBIDDEN,
|
||||
"Ein Nutzer kann nur sein eigenes Profil löschen.");
|
||||
}
|
||||
|
||||
if (!userRepository.existsById(id)) {
|
||||
throw new RuntimeException("User existiert nicht.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND,
|
||||
"Nutzer existiert nicht.");
|
||||
}
|
||||
|
||||
userRepository.deleteById(id);
|
||||
@@ -106,24 +96,36 @@ public class UserService {
|
||||
|
||||
|
||||
public LoginResponseDTO setPassword(Long id, String newPassword) {
|
||||
User sender = getSender();
|
||||
User sender = currentUser.get();
|
||||
if (!sender.getId().equals(id) && !sender.getRoles().contains(RoleName.ADMIN)) {
|
||||
throw new RuntimeException("Ein Nutzer kann nur sein eigenes Passwort ändern.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.FORBIDDEN,
|
||||
"Ein Nutzer kann nur sein eigenes Passwort ändern.");
|
||||
}
|
||||
|
||||
if (newPassword.isBlank()) {
|
||||
throw new RuntimeException("Das Passwort darf nicht leer sein.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
"Das Passwort darf nicht leer sein."
|
||||
);
|
||||
}
|
||||
|
||||
if (newPassword.length() < 8) {
|
||||
throw new RuntimeException("Das Passwort muss mindestens 8 Zeichen lang sein.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
"Das Passwort muss mindestens 8 Zeichen lang sein."
|
||||
);
|
||||
}
|
||||
// TODO: Add Email Notification for password change
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
sender.setPassword(passwordEncoder.encode(newPassword));
|
||||
userRepository.save(sender);
|
||||
|
||||
User updatedSender = userRepository.findById(id).get();
|
||||
User updatedSender = userRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND,
|
||||
"Nutzer existiert nicht"
|
||||
));
|
||||
|
||||
return new LoginResponseDTO(userMapper.toUserDTO(updatedSender),
|
||||
tokenService.generateUserJwt(authentication, userMapper.toUserDTO(updatedSender)));
|
||||
@@ -131,22 +133,30 @@ public class UserService {
|
||||
}
|
||||
|
||||
public LoginResponseDTO setEmail(Long id, String newEmail) {
|
||||
User sender = getSender();
|
||||
User sender = currentUser.get();
|
||||
System.out.println(sender.getId());
|
||||
|
||||
if (!sender.getId().equals(id)) {
|
||||
throw new RuntimeException("Ein Nutzer kann nur seine eigene E-Mail-Adresse ändern.");
|
||||
}
|
||||
|
||||
if (userRepository.existsByEmail(newEmail)) {
|
||||
throw new RuntimeException("Diese E-Mail ist bereits vergeben.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.FORBIDDEN,
|
||||
"Ein Nutzer kann nur seine eigene E-Mail-Adresse ändern."
|
||||
);
|
||||
}
|
||||
|
||||
String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
|
||||
if (!newEmail.matches(emailRegex)) {
|
||||
throw new RuntimeException("Ungültige E-Mail-Adresse.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
"Ungültige E-Mail-Adresse."
|
||||
);
|
||||
}
|
||||
|
||||
if (userRepository.existsByEmail(newEmail)) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.CONFLICT,
|
||||
"Diese E-Mail ist bereits vergeben."
|
||||
);
|
||||
}
|
||||
|
||||
// TODO: Add Email Notification for password change
|
||||
System.out.println("################ Changing Email ################");
|
||||
@@ -154,14 +164,18 @@ public class UserService {
|
||||
sender.setEmail(newEmail);
|
||||
userRepository.save(sender);
|
||||
|
||||
User updatedUser = userRepository.findById(sender.getId()).orElseThrow();
|
||||
User updatedUser = userRepository.findById(sender.getId())
|
||||
.orElseThrow(() -> new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND,
|
||||
"Der Nutzer existiert nicht"
|
||||
));
|
||||
System.out.println("################# Returning LoginResponse ################");
|
||||
return new LoginResponseDTO(userMapper.toUserDTO(updatedUser),
|
||||
tokenService.generateUserJwt(authentication, userMapper.toUserDTO(updatedUser), newEmail));
|
||||
}
|
||||
|
||||
public void setVisibilityPrivacy(VisibilityPrivacy visibilityPrivacy) {
|
||||
User sender = getSender();
|
||||
User sender = currentUser.get();
|
||||
|
||||
sender.setVisibilityPrivacy(visibilityPrivacy);
|
||||
userRepository.save(sender);
|
||||
@@ -169,37 +183,24 @@ public class UserService {
|
||||
}
|
||||
|
||||
public void setPrivateName(Long id, String newPrivateName) {
|
||||
User sender = getSender();
|
||||
User sender = currentUser.get();
|
||||
if (!sender.getId().equals(id) && !sender.getRoles().contains(RoleName.ADMIN)) {
|
||||
throw new RuntimeException("Ein Nutzer kann nur seinen eigenen privaten Namen ändern.");
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Ein Nutzer kann nur seinen eigenen privaten Namen ändern.");
|
||||
}
|
||||
User userToChange = userRepository.findById(id).orElseThrow();
|
||||
User userToChange = userRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND,
|
||||
"Der Nutzer Existitert nicht."));
|
||||
|
||||
// TODO: Add String Validator
|
||||
userToChange.setPrivateName(newPrivateName);
|
||||
userRepository.save(userToChange);
|
||||
}
|
||||
|
||||
|
||||
public MaximalUserDTO getSelf() {
|
||||
User sender = getSender();
|
||||
User sender = currentUser.get();
|
||||
return userMapper.toMaximalUserDTO(sender);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public User getSender() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (auth == null || !auth.isAuthenticated()) {
|
||||
throw new RuntimeException("Nicht authentifiziert");
|
||||
}
|
||||
|
||||
return userRepository.findByEmail(auth.getName())
|
||||
.orElseThrow(() -> new RuntimeException(
|
||||
"Authentifizierter Nutzer existiert nicht mehr: " + auth.getName()
|
||||
));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package SuMoC.backend.user.stats;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class Stats {
|
||||
|
||||
@Schema(description = "Unique identifier of the Stats.", example = "1", required = true)
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "The StatsList to which these stats belong.", required = true)
|
||||
@ManyToOne
|
||||
private StatsList statsList;
|
||||
|
||||
|
||||
@Schema(description = "Experience points earned by the user.", example = "1500", required = true)
|
||||
private Long XP;
|
||||
|
||||
@Schema(description = "Amount of CO2 saved by the user in grams.", example = "2500", required = true)
|
||||
private Long CO2_SAVED;
|
||||
|
||||
@Schema(description = "Total kilometers cycled by the user in timeframe.", example = "120", required = true)
|
||||
private Long KM_CYCLED;
|
||||
|
||||
@Schema(description = "Total kilometers walked by the user in timeframe.", example = "80", required = true)
|
||||
private Long KM_WALKED;
|
||||
|
||||
@Schema(description = "Total kilometers traveled by public transport in timeframe.", example = "200", required = true)
|
||||
private Long KM_PUBLIC_TRANSPORT;
|
||||
|
||||
@Schema(description = "Total kilometers driven by the user in timeframe.", example = "300", required = true)
|
||||
private Long KM_DRIVEN;
|
||||
|
||||
|
||||
// Constructors
|
||||
|
||||
public Stats() {
|
||||
|
||||
}
|
||||
|
||||
public Stats(StatsList statsList) {
|
||||
this.statsList = statsList;
|
||||
this.XP = 0L;
|
||||
this.CO2_SAVED = 0L;
|
||||
this.KM_CYCLED = 0L;
|
||||
this.KM_WALKED = 0L;
|
||||
this.KM_PUBLIC_TRANSPORT = 0L;
|
||||
this.KM_DRIVEN = 0L;
|
||||
}
|
||||
|
||||
|
||||
// Getters and Setters
|
||||
|
||||
|
||||
public StatsList getStatsList() {
|
||||
return statsList;
|
||||
}
|
||||
|
||||
public void setStatsList(StatsList statsList) {
|
||||
this.statsList = statsList;
|
||||
}
|
||||
|
||||
public Long getXP() {
|
||||
return XP;
|
||||
}
|
||||
|
||||
public void setXP(Long XP) {
|
||||
this.XP = XP;
|
||||
}
|
||||
|
||||
public Long getCO2_SAVED() {
|
||||
return CO2_SAVED;
|
||||
}
|
||||
|
||||
public void setCO2_SAVED(Long CO2_SAVED) {
|
||||
this.CO2_SAVED = CO2_SAVED;
|
||||
}
|
||||
|
||||
public Long getKM_CYCLED() {
|
||||
return KM_CYCLED;
|
||||
}
|
||||
|
||||
public void setKM_CYCLED(Long KM_CYCLED) {
|
||||
this.KM_CYCLED = KM_CYCLED;
|
||||
}
|
||||
|
||||
public Long getKM_WALKED() {
|
||||
return KM_WALKED;
|
||||
}
|
||||
|
||||
public void setKM_WALKED(Long KM_WALKED) {
|
||||
this.KM_WALKED = KM_WALKED;
|
||||
}
|
||||
|
||||
public Long getKM_PUBLIC_TRANSPORT() {
|
||||
return KM_PUBLIC_TRANSPORT;
|
||||
}
|
||||
|
||||
public void setKM_PUBLIC_TRANSPORT(Long KM_PUBLIC_TRANSPORT) {
|
||||
this.KM_PUBLIC_TRANSPORT = KM_PUBLIC_TRANSPORT;
|
||||
}
|
||||
|
||||
public Long getKM_DRIVEN() {
|
||||
return KM_DRIVEN;
|
||||
}
|
||||
|
||||
public void setKM_DRIVEN(Long KM_DRIVEN) {
|
||||
this.KM_DRIVEN = KM_DRIVEN;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package SuMoC.backend.user.stats;
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
@Entity
|
||||
public class StatsList {
|
||||
@Schema(description = "Unique identifier of the StatsList.", example = "1")
|
||||
@Id
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "The User to whom this StatsList belongs.")
|
||||
@OneToOne
|
||||
@MapsId
|
||||
@JoinColumn(name = "user_id")
|
||||
private User user;
|
||||
|
||||
@Schema(description = "Total stats of the user.")
|
||||
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private Stats totalStats;
|
||||
|
||||
@Schema(description = "Monthly stats of the user.")
|
||||
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private Stats monthlyStats;
|
||||
|
||||
@Schema(description = "Weekly stats of the user.")
|
||||
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private Stats weeklyStats;
|
||||
|
||||
|
||||
// Constructors
|
||||
|
||||
public StatsList() {}
|
||||
|
||||
public StatsList(User user) {
|
||||
this.user = user;
|
||||
this.totalStats = new Stats(this);
|
||||
this.monthlyStats = new Stats(this);
|
||||
this.weeklyStats = new Stats(this);
|
||||
}
|
||||
|
||||
|
||||
// Getter & Setter
|
||||
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public Stats getTotalStats() {
|
||||
return totalStats;
|
||||
}
|
||||
|
||||
public void setTotalStats(Stats totalStats) {
|
||||
this.totalStats = totalStats;
|
||||
}
|
||||
|
||||
public Stats getMonthlyStats() {
|
||||
return monthlyStats;
|
||||
}
|
||||
|
||||
public void setMonthlyStats(Stats monthlyStats) {
|
||||
this.monthlyStats = monthlyStats;
|
||||
}
|
||||
|
||||
public Stats getWeeklyStats() {
|
||||
return weeklyStats;
|
||||
}
|
||||
|
||||
public void setWeeklyStats(Stats weeklyStats) {
|
||||
this.weeklyStats = weeklyStats;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Other Methods
|
||||
|
||||
public Stats getStats(Timeframe timeframe) {
|
||||
Stats stats;
|
||||
switch (timeframe) {
|
||||
case TOTAL -> stats = this.totalStats;
|
||||
case MONTHLY -> stats = this.monthlyStats;
|
||||
case WEEKLY -> stats = this.weeklyStats;
|
||||
default -> throw new IllegalArgumentException("Unknown timeframe: " + timeframe);
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value of a specific stat field for a given timeframe.
|
||||
* @param timeframe
|
||||
* @param fieldName
|
||||
* @return
|
||||
*/
|
||||
public Long getStatValue(Timeframe timeframe, String fieldName) {
|
||||
try {
|
||||
Stats stats = getStats(timeframe);
|
||||
|
||||
Field field = Stats.class.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
return (Long) field.get(stats);
|
||||
|
||||
} catch (NoSuchFieldException | IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the Field object of a specific stat field for a given timeframe.
|
||||
* @param timeframe
|
||||
* @param fieldName
|
||||
* @return
|
||||
*/
|
||||
public Field getStatField(Timeframe timeframe, String fieldName) {
|
||||
try {
|
||||
Stats stats = getStats(timeframe);
|
||||
|
||||
Field field = Stats.class.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
return field;
|
||||
|
||||
} catch (NoSuchFieldException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adds a value to a specific stat field for a given timeframe.
|
||||
* @param timeframe
|
||||
* @param fieldName
|
||||
* @param value
|
||||
*/
|
||||
public void addToStat(Timeframe timeframe, String fieldName, long value) {
|
||||
try {
|
||||
Stats stats = getStats(timeframe);
|
||||
|
||||
Field field = getStatField(timeframe, fieldName);
|
||||
field.setAccessible(true);
|
||||
|
||||
Long currentValue = (Long) field.get(stats);
|
||||
if (currentValue == null) currentValue = 0L;
|
||||
|
||||
field.set(stats, currentValue + value);
|
||||
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException("Failed to update stat " + fieldName, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adds a value to a specific stat field for all timeframes.
|
||||
* @param fieldName
|
||||
* @param value
|
||||
*/
|
||||
public void addToAllStats(String fieldName, long value) {
|
||||
addToStat(Timeframe.TOTAL, fieldName, value);
|
||||
addToStat(Timeframe.MONTHLY, fieldName, value);
|
||||
addToStat(Timeframe.WEEKLY, fieldName, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets all stats for a given timeframe to zero.
|
||||
* @param timeframe
|
||||
*/
|
||||
public void resetStats(Timeframe timeframe) {
|
||||
try {
|
||||
Stats stats = getStats(timeframe);
|
||||
|
||||
Field[] fields = Stats.class.getDeclaredFields();
|
||||
for (Field field : fields) {
|
||||
if (field.getType().equals(Long.class)
|
||||
&& !field.isAnnotationPresent(Id.class)) {
|
||||
field.setAccessible(true);
|
||||
field.set(stats, 0L);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException("Failed to reset stats for timeframe " + timeframe, e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package SuMoC.backend.user.stats;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface StatsListRepository
|
||||
extends JpaRepository<StatsList, Long>,
|
||||
JpaSpecificationExecutor<StatsList> {
|
||||
|
||||
Optional<StatsList> findByUserId(Long userId);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package SuMoC.backend.user.stats;
|
||||
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
import jakarta.persistence.criteria.Join;
|
||||
import jakarta.persistence.criteria.JoinType;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
|
||||
public final class StatsListSpecifications {
|
||||
|
||||
private StatsListSpecifications() {}
|
||||
|
||||
public static Specification<StatsList> orderByStat(
|
||||
Timeframe timeframe,
|
||||
String statField
|
||||
) {
|
||||
return (root, query, cb) -> {
|
||||
|
||||
Join<StatsList, Stats> stats =
|
||||
root.join(timeframe.getStatsField(), JoinType.LEFT);
|
||||
|
||||
query.orderBy(cb.desc(stats.get(statField)));
|
||||
|
||||
return cb.conjunction();
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<StatsList> higherThan(
|
||||
Timeframe timeframe,
|
||||
String statField,
|
||||
long value
|
||||
) {
|
||||
return (root, query, cb) -> {
|
||||
Join<StatsList, Stats> stats =
|
||||
root.join(timeframe.getStatsField(), JoinType.LEFT);
|
||||
|
||||
return cb.greaterThan(
|
||||
stats.get(statField),
|
||||
value
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package SuMoC.backend.user.stats;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface StatsRepository extends JpaRepository<Stats, Long> {
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package SuMoC.backend.user.stats;
|
||||
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class StatsService {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Scheduled(cron = "0 0 0 ? * MON")
|
||||
public void resetWeeklyStats() {
|
||||
userRepository.findAll().forEach( user -> {
|
||||
user.getStats().resetStats(Timeframe.WEEKLY);
|
||||
});
|
||||
|
||||
System.out.println("###### Weekly stats have been reset. ######");
|
||||
}
|
||||
|
||||
@Scheduled(cron = "0 0 0 1 * ?")
|
||||
public void resetMonthlyStats() {
|
||||
userRepository.findAll().forEach( user -> {
|
||||
user.getStats().resetStats(Timeframe.MONTHLY);
|
||||
});
|
||||
|
||||
System.out.println("###### Monthly stats have been reset. ######");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user