295 lines
14 KiB
Java
295 lines
14 KiB
Java
package SuMoC.backend.dev;
|
|
|
|
import SuMoC.backend.firebase.FirebaseMessageBuilder;
|
|
import SuMoC.backend.h3.H3Service;
|
|
import SuMoC.backend.meteo.ForecastService;
|
|
import SuMoC.backend.meteo.MeteoClient;
|
|
import SuMoC.backend.notification.enums.NotificationStatus;
|
|
import SuMoC.backend.notification.enums.NotificationType;
|
|
import SuMoC.backend.notification.models.Notification;
|
|
import SuMoC.backend.notification.repositories.NotificationRepository;
|
|
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
|
import SuMoC.backend.routing.dtos.RouteDTO;
|
|
import SuMoC.backend.scheduling.ScheduledTasks;
|
|
import SuMoC.backend.suggestion.services.RegularTripSuggestionService;
|
|
import SuMoC.backend.trend.dto.TrendDetectionDTO;
|
|
import SuMoC.backend.trend.services.StatTableUpdateService;
|
|
import SuMoC.backend.user.dtos.FriendshipDTO;
|
|
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
|
import SuMoC.backend.user.enums.FriendShipStatus;
|
|
import SuMoC.backend.user.mapper.UserMapper;
|
|
import SuMoC.backend.user.models.User;
|
|
import SuMoC.backend.user.repository.UserRepository;
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import com.google.firebase.messaging.FirebaseMessaging;
|
|
import com.google.firebase.messaging.Message;
|
|
import io.swagger.v3.oas.annotations.Operation;
|
|
import jakarta.validation.constraints.NotNull;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.context.annotation.Profile;
|
|
import org.springframework.http.ResponseEntity;
|
|
import org.springframework.web.bind.annotation.*;
|
|
|
|
import java.time.Duration;
|
|
import java.time.Instant;
|
|
import java.time.LocalDate;
|
|
import java.time.LocalTime;
|
|
import java.util.HashMap;
|
|
import java.util.List;
|
|
|
|
@RestController
|
|
@RequestMapping("/dev")
|
|
@Profile("dev")
|
|
public class DevController {
|
|
|
|
private final ScheduledTasks scheduledTasks;
|
|
private final StatTableUpdateService statTableUpdateService;
|
|
private final FirebaseMessaging firebaseMessaging;
|
|
private final MeteoClient meteoClient;
|
|
private final ForecastService forecastService;
|
|
private final FirebaseMessageBuilder firebaseMessageBuilder;
|
|
private final ObjectMapper objectMapper;
|
|
private final NotificationRepository notificationRepository;
|
|
private final UserRepository userRepository;
|
|
private final UserMapper userMapper;
|
|
private final H3Service h3Service;
|
|
private final RegularTripSuggestionService regularTripSuggestionService;
|
|
|
|
public DevController(
|
|
ScheduledTasks scheduledTasks,
|
|
StatTableUpdateService statTableUpdateService,
|
|
@Autowired(required = false) FirebaseMessaging firebaseMessaging,
|
|
MeteoClient meteoClient,
|
|
ForecastService forecastService,
|
|
FirebaseMessageBuilder firebaseMessageBuilder,
|
|
ObjectMapper objectMapper,
|
|
NotificationRepository notificationRepository, UserRepository userRepository, UserMapper userMapper, H3Service h3Service, RegularTripSuggestionService regularTripSuggestionService
|
|
) {
|
|
this.scheduledTasks = scheduledTasks;
|
|
this.statTableUpdateService = statTableUpdateService;
|
|
this.firebaseMessaging = firebaseMessaging;
|
|
this.meteoClient = meteoClient;
|
|
this.forecastService = forecastService;
|
|
this.firebaseMessageBuilder = firebaseMessageBuilder;
|
|
this.objectMapper = objectMapper;
|
|
this.notificationRepository = notificationRepository;
|
|
this.userRepository = userRepository;
|
|
this.userMapper = userMapper;
|
|
this.h3Service = h3Service;
|
|
this.regularTripSuggestionService = regularTripSuggestionService;
|
|
}
|
|
|
|
@PostMapping("/trigger-trend-calculation")
|
|
public void triggerTrendCalculation() {
|
|
LocalDate dayOfLastWeek = LocalDate.now().minusDays(7);
|
|
LocalDate day2WeeksAgo = LocalDate.now().minusDays(14);
|
|
LocalDate day3WeeksAgo = LocalDate.now().minusDays(21);
|
|
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(dayOfLastWeek);
|
|
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day2WeeksAgo);
|
|
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day3WeeksAgo);
|
|
}
|
|
|
|
@GetMapping("/test-firebase-trend-notification/{fcm_token}")
|
|
@Operation(description = "Immediately sends a test notification of type TREND to the provided FCM token.")
|
|
public ResponseEntity<String> SendTestTrendNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
|
|
if (firebaseMessaging == null) {
|
|
return ResponseEntity.status(503)
|
|
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
|
}
|
|
try {
|
|
Notification notification = new Notification();
|
|
notification.setType(NotificationType.TREND);
|
|
notification.setData(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO()));
|
|
|
|
Message mockTrendMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
|
|
|
|
// Send to a topic (no device registration needed)
|
|
String message = firebaseMessaging.sendAsync(
|
|
mockTrendMessage
|
|
).get();
|
|
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
|
|
} catch (Exception e) {
|
|
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
|
}
|
|
}
|
|
|
|
@GetMapping("/test-firebase-adhoc-route-notification/{fcm_token}")
|
|
@Operation(description = "Immediately sends a test notification of type ADHOC_ALTERNATIVE to the provided FCM token.")
|
|
public ResponseEntity<String> SendTestAdhocRouteNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
|
|
if (firebaseMessaging == null) {
|
|
return ResponseEntity.status(503)
|
|
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
|
}
|
|
try {
|
|
Notification notification = new Notification();
|
|
notification.setType(NotificationType.ADHOC_ALTERNATIVE);
|
|
List<RouteDTO> mockRoutes = List.of(RouteDTO.getMockRouteDTO(), RouteDTO.getMockRouteDTO());
|
|
notification.setData(objectMapper.writeValueAsString(mockRoutes));
|
|
|
|
Message mockAdhocMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
|
|
|
|
// Send to a topic (no device registration needed)
|
|
String message = firebaseMessaging.sendAsync(
|
|
mockAdhocMessage
|
|
).get();
|
|
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
|
|
} catch (Exception e) {
|
|
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
|
}
|
|
}
|
|
|
|
@GetMapping("/test-firebase-regular-trip-notification/{fcm_token}")
|
|
@Operation(description = "Immediately sends a test notification of type REGULAR_TRIP_ALTERNATIVE to the provided FCM token.")
|
|
public ResponseEntity<String> SendTestRegularTripAlternativeNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
|
|
if (firebaseMessaging == null) {
|
|
return ResponseEntity.status(503)
|
|
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
|
}
|
|
try {
|
|
Notification notification = new Notification();
|
|
notification.setType(NotificationType.REGULAR_TRIP_ALTERNATIVE);
|
|
RouteDTO mockRoute = RouteDTO.getMockRouteDTO();
|
|
notification.setData(objectMapper.writeValueAsString(mockRoute));
|
|
Message mockRegularTripMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
|
|
// Send to a topic (no device registration needed)
|
|
String message = firebaseMessaging.sendAsync(
|
|
mockRegularTripMessage
|
|
).get();
|
|
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
|
|
} catch (Exception e) {
|
|
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
|
}
|
|
}
|
|
|
|
@GetMapping("/test-firebase-friendship-request-notification/{fcm_token}")
|
|
@Operation(description = "Immediately sends a test notification of type FRIENDSHIP_REQUEST_RECEIVED to the provided FCM token.")
|
|
public ResponseEntity<String> SendTestRFriendshipRequestReceivedNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
|
|
if (firebaseMessaging == null) {
|
|
return ResponseEntity.status(503)
|
|
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
|
}
|
|
try {
|
|
Notification notification = new Notification();
|
|
notification.setType(NotificationType.FRIENDSHIP_REQUEST_RECEIVED);
|
|
FriendshipDTO friendshipDTO = new FriendshipDTO(
|
|
1L,
|
|
2L,
|
|
new MinimalUserDTO(
|
|
2L,
|
|
"request_public_name"
|
|
),
|
|
FriendShipStatus.PENDING,
|
|
Instant.now()
|
|
);
|
|
notification.setData(objectMapper.writeValueAsString(friendshipDTO));
|
|
Message mockRegularTripMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
|
|
String message = firebaseMessaging.sendAsync(
|
|
mockRegularTripMessage
|
|
).get();
|
|
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
|
|
} catch (Exception e) {
|
|
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
|
}
|
|
}
|
|
|
|
@GetMapping("/test-notification-from-detected-regular-trip")
|
|
@Operation(description = "Testing endpoint that mocks the detection of regular trips and then tests the alternative calculation and notification scheduling.")
|
|
public ResponseEntity<String> testNotificationFromDetectedRegularTrip() {
|
|
if (firebaseMessaging == null) {
|
|
return ResponseEntity.status(503)
|
|
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
|
}
|
|
try {
|
|
// we seed user 1 and 2 in the dev data loader
|
|
HashMap<Long, List<DetectedRegularTripDTO>> detectedRegularTripsByUser = new HashMap<>();
|
|
List<DetectedRegularTripDTO> list1 = List.of(
|
|
DetectedRegularTripDTO.getTriggeringMock(h3Service, 1L)
|
|
);
|
|
List<DetectedRegularTripDTO> list2 = List.of(
|
|
DetectedRegularTripDTO.getTriggeringMock(h3Service, 2L)
|
|
);
|
|
detectedRegularTripsByUser.put(1L, list1);
|
|
detectedRegularTripsByUser.put(2L, list2);
|
|
|
|
regularTripSuggestionService.checkAlternativesAndNotify(detectedRegularTripsByUser);
|
|
return ResponseEntity.ok("✓ Test notifications from detected regular trips processed.");
|
|
|
|
|
|
} catch (Exception e) {
|
|
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
|
}
|
|
}
|
|
|
|
@Operation(description = "Immediately queues a notification to the fcm key specified in application-dev.properties to be processed by the notification queue.")
|
|
@GetMapping("/queue-test-notification")
|
|
public ResponseEntity<String> queueTestNotification() {
|
|
if (firebaseMessaging == null) {
|
|
return ResponseEntity.status(503)
|
|
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
|
}
|
|
try {
|
|
User user = userRepository.findByEmail("user1@email.com").orElseThrow();
|
|
|
|
TrendDetectionDTO mockDTO = TrendDetectionDTO.mockTrendDetectionDTO();
|
|
mockDTO.setUserId(user.getId());
|
|
|
|
Notification notification = Notification.builder()
|
|
.type(NotificationType.TREND)
|
|
.data(objectMapper.writeValueAsString(mockDTO))
|
|
.user(user)
|
|
.earliestTimeOfDayToSend(LocalTime.now())
|
|
.createdAt(Instant.now())
|
|
.status(NotificationStatus.PENDING)
|
|
.build();
|
|
|
|
notificationRepository.save(notification);
|
|
|
|
return ResponseEntity.ok("✓ Test notification queued.");
|
|
} catch (Exception e) {
|
|
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
|
}
|
|
}
|
|
|
|
@Operation(description = "Tests the method cleaning old notifications from the database.")
|
|
@GetMapping("/test-clean-old-notifications")
|
|
public void testCleanOldNotifications() throws JsonProcessingException, InterruptedException {
|
|
User user = userRepository.findByEmail("user1@email.com").orElseThrow();
|
|
|
|
Notification notification = Notification.builder()
|
|
.type(NotificationType.TREND)
|
|
.data(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO()))
|
|
.user(user)
|
|
.earliestTimeOfDayToSend(LocalTime.now())
|
|
.createdAt(Instant.now().minus(Duration.ofDays(60)))
|
|
.status(NotificationStatus.SENT)
|
|
.build();
|
|
|
|
notificationRepository.save(notification);
|
|
|
|
Thread.sleep(5000);
|
|
|
|
scheduledTasks.scheduleCleanUpOldNotifications();
|
|
}
|
|
|
|
@GetMapping("/test-meteo")
|
|
public void testMeteoClient() {
|
|
try {
|
|
// Test with Zurich coordinates
|
|
double lat = 51.44378662109375;
|
|
double lon = 7.007565975189209;
|
|
|
|
var forecast = forecastService.getTodayYesterdayForecast(
|
|
lat,
|
|
lon);
|
|
} catch (Exception e) {
|
|
}
|
|
}
|
|
|
|
@PostMapping("/test-detection-and-notification-regular-trips")
|
|
public void testDetectionAndNotificationOfRegularTrips() {
|
|
regularTripSuggestionService.detectAndNotifyRegularTripsForTodaysDayOfWeek();
|
|
}
|
|
|
|
}
|