|
| 1 | +package com.loopers.batch.job.ranking.writer; |
| 2 | + |
| 3 | +import com.loopers.batch.domain.ranking.WeeklyRanking; |
| 4 | +import com.loopers.batch.domain.ranking.WeeklyRankingRepository; |
| 5 | +import lombok.RequiredArgsConstructor; |
| 6 | +import lombok.extern.slf4j.Slf4j; |
| 7 | +import org.springframework.batch.core.configuration.annotation.StepScope; |
| 8 | +import org.springframework.batch.item.Chunk; |
| 9 | +import org.springframework.batch.item.ItemWriter; |
| 10 | +import org.springframework.beans.factory.annotation.Value; |
| 11 | +import org.springframework.stereotype.Component; |
| 12 | +import org.springframework.transaction.annotation.Transactional; |
| 13 | + |
| 14 | +import java.time.DayOfWeek; |
| 15 | +import java.time.LocalDate; |
| 16 | +import java.time.format.DateTimeFormatter; |
| 17 | + |
| 18 | +@Slf4j |
| 19 | +@StepScope |
| 20 | +@Component |
| 21 | +@RequiredArgsConstructor |
| 22 | +public class WeeklyRankingWriter implements ItemWriter<WeeklyRanking> { |
| 23 | + |
| 24 | + private final WeeklyRankingRepository weeklyRankingRepository; |
| 25 | + |
| 26 | + @Value("#{jobParameters['startDate']}") |
| 27 | + private String startDateStr; |
| 28 | + |
| 29 | + @Value("#{jobParameters['endDate']}") |
| 30 | + private String endDateStr; |
| 31 | + |
| 32 | + private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd"); |
| 33 | + |
| 34 | + private boolean deletedExisting = false; |
| 35 | + |
| 36 | + @Override |
| 37 | + @Transactional |
| 38 | + public void write(Chunk<? extends WeeklyRanking> chunk) { |
| 39 | + if (!deletedExisting) { |
| 40 | + LocalDate weekStart = parseStartDate(); |
| 41 | + LocalDate weekEnd = parseEndDate(); |
| 42 | + |
| 43 | + log.info("기존 주간 랭킹 삭제: weekStart={}, weekEnd={}", weekStart, weekEnd); |
| 44 | + weeklyRankingRepository.deleteByWeekStartAndWeekEnd(weekStart, weekEnd); |
| 45 | + deletedExisting = true; |
| 46 | + } |
| 47 | + |
| 48 | + log.info("주간 랭킹 저장: count={}", chunk.size()); |
| 49 | + weeklyRankingRepository.saveAll(chunk.getItems().stream().map(item -> (WeeklyRanking) item).toList()); |
| 50 | + } |
| 51 | + |
| 52 | + private LocalDate parseStartDate() { |
| 53 | + if (startDateStr != null && !startDateStr.isBlank()) { |
| 54 | + return LocalDate.parse(startDateStr, DATE_FORMATTER); |
| 55 | + } |
| 56 | + return LocalDate.now().with(DayOfWeek.MONDAY); |
| 57 | + } |
| 58 | + |
| 59 | + private LocalDate parseEndDate() { |
| 60 | + if (endDateStr != null && !endDateStr.isBlank()) { |
| 61 | + return LocalDate.parse(endDateStr, DATE_FORMATTER); |
| 62 | + } |
| 63 | + return LocalDate.now().with(DayOfWeek.SUNDAY); |
| 64 | + } |
| 65 | +} |
0 commit comments