Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
This commit is contained in:
@@ -2,11 +2,12 @@ package SuMoC.backend.common.converter;
|
||||
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
|
||||
/**
|
||||
* This converter handles the conversion between Java's DayOfWeek enum and the SQL DAY_OF_WEEK integer representation.
|
||||
* In Java, DayOfWeek uses 1 (Monday) to 7 (Sunday), while SQL's DAY_OF_WEEK function returns 1 (Sunday) to 7 (Saturday).
|
||||
* In Java, DayOfWeek uses 1 (Monday) to 7 (Sunday), while SQL's DAY_OF_WEEK function returns 0 (Sunday) to 6 (Saturday).
|
||||
*/
|
||||
@Converter(autoApply = true)
|
||||
public class DayOfWeekConverter implements AttributeConverter<DayOfWeek, Integer> {
|
||||
@@ -16,8 +17,8 @@ public class DayOfWeekConverter implements AttributeConverter<DayOfWeek, Integer
|
||||
if (attribute == null) {
|
||||
return null;
|
||||
}
|
||||
// Convert Java DayOfWeek (1=Monday) to SQL format (1=Sunday)
|
||||
return (attribute.getValue() % 7) + 1;
|
||||
// Convert Java DayOfWeek (1=Monday, ..., 7=Sunday) to SQL DOW (0=Sunday, ..., 6=Saturday)
|
||||
return attribute.getValue() % 7;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -25,10 +26,7 @@ public class DayOfWeekConverter implements AttributeConverter<DayOfWeek, Integer
|
||||
if (dbData == null) {
|
||||
return null;
|
||||
}
|
||||
// Convert SQL format (1=Sunday) back to Java DayOfWeek (1=Monday)
|
||||
// Example: SQL 1 (Sunday) -> Java 7
|
||||
// SQL 7 (Saturday) -> Java 6
|
||||
// SQL 2 (Monday) -> Java 1
|
||||
return DayOfWeek.of(((dbData + 5) % 7) + 1);
|
||||
// Convert SQL DOW (0=Sunday, ..., 6=Saturday) to Java DayOfWeek (1=Monday, ..., 7=Sunday)
|
||||
return DayOfWeek.of(dbData == 0 ? 7 : dbData);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,4 +251,9 @@ public class DevController {
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/test-detection-and-notification-regular-trips")
|
||||
public void testDetectionAndNotificationOfRegularTrips() {
|
||||
regularTripSuggestionService.detectAndNotifyRegularTripsForTodaysDayOfWeek();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Notification System Overview
|
||||
|
||||
This document provides an overview of the notification system for client developers integrating with the backend. It
|
||||
explains notification types, expected payloads, and device token registration.
|
||||
|
||||
## Notification Types
|
||||
|
||||
Notifications sent to clients are categorized by `NotificationType`:
|
||||
|
||||
- **TREND**: Informs users about changes in their mobility trends (e.g., reduced car usage). See
|
||||
`TrendNotificationService`.
|
||||
- **ADHOC_ALTERNATIVE**: Suggests a more sustainable alternative after a recent trip upload. See
|
||||
`AdHocSuggestionService`.
|
||||
- **REGULAR_TRIP_ALTERNATIVE**: Suggests an alternative for a detected regular trip (e.g., weekly commute). See
|
||||
`RegularTripSuggestionService`.
|
||||
- **FRIENDSHIP_REQUEST_RECEIVED**: Notifies about a new pending friendship request.
|
||||
|
||||
See `NotificationType.java` for the full enum.
|
||||
|
||||
## Notification Payloads
|
||||
|
||||
Each notification type includes a data payload. The main DTOs in the notification body are:
|
||||
|
||||
- **TREND**: Contains a list of `TrendDetectionDTO` objects, each describing a detected trend for the user. The
|
||||
structure includes fields such as `userId`, `timespan`, `type`, `attribute`, `deltaType`, `changeValue`, and
|
||||
`trendConnotation`. See `TrendDetectionDTO.java` for details.
|
||||
- **ADHOC_ALTERNATIVE**: Contains a list of `RouteDTO` objects representing the best alternative(s) for a recent trip (
|
||||
see `AdHocSuggestionService`).
|
||||
- **REGULAR_TRIP_ALTERNATIVE**: Contains a list of 1 or 2 `RouteDTO` objects for the best alternative(s) to a detected
|
||||
regular trip, depending on user preferences (e.g., if `preferPhysicalActivity` is set, two alternatives may be
|
||||
included). See `RegularTripSuggestionService` and `RegularTripDetectionService` for details.
|
||||
- **FRIENDSHIP_REQUEST_RECEIVED**: Contains a `friendshipDTO` where `friend` is the user who sent the request. See
|
||||
`FriendshipDTO.java`.
|
||||
|
||||
## Device Token Registration
|
||||
|
||||
To receive push notifications, clients must register their device token. Token registration is handled in the
|
||||
`NotificationController`. The backend stores or updates the token for the authenticated user.
|
||||
|
||||
---
|
||||
|
||||
## For Backend Developers
|
||||
|
||||
To queue notifications for users, use the `NotificationSchedulerService` as the main entry point. This service provides
|
||||
methods to schedule notifications with the appropriate type and payload. See `NotificationSchedulerService.java` for
|
||||
usage details.
|
||||
|
||||
---
|
||||
For further details, refer to the respective service and DTO classes in the codebase.
|
||||
@@ -16,5 +16,9 @@ public enum NotificationType {
|
||||
* An alternative suggestion that refers to a detected regular trip.
|
||||
* E.g. user drives by car every monday at 8 am and there is a sustainable alternative.
|
||||
*/
|
||||
REGULAR_TRIP_ALTERNATIVE
|
||||
REGULAR_TRIP_ALTERNATIVE,
|
||||
/**
|
||||
* A notification informing the user about a new pending friendship request.
|
||||
*/
|
||||
FRIENDSHIP_REQUEST_RECEIVED,
|
||||
}
|
||||
|
||||
+27
-2
@@ -15,6 +15,10 @@ import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This service is the main entry point to schedule notifications to be sent to a users' mobile device.
|
||||
* It creates Notification entities in the database with status PENDING which are then later processed by the notification worker.
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationSchedulerService {
|
||||
@@ -25,6 +29,14 @@ public class NotificationSchedulerService {
|
||||
|
||||
private final EntityManager entityManager;
|
||||
|
||||
/**
|
||||
* Can be used to schedule multiple notifications at once. Notifieable interface allows sending to multiple users.
|
||||
* dataBodies need to be serializable to JSON.
|
||||
*
|
||||
* @param dataBodies
|
||||
* @param notificationType
|
||||
* @param earliestTimeOfDayToSend
|
||||
*/
|
||||
public void scheduleAll(List<Notifieable> dataBodies,
|
||||
NotificationType notificationType,
|
||||
LocalTime earliestTimeOfDayToSend
|
||||
@@ -53,11 +65,20 @@ public class NotificationSchedulerService {
|
||||
notificationRepository.saveAll(notifications);
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules a notification to be sent to the specified user.
|
||||
* Data body needs to be serializable to JSON.
|
||||
*
|
||||
* @param userId
|
||||
* @param dataBody
|
||||
* @param notificationType
|
||||
* @param earliestTimeOfDayToSend TOD from which on the notification can be sent. If null, send as soon as possible.
|
||||
*/
|
||||
public void schedule(
|
||||
Long userId,
|
||||
Object dataBody,
|
||||
NotificationType notificationType,
|
||||
LocalTime earliestTimeOfDayToSend
|
||||
NotificationType notificationType,
|
||||
LocalTime earliestTimeOfDayToSend
|
||||
) {
|
||||
String dataBodyJson;
|
||||
try {
|
||||
@@ -66,6 +87,10 @@ public class NotificationSchedulerService {
|
||||
throw new RuntimeException("Failed to serialize notification data body", e);
|
||||
}
|
||||
|
||||
if (earliestTimeOfDayToSend == null) {
|
||||
earliestTimeOfDayToSend = LocalTime.now();
|
||||
}
|
||||
|
||||
User userProxy = entityManager.getReference(User.class, userId);
|
||||
|
||||
Notification notification = Notification.builder()
|
||||
|
||||
@@ -7,6 +7,7 @@ import SuMoC.backend.trip.Modality;
|
||||
import SuMoC.backend.trip.TripMapper;
|
||||
import SuMoC.backend.trip.TripRepository;
|
||||
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
@@ -16,15 +17,16 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class RegularTripDetectionService {
|
||||
|
||||
RegularTripDetectionProperties properties;
|
||||
private final RegularTripDetectionProperties properties;
|
||||
|
||||
TripRepository tripRepository;
|
||||
private final TripRepository tripRepository;
|
||||
|
||||
TripMapper tripMapper;
|
||||
private final TripMapper tripMapper;
|
||||
|
||||
Detector tripDetector;
|
||||
private final Detector tripDetector;
|
||||
|
||||
/**
|
||||
* Detects regular trips for the current day of the week for all users based on saved trip data and RegularTripDetectionProperties.
|
||||
|
||||
@@ -4,6 +4,7 @@ import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||
import SuMoC.backend.routing.services.RoutingPreferencesService;
|
||||
import SuMoC.backend.routing.services.RoutingService;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -29,10 +30,19 @@ public class RoutingController {
|
||||
|
||||
private final RoutingPreferencesService routingPreferencesService;
|
||||
|
||||
private final CurrentUserService currentUserService;
|
||||
|
||||
@PostMapping("/request")
|
||||
@Schema(description = "Calculates alternative, sustainable routes for the request. The delta of departure and arrival in the requestdto is used as baseline to determine if alternatives are acceptable.")
|
||||
public ResponseEntity<List<RouteDTO>> requestAlternativeRoutes(@Valid @RequestBody RoutingAlternativeRequestDTO routingAlternativeRequestDTO) {
|
||||
try {
|
||||
|
||||
if (currentUserService.isAuthenticated()) {
|
||||
logger.info("Authenticaed user is making request: " + currentUserService.get().getEmail());
|
||||
} else {
|
||||
logger.info("Unauthenticated user is making request.");
|
||||
}
|
||||
|
||||
if (routingAlternativeRequestDTO.getRoutingPreferencesDTO() == null) {
|
||||
// This automatically uses default preferences for unauthenticated users
|
||||
routingAlternativeRequestDTO.setRoutingPreferencesDTO(routingPreferencesService.getRoutingPreferencesForCurrentUser());
|
||||
|
||||
@@ -28,9 +28,18 @@ public class DevTripSeeder implements CommandLineRunner {
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
// Iterate over all users and create 5 random trips for each of the last 5 weeks
|
||||
// Iterate over all users and create 5 random trips for each of the last 5 weeks + adds car trips for every day at same time
|
||||
userRepository.findAll().forEach(user -> {
|
||||
for (int week = 0; week < 5; week++) {
|
||||
for (int day = 0; day < 7; day++) {
|
||||
NewTripDTO carTrip = TripFactory.newCarTripDTO(
|
||||
java.time.Instant.now()
|
||||
.minus(java.time.Duration.ofDays(week * 7 + day))
|
||||
);
|
||||
tripService.addTrip(user, carTrip);
|
||||
}
|
||||
|
||||
// Create 5 trips per week
|
||||
for (int i = 0; i < 5; i++) {
|
||||
// Create trips within each week's time range
|
||||
long daysAgo = week * 7 + (long) (Math.random() * 7);
|
||||
|
||||
@@ -23,6 +23,33 @@ public class TripFactory {
|
||||
return modalities[ThreadLocalRandom.current().nextInt(modalities.length)];
|
||||
}
|
||||
|
||||
public static NewTripDTO newCarTripDTO(Instant startTime) {
|
||||
String startPlace = "Cologne";
|
||||
String endPlace = "Düsseldorf";
|
||||
|
||||
Set<NewTripSegmentDTO> segments = Set.of(
|
||||
NewTripSegmentDTO.builder()
|
||||
.modality(Modality.CAR)
|
||||
.startTime(startTime)
|
||||
.distanceMeters(50000)
|
||||
.build()
|
||||
);
|
||||
|
||||
return NewTripDTO.builder()
|
||||
.startPlace(startPlace)
|
||||
.endPlace(endPlace)
|
||||
.startLatitude(51.4617108)
|
||||
.startLongitude(7.0170745)
|
||||
.endLatitude(51.2277411)
|
||||
.endLongitude(6.7734556)
|
||||
.co2Emissions(120.0)
|
||||
.startTime(startTime)
|
||||
.endTime(startTime.plus(Duration.ofMinutes(45)))
|
||||
.mobilityScore(75.0f)
|
||||
.tripSegments(segments)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a random NewTripDTO that always consists of two random segments that start at the given startTime,
|
||||
* take 2 hours in total, and have random start and end places from a predefined list of NRW cities.
|
||||
|
||||
@@ -32,12 +32,15 @@ public interface TripRepository extends JpaRepository<Trip, Long> {
|
||||
DayOfWeekConverter converter = new DayOfWeekConverter();
|
||||
return findAllValidFromDateWithMainModalityOnCertainWeekdayInt(
|
||||
fromDate,
|
||||
modality,
|
||||
modality.toString(),
|
||||
converter.convertToDatabaseColumn(dayOfWeek)
|
||||
);
|
||||
}
|
||||
|
||||
@Query("SELECT t FROM Trip t WHERE t.invalidated = false AND t.startTime >= :fromDate AND t.mainModality = :modality AND FUNCTION('day_of_week', t.startTime) = :dayOfWeek")
|
||||
List<Trip> findAllValidFromDateWithMainModalityOnCertainWeekdayInt(Instant fromDate, Modality modality, int dayOfWeek);
|
||||
@Query(
|
||||
value = "SELECT * FROM trips t WHERE t.invalidated = false AND t.start_time >= :fromDate AND t.main_modality = :modality AND EXTRACT(DOW from t.start_time) = :dayOfWeek",
|
||||
nativeQuery = true
|
||||
)
|
||||
List<Trip> findAllValidFromDateWithMainModalityOnCertainWeekdayInt(Instant fromDate, String modality, int dayOfWeek);
|
||||
|
||||
}
|
||||
|
||||
@@ -6,13 +6,10 @@ import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import SuMoC.backend.user.service.FriendshipService;
|
||||
import SuMoC.backend.user.service.PrivacyService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
@@ -23,18 +20,13 @@ import java.util.concurrent.TimeUnit;
|
||||
public class FriendshipController {
|
||||
private final UserRepository userRepository;
|
||||
private final FriendshipService friendshipService;
|
||||
private final CurrentUserService currentUser;
|
||||
private final CurrentUserService currentUserService;
|
||||
|
||||
@Autowired
|
||||
public FriendshipController(UserRepository userRepository, FriendshipService friendshipService, CurrentUserService currentUser) {
|
||||
public FriendshipController(UserRepository userRepository, FriendshipService friendshipService, CurrentUserService currentUserService) {
|
||||
this.userRepository = userRepository;
|
||||
this.friendshipService = friendshipService;
|
||||
this.currentUser = currentUser;
|
||||
}
|
||||
|
||||
// TODO extend security context with user id to avoid unnecessary db query
|
||||
private User getAuthenticatedUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
return userRepository.findByEmail(authentication.getName()).get();
|
||||
this.currentUserService = currentUserService;
|
||||
}
|
||||
|
||||
@Operation(summary = "Return all friendships of the logged in user.",
|
||||
@@ -51,7 +43,7 @@ public class FriendshipController {
|
||||
""")
|
||||
@GetMapping("/all")
|
||||
public ResponseEntity<List<FriendshipDTO>> getFriendships() {
|
||||
User user = currentUser.get();
|
||||
User user = currentUserService.get();
|
||||
List<FriendshipDTO> friendships = friendshipService.getFriendships(user.getId());
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
|
||||
@@ -61,7 +53,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Return all accepted friends of the logged in user.", description = "Returns all friends with accepted status.")
|
||||
@GetMapping("/accepted")
|
||||
public ResponseEntity<List<FriendshipDTO>> getAcceptedFriendships() {
|
||||
User user = currentUser.get();
|
||||
User user = currentUserService.get();
|
||||
List<FriendshipDTO> friendships = friendshipService.getAcceptedFriendships(user.getId());
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
|
||||
@@ -71,7 +63,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Request a friendship with another user.", description = "Sends a friendship request to another user from the logged in user.")
|
||||
@PostMapping("/request/{friendId}")
|
||||
public ResponseEntity<Void> requestFriendship(@PathVariable Long friendId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUserService.get();
|
||||
checkSelfAction(user.getId(), friendId);
|
||||
friendshipService.requestFriendship(user, friendId);
|
||||
return ResponseEntity.ok().build();
|
||||
@@ -80,7 +72,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Request a friendship with another user by friend code.", description = "Sends a friendship request to another user identified by their friend code from the logged in user.")
|
||||
@PostMapping("/request/by-friendcode/{friendCode}")
|
||||
public ResponseEntity<Void> requestFriendshipByFriendcode(@PathVariable String friendCode) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUserService.get();
|
||||
User requestedFriend = userRepository.findByFriendCode(friendCode).orElseThrow();
|
||||
checkSelfAction(user.getId(), requestedFriend.getId());
|
||||
friendshipService.requestFriendship(user, requestedFriend.getId());
|
||||
@@ -90,7 +82,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Accept a friendship request.", description = "Accepts a pending friendship request for the logged in user from user with friendId.")
|
||||
@PostMapping("/accept/{friendId}")
|
||||
public ResponseEntity<Void> acceptFriendship(@PathVariable Long friendId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUserService.get();
|
||||
friendshipService.acceptFriendship(user, friendId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -98,7 +90,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Reject a friendship request.", description = "Rejects a pending friendship request for the logged in user from user with friendId.")
|
||||
@PostMapping("/reject/{friendId}")
|
||||
public ResponseEntity<Void> rejectFriendship(@PathVariable Long friendId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUserService.get();
|
||||
friendshipService.rejectFriendship(user, friendId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -106,7 +98,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Unfriend a user.", description = "Removes an accepted friendship between the logged in user and user with friendId.")
|
||||
@DeleteMapping("/unfriend/{friendId}")
|
||||
public ResponseEntity<Void> unfriend(@PathVariable Long friendId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUserService.get();
|
||||
friendshipService.unfriend(user, friendId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -114,7 +106,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Block a user.", description = "Blocks the user with friendId for the logged in user.")
|
||||
@PostMapping("/block/{friendId}")
|
||||
public ResponseEntity<Void> blockUser(@PathVariable Long friendId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUserService.get();
|
||||
checkSelfAction(user.getId(), friendId);
|
||||
friendshipService.blockUser(user, friendId);
|
||||
return ResponseEntity.ok().build();
|
||||
@@ -123,7 +115,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Unblock a user.", description = "Unblocks the user with friendId for the logged in user.")
|
||||
@PostMapping("/unblock/{friendId}")
|
||||
public ResponseEntity<Void> unblockUser(@PathVariable Long friendId) {
|
||||
User user = getAuthenticatedUser();
|
||||
User user = currentUserService.get();
|
||||
friendshipService.unblockUser(user, friendId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -131,7 +123,7 @@ public class FriendshipController {
|
||||
@Operation(summary = "Get all users the logged in user has blocked.", description = "Returns a list of all users that have been blocked by the logged in user.")
|
||||
@GetMapping("/blocked")
|
||||
public ResponseEntity<List<MinimalUserDTO>> blockedUsers() {
|
||||
User user = currentUser.get();
|
||||
User user = currentUserService.get();
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
|
||||
.body(friendshipService.getBlockedUsers(user.getId()));
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package SuMoC.backend.user.dtos;
|
||||
|
||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@@ -11,6 +13,8 @@ import java.time.Instant;
|
||||
* The MinimalUserDTO of the friend represents the friend depending on the relationship.
|
||||
* So only if friendship is accepted the private name of the friend is used as displayname.
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
public class FriendshipDTO {
|
||||
private Long friendshipId;
|
||||
private Long userId;
|
||||
@@ -29,43 +33,4 @@ public class FriendshipDTO {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public Long getFriendshipId() {
|
||||
return friendshipId;
|
||||
}
|
||||
|
||||
public void setFriendshipId(Long friendshipId) {
|
||||
this.friendshipId = friendshipId;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public MinimalUserDTO getFriend() {
|
||||
return friend;
|
||||
}
|
||||
|
||||
public void setFriend(MinimalUserDTO friend) {
|
||||
this.friend = friend;
|
||||
}
|
||||
|
||||
public FriendShipStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(FriendShipStatus status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,10 +23,20 @@ public class MaximalUserDTO {
|
||||
private Set<Friendship> friendships;
|
||||
private String base64ProfilePicture;
|
||||
|
||||
public String getFriendCode() {
|
||||
return friendCode;
|
||||
}
|
||||
|
||||
public void setFriendCode(String friendCode) {
|
||||
this.friendCode = friendCode;
|
||||
}
|
||||
|
||||
private String friendCode;
|
||||
|
||||
public MaximalUserDTO() {
|
||||
}
|
||||
|
||||
public MaximalUserDTO(Long id, String publicName, String privateName, String email, VisibilityPrivacy visibilityPrivacy, Set<Trip> trips, Set<Friendship> friendships, String base64ProfilePicture) {
|
||||
public MaximalUserDTO(Long id, String publicName, String privateName, String email, VisibilityPrivacy visibilityPrivacy, Set<Trip> trips, Set<Friendship> friendships, String friendCode,String base64ProfilePicture) {
|
||||
this.id = id;
|
||||
this.publicName = publicName;
|
||||
this.privateName = privateName;
|
||||
@@ -35,6 +45,7 @@ public class MaximalUserDTO {
|
||||
this.trips = trips;
|
||||
this.friendships = friendships;
|
||||
this.base64ProfilePicture = base64ProfilePicture;
|
||||
this.friendCode = friendCode;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -9,14 +9,14 @@ public class UserDTO {
|
||||
private String privateName;
|
||||
private String publicName;
|
||||
private Set<RoleName> roles;
|
||||
private String friendCode;
|
||||
|
||||
|
||||
|
||||
public UserDTO(Long userId, String privateName, String publicName, Set<RoleName> roles){
|
||||
public UserDTO(Long userId, String privateName, String publicName, Set<RoleName> roles, String friendCode) {
|
||||
this.userId = userId;
|
||||
this.privateName = privateName;
|
||||
this.publicName = publicName;
|
||||
this.roles = roles;
|
||||
this.friendCode = friendCode;
|
||||
}
|
||||
|
||||
public UserDTO(){}
|
||||
@@ -57,4 +57,13 @@ public class UserDTO {
|
||||
public void setPublicName(String publicName) {
|
||||
this.publicName = publicName;
|
||||
}
|
||||
|
||||
public String getFriendCode() {
|
||||
return friendCode;
|
||||
}
|
||||
|
||||
public void setFriendCode(String friendCode) {
|
||||
this.friendCode = friendCode;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ public interface UserMapper {
|
||||
user.getVisibilityPrivacy(),
|
||||
user.getTrips(),
|
||||
user.getFriendships(),
|
||||
user.getFriendCode(),
|
||||
ImageBase64Util.encode(user.getProfileImage().getImageData())
|
||||
);
|
||||
return maximalUserDTO;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package SuMoC.backend.user.service;
|
||||
|
||||
import SuMoC.backend.notification.services.NotificationSchedulerService;
|
||||
import SuMoC.backend.user.dtos.FriendshipDTO;
|
||||
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||
@@ -8,25 +9,22 @@ import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.FriendshipRepository;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.jspecify.annotations.NonNull;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static SuMoC.backend.notification.enums.NotificationType.FRIENDSHIP_REQUEST_RECEIVED;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
@RequiredArgsConstructor
|
||||
public class FriendshipService {
|
||||
private final FriendshipRepository friendshipRepository;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
public FriendshipService(FriendshipRepository friendshipRepository, UserRepository userRepository) {
|
||||
this.friendshipRepository = friendshipRepository;
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
private final NotificationSchedulerService notificationSchedulerService;
|
||||
|
||||
private static @NonNull MinimalUserDTO getMinimalUserDTOforFriend(Friendship friendship) {
|
||||
User friend = friendship.getFriend();
|
||||
@@ -156,6 +154,36 @@ public class FriendshipService {
|
||||
Friendship reverseFriendship = new Friendship(requestedFriend, sender, FriendShipStatus.PENDING);
|
||||
friendshipRepository.save(friendship);
|
||||
friendshipRepository.save(reverseFriendship);
|
||||
|
||||
// Send notification to requestedFriend about new friendship request
|
||||
notifyAboutFriendshipRequest(reverseFriendship, sender, requestedFriend);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts pending friendship into a dto and schedules a notification to the requested friend.
|
||||
* This method should be called with the reverse friendship, so that the client receives the friendshipDto
|
||||
* with a MinimalUserDTO of the sender.
|
||||
*/
|
||||
public void notifyAboutFriendshipRequest(Friendship requestFriendship, User sender, User requestedFriend) {
|
||||
MinimalUserDTO senderMinimalUserDTO = new MinimalUserDTO(
|
||||
sender.getId(),
|
||||
sender.getPrivateName()
|
||||
);
|
||||
|
||||
FriendshipDTO friendshipDTO = new FriendshipDTO(
|
||||
requestFriendship.getId(),
|
||||
requestedFriend.getId(),
|
||||
senderMinimalUserDTO,
|
||||
requestFriendship.getStatus(),
|
||||
requestFriendship.getCreatedAt()
|
||||
);
|
||||
|
||||
notificationSchedulerService.schedule(
|
||||
requestedFriend.getId(),
|
||||
friendshipDTO,
|
||||
FRIENDSHIP_REQUEST_RECEIVED,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
public void acceptFriendship(User sender, long friendId) {
|
||||
@@ -272,14 +300,6 @@ 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<>();
|
||||
|
||||
@@ -323,4 +343,11 @@ public class FriendshipService {
|
||||
|
||||
return friends;
|
||||
}
|
||||
|
||||
public record NameWithFriendship(
|
||||
Long id,
|
||||
String name,
|
||||
boolean friendship
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +67,8 @@ public class UserTestFactory {
|
||||
user.getId(),
|
||||
user.getPrivateName(),
|
||||
user.getPublicName(),
|
||||
user.getRoles()
|
||||
user.getRoles(),
|
||||
user.getFriendCode()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package SuMoC.backend.common.converter;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class DayOfWeekConverterTest {
|
||||
private final DayOfWeekConverter converter = new DayOfWeekConverter();
|
||||
|
||||
@Test
|
||||
void testConvertToDatabaseColumn() {
|
||||
assertEquals(1, converter.convertToDatabaseColumn(DayOfWeek.MONDAY));
|
||||
assertEquals(2, converter.convertToDatabaseColumn(DayOfWeek.TUESDAY));
|
||||
assertEquals(3, converter.convertToDatabaseColumn(DayOfWeek.WEDNESDAY));
|
||||
assertEquals(4, converter.convertToDatabaseColumn(DayOfWeek.THURSDAY));
|
||||
assertEquals(5, converter.convertToDatabaseColumn(DayOfWeek.FRIDAY));
|
||||
assertEquals(6, converter.convertToDatabaseColumn(DayOfWeek.SATURDAY));
|
||||
assertEquals(0, converter.convertToDatabaseColumn(DayOfWeek.SUNDAY));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConvertToEntityAttribute() {
|
||||
assertEquals(DayOfWeek.MONDAY, converter.convertToEntityAttribute(1));
|
||||
assertEquals(DayOfWeek.TUESDAY, converter.convertToEntityAttribute(2));
|
||||
assertEquals(DayOfWeek.WEDNESDAY, converter.convertToEntityAttribute(3));
|
||||
assertEquals(DayOfWeek.THURSDAY, converter.convertToEntityAttribute(4));
|
||||
assertEquals(DayOfWeek.FRIDAY, converter.convertToEntityAttribute(5));
|
||||
assertEquals(DayOfWeek.SATURDAY, converter.convertToEntityAttribute(6));
|
||||
assertEquals(DayOfWeek.SUNDAY, converter.convertToEntityAttribute(0));
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package SuMoC.backend.trip;
|
||||
|
||||
import SuMoC.backend.Factories.TripTestFactory;
|
||||
import SuMoC.backend.Factories.UserTestFactory;
|
||||
import SuMoC.backend.common.converter.DayOfWeekConverter;
|
||||
import SuMoC.backend.trip.models.Trip;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@DataJpaTest
|
||||
@TestPropertySource(properties = {
|
||||
"spring.jpa.hibernate.ddl-auto=create-drop",
|
||||
"spring.datasource.url=jdbc:h2:mem:testdb"
|
||||
})
|
||||
public class TripRepositoryTest {
|
||||
|
||||
@Autowired
|
||||
private TripRepository tripRepository;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Test
|
||||
void testDayOfWeekConverterAppliedInQuery() {
|
||||
// Create a user
|
||||
User user = UserTestFactory.validUser();
|
||||
userRepository.save(user);
|
||||
|
||||
// Create trips on different days of the week
|
||||
// 2025-01-13 is a Monday
|
||||
Trip mondayTrip = TripTestFactory.getValidTrip(Instant.parse("2025-01-13T10:00:00Z"), Instant.parse("2025-01-13T11:00:00Z"), user);
|
||||
tripRepository.save(mondayTrip);
|
||||
|
||||
// 2025-01-19 is a Sunday
|
||||
Trip sundayTrip = TripTestFactory.getValidTrip(Instant.parse("2025-01-19T10:00:00Z"), Instant.parse("2025-01-19T11:00:00Z"), user);
|
||||
tripRepository.save(sundayTrip);
|
||||
|
||||
// Query for trips on Monday
|
||||
List<Trip> mondayTrips = tripRepository.findAllValidFromDateWithMainModalityOnCertainWeekday(
|
||||
Instant.parse("2025-01-01T00:00:00Z"),
|
||||
Modality.CAR,
|
||||
DayOfWeek.MONDAY
|
||||
);
|
||||
|
||||
// Verify only Monday trip is returned
|
||||
assertEquals(1, mondayTrips.size());
|
||||
assertEquals(mondayTrip.getId(), mondayTrips.get(0).getId());
|
||||
|
||||
// Query for trips on Sunday
|
||||
List<Trip> sundayTrips = tripRepository.findAllValidFromDateWithMainModalityOnCertainWeekday(
|
||||
Instant.parse("2025-01-01T00:00:00Z"),
|
||||
Modality.CAR,
|
||||
DayOfWeek.SUNDAY
|
||||
);
|
||||
|
||||
// Verify only Tuesday trip is returned
|
||||
assertEquals(1, sundayTrips.size());
|
||||
assertEquals(sundayTrip.getId(), sundayTrips.get(0).getId());
|
||||
}
|
||||
}
|
||||
@@ -5,18 +5,15 @@ import SuMoC.backend.user.models.Friendship;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
||||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
|
||||
@DataJpaTest
|
||||
@ActiveProfiles("test")
|
||||
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
|
||||
@SpringBootTest
|
||||
@Profile("test")
|
||||
public class FriendshipRepositoryTests {
|
||||
@Autowired
|
||||
private FriendshipRepository friendshipRepository;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package SuMoC.backend.user.service;
|
||||
|
||||
import SuMoC.backend.notification.services.NotificationSchedulerService;
|
||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||
import SuMoC.backend.user.models.Friendship;
|
||||
import SuMoC.backend.user.models.User;
|
||||
@@ -20,6 +21,7 @@ import java.util.Optional;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@@ -31,6 +33,9 @@ public class FriendshipServiceTest {
|
||||
@Mock
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Mock
|
||||
private NotificationSchedulerService notificationSchedulerService;
|
||||
|
||||
@InjectMocks
|
||||
private FriendshipService friendshipService;
|
||||
|
||||
@@ -69,6 +74,21 @@ public class FriendshipServiceTest {
|
||||
// Verify one friendship: friend -> sender, PENDING
|
||||
assertTrue(capturedFriendships.stream()
|
||||
.anyMatch(f -> f.getUser().equals(friend) && f.getFriend().equals(sender) && f.getStatus().equals(FriendShipStatus.PENDING)));
|
||||
|
||||
// Verify notificationSchedulerService.schedule called with correct params
|
||||
verify(notificationSchedulerService, times(1)).schedule(
|
||||
eq(friend.getId()),
|
||||
argThat(arg -> {
|
||||
// Check FriendshipDTO fields
|
||||
if (!(arg instanceof SuMoC.backend.user.dtos.FriendshipDTO dto)) return false;
|
||||
return dto.getUserId().equals(friend.getId()) &&
|
||||
dto.getFriend().getId().equals(sender.getId()) &&
|
||||
dto.getFriend().getDisplayName().equals(sender.getPrivateName()) &&
|
||||
dto.getStatus() == FriendShipStatus.PENDING;
|
||||
}),
|
||||
eq(SuMoC.backend.notification.enums.NotificationType.FRIENDSHIP_REQUEST_RECEIVED),
|
||||
isNull()
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in New Issue
Block a user