diff --git a/src/main/java/ru/ulstu/paper/service/DeadlineScheduler.java b/src/main/java/ru/ulstu/paper/service/DeadlineScheduler.java index da1f2bf..0388f2e 100644 --- a/src/main/java/ru/ulstu/paper/service/DeadlineScheduler.java +++ b/src/main/java/ru/ulstu/paper/service/DeadlineScheduler.java @@ -4,28 +4,26 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +import ru.ulstu.core.util.DateUtils; import ru.ulstu.paper.model.Paper; -import ru.ulstu.paper.repository.PaperRepository; import ru.ulstu.user.model.User; -import ru.ulstu.user.scheduler.UserScheduler; import ru.ulstu.user.service.MailService; -import java.util.Calendar; -import java.util.List; +import java.util.Date; @Service public class DeadlineScheduler { + private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true; + private final static int DAYS_TO_DEADLINE_NOTIFICATION = 7; private final Logger log = LoggerFactory.getLogger(DeadlineScheduler.class); - private final PaperRepository paperRepository; + private final PaperService paperService; private final MailService mailService; - private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true; - - public DeadlineScheduler(PaperRepository paperRepository, MailService mailService) { - this.paperRepository = paperRepository; + public DeadlineScheduler(PaperService paperService, MailService mailService) { + this.paperService = paperService; this.mailService = mailService; } @@ -45,21 +43,25 @@ public class DeadlineScheduler { } private void sendNotifications(boolean isDeadlineBeforeWeek) { - List allPapers = paperRepository.findAll(); - for (Paper paper : allPapers) { - Calendar c = Calendar.getInstance(); - c.add(Calendar.DAY_OF_YEAR, 7); - if (((c.getTime().compareTo(paper.getDeadlineDate()) < 0) && isDeadlineBeforeWeek) || - (c.getTime().compareTo(paper.getDeadlineDate()) >= 0) && !isDeadlineBeforeWeek) { - sendMessageDeadline(paper); - } - } + Date now = DateUtils.addDays(new Date(), DAYS_TO_DEADLINE_NOTIFICATION); + paperService + .findAll() + .stream() + .filter(paper -> needToSendDeadlineNotification(paper, now, isDeadlineBeforeWeek)) + .map(paper -> sendMessageDeadline(paper)); } - private void sendMessageDeadline(Paper paper){ + private boolean needToSendDeadlineNotification(Paper paper, Date compareDate, boolean isDeadlineBeforeWeek) { + return paper.getDeadlineDate() != null + && (compareDate.before(paper.getDeadlineDate()) && isDeadlineBeforeWeek + || compareDate.after(paper.getDeadlineDate()) && !isDeadlineBeforeWeek); + } + + private Paper sendMessageDeadline(Paper paper) { for (User user : paper.getAuthors()) { mailService.sendEmail(user.getEmail(), "Приближается срок сдачи статьи", "Срок сдачи статьи " + paper.getTitle() + " " + paper.getDeadlineDate().toString()); } + return paper; } }