implemented scheduled tasks and notification scheduler so that whole chain task -> detected trends -> scheduled notification -> notification sent by worker is working
This commit is contained in:
@@ -10,6 +10,7 @@ import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||
import SuMoC.backend.scheduling.ScheduledTasks;
|
||||
import SuMoC.backend.trend.dto.TrendDetectionDTO;
|
||||
import SuMoC.backend.trend.services.StatTableUpdateService;
|
||||
import SuMoC.backend.user.mapper.UserMapper;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
@@ -41,6 +42,7 @@ public class DevController {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final NotificationRepository notificationRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final UserMapper userMapper;
|
||||
|
||||
public DevController(
|
||||
ScheduledTasks scheduledTasks,
|
||||
@@ -50,7 +52,7 @@ public class DevController {
|
||||
ForecastService forecastService,
|
||||
FirebaseMessageBuilder firebaseMessageBuilder,
|
||||
ObjectMapper objectMapper,
|
||||
NotificationRepository notificationRepository, UserRepository userRepository
|
||||
NotificationRepository notificationRepository, UserRepository userRepository, UserMapper userMapper
|
||||
) {
|
||||
this.scheduledTasks = scheduledTasks;
|
||||
this.statTableUpdateService = statTableUpdateService;
|
||||
@@ -61,6 +63,7 @@ public class DevController {
|
||||
this.objectMapper = objectMapper;
|
||||
this.notificationRepository = notificationRepository;
|
||||
this.userRepository = userRepository;
|
||||
this.userMapper = userMapper;
|
||||
}
|
||||
|
||||
@PostMapping("/trigger-trend-calculation")
|
||||
@@ -107,9 +110,12 @@ public class DevController {
|
||||
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(TrendDetectionDTO.mockTrendDetectionDTO()))
|
||||
.data(objectMapper.writeValueAsString(mockDTO))
|
||||
.user(user)
|
||||
.earliestTimeOfDayToSend(LocalTime.now())
|
||||
.createdAt(LocalDateTime.now())
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
package SuMoC.backend.notification.factories;
|
||||
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.trend.dto.TrendDetectionDTO;
|
||||
import SuMoC.backend.trend.services.TrendMessageGenerator;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class TrendNotificationFactory {
|
||||
|
||||
private final TrendMessageGenerator trendMessageGenerator;
|
||||
|
||||
public Notification createNotification(TrendDetectionDTO trend) {
|
||||
return Notification.builder()
|
||||
.user(trend.getUser())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package SuMoC.backend.notification.interfaces;
|
||||
|
||||
public interface NotificationPublisher {
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package SuMoC.backend.notification.interfaces;
|
||||
|
||||
public interface NotificationSender {
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package SuMoC.backend.notification.interfaces;
|
||||
|
||||
public interface Notifieable {
|
||||
Long getUserId();
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
import SuMoC.backend.notification.enums.NotificationStatus;
|
||||
import SuMoC.backend.notification.enums.NotificationType;
|
||||
import SuMoC.backend.notification.interfaces.Notifieable;
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationSchedulerService {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private final NotificationRepository notificationRepository;
|
||||
|
||||
private final EntityManager entityManager;
|
||||
|
||||
public void scheduleAll(List<Notifieable> dataBodies,
|
||||
NotificationType notificationType,
|
||||
LocalTime earliestTimeOfDayToSend
|
||||
) {
|
||||
List<Notification> notifications = dataBodies.stream().map(dataBody -> {
|
||||
String dataBodyJson;
|
||||
try {
|
||||
dataBodyJson = objectMapper.writeValueAsString(dataBody);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize notification data body", e);
|
||||
}
|
||||
|
||||
User userProxy = entityManager.getReference(User.class, dataBody.getUserId());
|
||||
|
||||
return Notification.builder()
|
||||
.user(userProxy)
|
||||
.type(notificationType)
|
||||
.data(dataBodyJson)
|
||||
.earliestTimeOfDayToSend(earliestTimeOfDayToSend)
|
||||
.status(NotificationStatus.PENDING)
|
||||
.createdAt(LocalDateTime.now())
|
||||
.failedSendAttempts(0)
|
||||
.build();
|
||||
}).toList();
|
||||
|
||||
notificationRepository.saveAll(notifications);
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
import SuMoC.backend.notification.factories.TrendNotificationFactory;
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||
import SuMoC.backend.trend.dto.TrendDetectionDTO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class TrendNotificationService {
|
||||
|
||||
private final NotificationRepository notificationRepository;
|
||||
|
||||
private final TrendNotificationFactory trendNotificationFactory;
|
||||
|
||||
public List<Notification> generateTrendNotifications(List<TrendDetectionDTO> trendList) {
|
||||
List<Notification> notificationList = trendList.stream().map(trendNotificationFactory::createNotification).toList();
|
||||
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package SuMoC.backend.scheduling;
|
||||
|
||||
import SuMoC.backend.notification.services.NotificationWorker;
|
||||
import SuMoC.backend.trend.services.StatTableUpdateService;
|
||||
import SuMoC.backend.trend.services.TrendNotificationService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -20,18 +21,20 @@ public class ScheduledTasks {
|
||||
|
||||
private final StatTableUpdateService statTableUpdateService;
|
||||
|
||||
private final TrendNotificationService trendNotificationService;
|
||||
|
||||
private final NotificationWorker notificationWorker;
|
||||
|
||||
/**
|
||||
* Calculate weekly mobility stats for all users and generate corresponding notifications.
|
||||
*/
|
||||
@Scheduled(cron = "#{@schedulingProperties.calculateWeeklyMobilityStats}")
|
||||
public void scheduleCalculateWeeklyMobilityStats() {
|
||||
@Scheduled(cron = "#{@schedulingProperties.notifyWeeklyMobilityStats}")
|
||||
public void scheduleNotifyWeeklyMobilityStats() {
|
||||
logger.info("Scheduled task triggered: calculateWeeklyMobilityStatsForAllUsers");
|
||||
try {
|
||||
LocalDate dayOfLastWeek = LocalDate.now().minusDays(7);
|
||||
LocalDate dayOfLastWeek = LocalDate.now().minusWeeks(1);
|
||||
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(dayOfLastWeek);
|
||||
// TODO generate and queue notifications about new stats being available
|
||||
trendNotificationService.detectAndNotifyTrends(dayOfLastWeek.getYear(), dayOfLastWeek.get(java.time.temporal.IsoFields.WEEK_OF_WEEK_BASED_YEAR));
|
||||
} catch (Exception e) {
|
||||
logger.error("Error calculating weekly mobility stats.", e);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import org.springframework.stereotype.Component;
|
||||
@Setter
|
||||
public class SchedulingProperties {
|
||||
private int poolSize = 5;
|
||||
private String calculateWeeklyMobilityStats = "1 30 0 * * 1"; // Once per week
|
||||
private String notifyWeeklyMobilityStats = "1 30 0 * * 1"; // Once per week
|
||||
private String runNotificationWorker = "0 * * * * *"; // Every minute
|
||||
private String cleanUpOldNotifications = "0 0 3 * * *"; // Daily at 3 AM
|
||||
}
|
||||
|
||||
+10
-2
@@ -4,10 +4,12 @@ import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalTime;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "trenddetection")
|
||||
public class TrendDetectionProperties {
|
||||
@ConfigurationProperties(prefix = "trend")
|
||||
public class TrendProperties {
|
||||
|
||||
/**
|
||||
* Minimum percentage change to detect a positive trend (e.g., 25.0 for 25%)
|
||||
@@ -18,4 +20,10 @@ public class TrendDetectionProperties {
|
||||
* Minimum percentage change to detect a negative trend (e.g., -25.0 for -25%)
|
||||
*/
|
||||
private double negativeThreshold = -25.0;
|
||||
|
||||
/**
|
||||
* Time of day from which on trend notifications might be sent.
|
||||
* Useful since we dont want to inform about trend changes in the middle of night when calculating jobs might run.
|
||||
*/
|
||||
private LocalTime earliestTrendNotificationTimeOfDay = LocalTime.of(12, 0);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package SuMoC.backend.trend.dto;
|
||||
|
||||
import SuMoC.backend.notification.interfaces.Notifieable;
|
||||
import SuMoC.backend.trend.enums.*;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -9,8 +9,8 @@ import lombok.Data;
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
public class TrendDetectionDTO {
|
||||
private User user;
|
||||
public class TrendDetectionDTO implements Notifieable {
|
||||
private Long userId;
|
||||
private TrendTimespan timespan;
|
||||
private TrendType type;
|
||||
private StatAttribute attribute;
|
||||
@@ -19,7 +19,7 @@ public class TrendDetectionDTO {
|
||||
|
||||
public static TrendDetectionDTO mockTrendDetectionDTO() {
|
||||
return TrendDetectionDTO.builder()
|
||||
.user(null) // Replace with a mock User if needed
|
||||
.userId(null) // Replace with a mock User if needed
|
||||
.timespan(TrendTimespan.WEEKLY)
|
||||
.type(TrendType.INCREASING)
|
||||
.attribute(StatAttribute.CAR_DISTANCE)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package SuMoC.backend.trend.services;
|
||||
|
||||
import SuMoC.backend.trend.WeeklyMobilityStatsRepository;
|
||||
import SuMoC.backend.trend.config.TrendDetectionProperties;
|
||||
import SuMoC.backend.trend.config.TrendProperties;
|
||||
import SuMoC.backend.trend.dto.TrendDetectionDTO;
|
||||
import SuMoC.backend.trend.enums.DeltaType;
|
||||
import SuMoC.backend.trend.enums.StatAttribute;
|
||||
@@ -22,7 +22,7 @@ public class TrendDetectorService {
|
||||
|
||||
private final WeeklyMobilityStatsRepository weeklyMobilityStatsRepository;
|
||||
|
||||
private final TrendDetectionProperties trendDetectionProperties;
|
||||
private final TrendProperties trendProperties;
|
||||
|
||||
public List<TrendDetectionDTO> detectWeeklyTrends(Integer year, Integer weekNumber, StatAttribute attribute) {
|
||||
// Fetch stats for current and previous week
|
||||
@@ -56,18 +56,18 @@ public class TrendDetectorService {
|
||||
if (previousValue != 0) {
|
||||
double percentageChange = ((currentValue - previousValue) / previousValue) * 100.0;
|
||||
|
||||
if (percentageChange >= trendDetectionProperties.getPositiveThreshold()) {
|
||||
if (percentageChange >= trendProperties.getPositiveThreshold()) {
|
||||
detectedTrends.add(new TrendDetectionDTO(
|
||||
currentStats.getUser(),
|
||||
currentStats.getUser().getId(),
|
||||
TrendTimespan.WEEKLY,
|
||||
TrendType.INCREASING,
|
||||
StatAttribute.CAR_DISTANCE,
|
||||
DeltaType.PERCENTAGE,
|
||||
percentageChange
|
||||
));
|
||||
} else if (percentageChange <= trendDetectionProperties.getNegativeThreshold()) {
|
||||
} else if (percentageChange <= trendProperties.getNegativeThreshold()) {
|
||||
detectedTrends.add(new TrendDetectionDTO(
|
||||
previousStats.getUser(),
|
||||
previousStats.getUser().getId(),
|
||||
TrendTimespan.WEEKLY,
|
||||
TrendType.DECREASING,
|
||||
StatAttribute.CAR_DISTANCE,
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package SuMoC.backend.trend.services;
|
||||
|
||||
import SuMoC.backend.notification.enums.NotificationType;
|
||||
import SuMoC.backend.notification.services.NotificationSchedulerService;
|
||||
import SuMoC.backend.trend.config.TrendProperties;
|
||||
import SuMoC.backend.trend.enums.StatAttribute;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class TrendNotificationService {
|
||||
|
||||
private final TrendDetectorService trendDetectorService;
|
||||
|
||||
private final NotificationSchedulerService notificationSchedulerService;
|
||||
|
||||
private final TrendProperties trendProperties;
|
||||
|
||||
/**
|
||||
* Detects trends for the given year and week number and sends notifications to users.
|
||||
*/
|
||||
public void detectAndNotifyTrends(int year, int weekNumber) {
|
||||
// TODO for now we only consider CAR_DISTANCE, but this can be extended later
|
||||
var detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE);
|
||||
// we create a new list so the java type system is happy
|
||||
notificationSchedulerService.scheduleAll(new ArrayList<>(detectedTrends), NotificationType.TREND, trendProperties.getEarliestTrendNotificationTimeOfDay());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user