Untitled

mail@pastecode.io avatar
unknown
plain_text
9 days ago
1.7 kB
2
Indexable
Never
@Component
@EnableScheduling
public class TrainingRaportGenerator {

    // ... (Constructor and dependencies)

    @Scheduled(fixedDelay = 5000)
    public void generateTrainingRaport() {
        List<Training> trainingList = trainingProvider.getAllTrainings();

        // Find unique users and store them in a list
        List<User> uniqueUsers = trainingList.stream()
                                           .map(Training::getUser)
                                           .distinct()
                                           .collect(Collectors.toList());

        // Iterate over unique users
        for (User user : uniqueUsers) {
            // Filter trainings for the current user
            List<Training> userTrainings = trainingList.stream()
                                                      .filter(t -> t.getUser().equals(user))
                                                      .collect(Collectors.toList());

            int numberOfTrainings = userTrainings.size();
            String activityType = numberOfTrainings > 0 ? userTrainings.get(0).getActivityType().name() : "No activity";

            String result = user.getFirstName() + " " + user.getLastName() + "\n" +
                            "Your weekly dose of trainings: " + numberOfTrainings + "\n" +
                            "Your last activity was: " + activityType + "\n";

            EmailDto email = new EmailDto(user.getEmail(), "Weekly report", result);

            try {
                emailSender.send(email);
            } catch (Exception e) {
                System.err.println("Error sending email to " + user.getEmail());
            }
        }
    }
}
Leave a Comment