|
| 1 | +package com.otchi.application; |
| 2 | + |
| 3 | +import com.otchi.application.utils.Clock; |
| 4 | +import com.otchi.domain.kitchen.Chef; |
| 5 | +import com.otchi.domain.kitchen.Recipe; |
| 6 | +import com.otchi.domain.kitchen.TodayRecipe; |
| 7 | +import com.otchi.domain.kitchen.TodayRecipeRepository; |
| 8 | +import com.otchi.domain.social.models.Post; |
| 9 | +import com.otchi.domain.social.repositories.PostRepository; |
| 10 | +import org.slf4j.Logger; |
| 11 | +import org.slf4j.LoggerFactory; |
| 12 | +import org.springframework.beans.factory.annotation.Autowired; |
| 13 | +import org.springframework.scheduling.annotation.Scheduled; |
| 14 | +import org.springframework.stereotype.Service; |
| 15 | + |
| 16 | +import java.time.LocalDate; |
| 17 | +import java.time.LocalDateTime; |
| 18 | +import java.util.Optional; |
| 19 | + |
| 20 | +import static java.util.Optional.of; |
| 21 | + |
| 22 | +@Service |
| 23 | +public class KitchenService { |
| 24 | + |
| 25 | + private final PostRepository postRepository; |
| 26 | + private final TodayRecipeRepository todayRecipeRepository; |
| 27 | + private Clock clock; |
| 28 | + private static final Logger log = LoggerFactory.getLogger(KitchenService.class); |
| 29 | + |
| 30 | + |
| 31 | + @Autowired |
| 32 | + public KitchenService(PostRepository postRepository, TodayRecipeRepository todayRecipeRepository, Clock clock) { |
| 33 | + this.postRepository = postRepository; |
| 34 | + this.todayRecipeRepository = todayRecipeRepository; |
| 35 | + this.clock = clock; |
| 36 | + } |
| 37 | + |
| 38 | + public Optional<TodayRecipe> getTodayRecipe() { |
| 39 | + LocalDateTime now = clock.now(); |
| 40 | + LocalDateTime yesterday = now.minusDays(1); |
| 41 | + Optional<Post> foundPost = postRepository.findFirstRecipePostMostLikedAfter(yesterday); |
| 42 | + return foundPost.flatMap( |
| 43 | + post -> { |
| 44 | + Recipe recipe = (Recipe) post.getPostContent(); |
| 45 | + TodayRecipe todayRecipe = new TodayRecipe(post.getId(), post.images().get(0), recipe.getTitle(), new Chef(post.getAuthor())); |
| 46 | + return of(todayRecipe); |
| 47 | + } |
| 48 | + ); |
| 49 | + } |
| 50 | + |
| 51 | + @Scheduled(cron = "00 00 * * * *") |
| 52 | + public void updateTodayRecipeAtMidNight() { |
| 53 | + Optional<TodayRecipe> todayRecipe = getTodayRecipe(); |
| 54 | + todayRecipe.ifPresent(todayRecipeRepository::save); |
| 55 | + log.info("Update the today recipe - {}", LocalDate.now()); |
| 56 | + } |
| 57 | +} |
0 commit comments