From c368594d60c99df350e16c284f45593e629e1b63 Mon Sep 17 00:00:00 2001 From: Minjoo-kang123 Date: Mon, 8 Jul 2024 15:46:08 +0900 Subject: [PATCH] add mission push --- .../service/ChallengeRecordService.java | 38 +++++++++++++++-- .../dailyRank/service/DailyRankService.java | 35 ++++++++++++---- .../service/PushNotificationService.java | 2 +- .../api/group/repository/GroupRepository.java | 4 +- .../repository/GroupMemberRepository.java | 2 + .../challenge/CalculateDailyRanksConfig.java | 41 +++++++++++++++++++ .../challenge/CalculateDailyRanksTasklet.java | 21 ++++++++++ .../hana/common/scheduler/BatchScheduler.java | 17 +++++--- 8 files changed, 140 insertions(+), 20 deletions(-) create mode 100644 src/main/java/com/hana/common/job/challenge/CalculateDailyRanksConfig.java create mode 100644 src/main/java/com/hana/common/job/challenge/CalculateDailyRanksTasklet.java diff --git a/src/main/java/com/hana/api/challenge/service/ChallengeRecordService.java b/src/main/java/com/hana/api/challenge/service/ChallengeRecordService.java index df477ce..e0e6134 100644 --- a/src/main/java/com/hana/api/challenge/service/ChallengeRecordService.java +++ b/src/main/java/com/hana/api/challenge/service/ChallengeRecordService.java @@ -3,12 +3,19 @@ import com.hana.api.card.entity.Card; import com.hana.api.challenge.entity.ChallengeRecord; import com.hana.api.challenge.repository.ChallengRecordRepository; +import com.hana.api.firebase.service.PushNotificationService; +import com.hana.api.group.entity.Group; +import com.hana.api.group.repository.GroupRepository; +import com.hana.api.groupMember.entity.GroupMember; +import com.hana.api.groupMember.repository.GroupMemberRepository; +import com.hana.api.user.entity.User; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDate; +import java.util.List; @Service @RequiredArgsConstructor @@ -16,13 +23,38 @@ public class ChallengeRecordService { final ChallengRecordRepository challengRecordRepository; + final GroupRepository groupRepository; + final GroupMemberRepository groupMemberRepository; + final PushNotificationService pushNotificationService; @Transactional - public void insertDailyChallengeRecord() { + public int insertDailyChallengeRecord() { LocalDate today = LocalDate.now(); int randomNumber = (int) (Math.random() * 3); ChallengeRecord challengeRecord = ChallengeRecord.builder() - .challengeDate(today.plusDays(1)) - .challengeType(randomNumber).build(); + .challengeDate(today.plusDays(1)) + .challengeType(randomNumber).build(); challengRecordRepository.save(challengeRecord); + String challenge = ""; + switch (randomNumber){ + case 0: + challenge = "Walking"; + break; + case 1: + challenge = "Wake up At Morning"; + break; + case 2: + challenge = "Quiz Time"; + break; + } + List groups = groupRepository.findActiveGroup(LocalDate.now()); + for(Group g : groups){ + log.info(g.toString()); + List groupMembers = groupMemberRepository.findGroupMemberByGroupId(g.getId()); + for(GroupMember gm : groupMembers){ + String deviceId = gm.getUser().getDeviceId(); + pushNotificationService.sendNotificationToDevice(deviceId, "Check your Chellenge", challenge); + } + } + return randomNumber; } } diff --git a/src/main/java/com/hana/api/dailyRank/service/DailyRankService.java b/src/main/java/com/hana/api/dailyRank/service/DailyRankService.java index 2ad99b5..b1b4405 100644 --- a/src/main/java/com/hana/api/dailyRank/service/DailyRankService.java +++ b/src/main/java/com/hana/api/dailyRank/service/DailyRankService.java @@ -38,16 +38,35 @@ public class DailyRankService { private final ChallengeRecordRepository challengeRecordRepository; @Transactional - public void calculateDailyRanks(Long groupId) { - List users = groupRepository.findUsersByGroupId(groupId); + public void calculateDailyRanks() { LocalDate now = LocalDate.now(); + ChallengeRecord challengeRecord = challengeRecordRepository.findByChallengeDate(now); + int challenge = challengeRecord.getChallengeType(); + List groupIds = groupRepository.findAllGroupIds(now); + switch (challenge){ + case 0: + // 걷기 순위 계산 + for (Long groupId : groupIds) { + List users = groupRepository.findUsersByGroupId(groupId); + calculateWalkingRanks(groupId, now, users); + } + break; + + case 1: + // 기상 순위 계산 + for (Long groupId : groupIds) { + List users = groupRepository.findUsersByGroupId(groupId); + calculateWakeupRanks(groupId, now, users); + } + break; - // 걷기 순위 계산 - calculateWalkingRanks(groupId, now, users); - // 기상 순위 계산 - calculateWakeupRanks(groupId, now, users); - // 퀴즈 순위 계산 - calculateQuizRanks(groupId, now, users); + case 2: + // 퀴즈 순위 계산 + for (Long groupId : groupIds) { + List users = groupRepository.findUsersByGroupId(groupId); + calculateQuizRanks(groupId, now, users); + } + } } private void calculateWalkingRanks(Long groupId, LocalDate now, List users) { diff --git a/src/main/java/com/hana/api/firebase/service/PushNotificationService.java b/src/main/java/com/hana/api/firebase/service/PushNotificationService.java index 96056ce..50b31c8 100644 --- a/src/main/java/com/hana/api/firebase/service/PushNotificationService.java +++ b/src/main/java/com/hana/api/firebase/service/PushNotificationService.java @@ -14,7 +14,7 @@ public void sendNotificationToDevice(String token, String title, String message) private void sendPushNotification(String token, String title, String message) { RestTemplate restTemplate = new RestTemplate(); - String payload = String.format("{\"to\":\"%s\",\"sound\":\"default\",\"title\":\"%s\",\"body\":\"%s\"}", "ExponentPushToken[-FSFxvP0NsUarmmpNqcOlm]", "Dofarming", "message"); + String payload = String.format("{\"to\":\"%s\",\"sound\":\"default\",\"title\":\"%s\",\"body\":\"%s\"}", token, title, message); restTemplate.postForEntity(EXPO_PUSH_URL, payload, String.class); } } \ No newline at end of file diff --git a/src/main/java/com/hana/api/group/repository/GroupRepository.java b/src/main/java/com/hana/api/group/repository/GroupRepository.java index ba3eebb..cb3b5ec 100644 --- a/src/main/java/com/hana/api/group/repository/GroupRepository.java +++ b/src/main/java/com/hana/api/group/repository/GroupRepository.java @@ -15,8 +15,8 @@ public interface GroupRepository extends JpaRepository { @Query("SELECT gm.user FROM group_member gm WHERE gm.group.id = :groupId") List findUsersByGroupId(@Param("groupId") Long groupId); - @Query("SELECT g.id FROM group g") - List findAllGroupIds(); + @Query(value = "SELECT group_table.id from group_table where ?1 between group_table.started_at and group_table.ended_at", nativeQuery = true) + List findAllGroupIds(LocalDate now); @Query(value = "SELECT * from group_table where ?1 between group_table.started_at and group_table.ended_at", nativeQuery = true) List findActiveGroup(LocalDate tomorrow); diff --git a/src/main/java/com/hana/api/groupMember/repository/GroupMemberRepository.java b/src/main/java/com/hana/api/groupMember/repository/GroupMemberRepository.java index a901917..4ee742f 100644 --- a/src/main/java/com/hana/api/groupMember/repository/GroupMemberRepository.java +++ b/src/main/java/com/hana/api/groupMember/repository/GroupMemberRepository.java @@ -27,4 +27,6 @@ public interface GroupMemberRepository extends JpaRepository @Query("SELECT gm.user FROM group_member gm WHERE gm.group.id = :groupId") List findUsersByGroupId(Long groupId); + + List findGroupMemberByGroupId(Long groupId); } diff --git a/src/main/java/com/hana/common/job/challenge/CalculateDailyRanksConfig.java b/src/main/java/com/hana/common/job/challenge/CalculateDailyRanksConfig.java new file mode 100644 index 0000000..5f3a7e7 --- /dev/null +++ b/src/main/java/com/hana/common/job/challenge/CalculateDailyRanksConfig.java @@ -0,0 +1,41 @@ +package com.hana.common.job.challenge; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.Step; +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.batch.core.configuration.annotation.JobScope; +import org.springframework.batch.core.configuration.support.DefaultBatchConfiguration; +import org.springframework.batch.core.job.builder.JobBuilder; +import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.step.builder.StepBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; + +@Configuration +@RequiredArgsConstructor +@EnableBatchProcessing +@Slf4j +public class CalculateDailyRanksConfig extends DefaultBatchConfiguration { + + private final JobRepository jobRepository; + private final PlatformTransactionManager transactionManager; + private final CalculateDailyRanksTasklet calculateDailyRanksTasklet; + + @Bean + public Job calculateDailyRanksJob() { + return new JobBuilder("calculateDailyRanksJob", jobRepository) + .start(calculateDailyRanksStep()) + .build(); + } + + @Bean + @JobScope + public Step calculateDailyRanksStep() { + return new StepBuilder("calculateDailyRanksStep", jobRepository) + .tasklet(calculateDailyRanksTasklet, transactionManager) + .build(); + } +} diff --git a/src/main/java/com/hana/common/job/challenge/CalculateDailyRanksTasklet.java b/src/main/java/com/hana/common/job/challenge/CalculateDailyRanksTasklet.java new file mode 100644 index 0000000..afce7ab --- /dev/null +++ b/src/main/java/com/hana/common/job/challenge/CalculateDailyRanksTasklet.java @@ -0,0 +1,21 @@ +package com.hana.common.job.challenge; + + +import com.hana.api.dailyRank.service.DailyRankService; +import lombok.RequiredArgsConstructor; +import org.springframework.batch.core.StepContribution; +import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.repeat.RepeatStatus; +import org.springframework.stereotype.Component; + +@RequiredArgsConstructor +@Component +public class CalculateDailyRanksTasklet implements Tasklet { + final DailyRankService dailyRankService; + @Override + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + dailyRankService.calculateDailyRanks(); + return RepeatStatus.FINISHED; + } +} diff --git a/src/main/java/com/hana/common/scheduler/BatchScheduler.java b/src/main/java/com/hana/common/scheduler/BatchScheduler.java index 5fa99f9..afbdac3 100644 --- a/src/main/java/com/hana/common/scheduler/BatchScheduler.java +++ b/src/main/java/com/hana/common/scheduler/BatchScheduler.java @@ -88,7 +88,7 @@ public void runUpdateCardListDataJob() { } } - @Scheduled(cron = "0 0 12 * * ?") // 매일 정오에 실행 + @Scheduled(cron = "00 00 12 * * ?") // 매일 정오에 실행 //@Scheduled(fixedRate = 30000) public void insertDailyChallenge() { try { @@ -103,17 +103,22 @@ public void insertDailyChallenge() { } // 일일 랭킹 계산 - @Scheduled(cron = "0 42 13 * * ?") // 매일 오후 11시 50분에 실행 + @Scheduled(cron = "30 25 16 * * ?") // 매일 오후 11시 50분에 실행 public void calculateDailyRanks() { // 모든 그룹의 ID를 조회 - List groupIds = groupRepository.findAllGroupIds(); - for (Long groupId : groupIds) { - dailyRankService.calculateDailyRanks(groupId); + try { + Job job = jobRegistry.getJob("calculateDailyRanksJob"); + JobParametersBuilder jobParam = new JobParametersBuilder() + .addLocalDateTime("runAt", LocalDateTime.now()); + jobLauncher.run(job, jobParam.toJobParameters()); + } catch (NoSuchJobException | JobInstanceAlreadyCompleteException | JobExecutionAlreadyRunningException | + JobParametersInvalidException | JobRestartException e) { + throw new RuntimeException(e); } } //WeeklyRate 매주 일요일 밤 11시 55분에 실행 - @Scheduled(cron = "40 39 13 ? * THU") // 매일 정오에 실행 + @Scheduled(cron = "45 33 14 * * ?") // 매일 정오에 실행 public void insertWeeklyRate() { try { Job job = jobRegistry.getJob("insertWeeklyRateJob");