Skip to content

Commit

Permalink
Merge pull request #85 from Do-Farming/feat/minjoo/addPush/#82
Browse files Browse the repository at this point in the history
feat : push add at daily mission insert
  • Loading branch information
Minjoo-kang123 authored Jul 8, 2024
2 parents a407820 + c368594 commit e98b87c
Show file tree
Hide file tree
Showing 8 changed files with 140 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,58 @@
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
@Slf4j
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<Group> groups = groupRepository.findActiveGroup(LocalDate.now());
for(Group g : groups){
log.info(g.toString());
List<GroupMember> groupMembers = groupMemberRepository.findGroupMemberByGroupId(g.getId());
for(GroupMember gm : groupMembers){
String deviceId = gm.getUser().getDeviceId();
pushNotificationService.sendNotificationToDevice(deviceId, "Check your Chellenge", challenge);
}
}
return randomNumber;
}
}
35 changes: 27 additions & 8 deletions src/main/java/com/hana/api/dailyRank/service/DailyRankService.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,35 @@ public class DailyRankService {
private final ChallengeRecordRepository challengeRecordRepository;

@Transactional
public void calculateDailyRanks(Long groupId) {
List<User> users = groupRepository.findUsersByGroupId(groupId);
public void calculateDailyRanks() {
LocalDate now = LocalDate.now();
ChallengeRecord challengeRecord = challengeRecordRepository.findByChallengeDate(now);
int challenge = challengeRecord.getChallengeType();
List<Long> groupIds = groupRepository.findAllGroupIds(now);
switch (challenge){
case 0:
// 걷기 순위 계산
for (Long groupId : groupIds) {
List<User> users = groupRepository.findUsersByGroupId(groupId);
calculateWalkingRanks(groupId, now, users);
}
break;

case 1:
// 기상 순위 계산
for (Long groupId : groupIds) {
List<User> 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<User> users = groupRepository.findUsersByGroupId(groupId);
calculateQuizRanks(groupId, now, users);
}
}
}

private void calculateWalkingRanks(Long groupId, LocalDate now, List<User> users) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ public interface GroupRepository extends JpaRepository<Group, Long> {
@Query("SELECT gm.user FROM group_member gm WHERE gm.group.id = :groupId")
List<User> findUsersByGroupId(@Param("groupId") Long groupId);

@Query("SELECT g.id FROM group g")
List<Long> 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<Long> findAllGroupIds(LocalDate now);

@Query(value = "SELECT * from group_table where ?1 between group_table.started_at and group_table.ended_at", nativeQuery = true)
List<Group> findActiveGroup(LocalDate tomorrow);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,6 @@ public interface GroupMemberRepository extends JpaRepository<GroupMember, Long>

@Query("SELECT gm.user FROM group_member gm WHERE gm.group.id = :groupId")
List<User> findUsersByGroupId(Long groupId);

List<GroupMember> findGroupMemberByGroupId(Long groupId);
}
Original file line number Diff line number Diff line change
@@ -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();
}
}
Original file line number Diff line number Diff line change
@@ -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;
}
}
17 changes: 11 additions & 6 deletions src/main/java/com/hana/common/scheduler/BatchScheduler.java
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public void runUpdateCardListDataJob() {
}
}

@Scheduled(cron = "0 0 12 * * ?") // 매일 정오에 실행
@Scheduled(cron = "00 00 12 * * ?") // 매일 정오에 실행
//@Scheduled(fixedRate = 30000)
public void insertDailyChallenge() {
try {
Expand All @@ -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<Long> 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");
Expand Down

0 comments on commit e98b87c

Please sign in to comment.