Skip to content

Commit

Permalink
Merge pull request #80 from Team-Umbba/feat/#67-demoday_test
Browse files Browse the repository at this point in the history
[FEAT] 데모데이 시연을 위한 테스트용 API
  • Loading branch information
ddongseop authored Jul 21, 2023
2 parents 3702322 + 68a3e15 commit 76b0516
Show file tree
Hide file tree
Showing 8 changed files with 136 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ public ApiResponse<GetMainViewResponseDto> home(Principal principal) {
}

@GetMapping("/home/case")
@ResponseStatus(HttpStatus.OK)
public ApiResponse<GetInvitationResponseDto> invitation(Principal principal) {

return ApiResponse.success(SuccessType.GET_INVITE_CODE_SUCCESS, qnAService.getInvitation(JwtProvider.getUserFromPrincial(principal)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@

import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.*;

import javax.validation.constraints.NotBlank;

@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class TodayAnswerRequestDto {

@NotBlank // null, "", " "을 모두 허용하지 X
String answer;

public static TodayAnswerRequestDto of (String answer) {
return new TodayAnswerRequestDto(answer);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
import sopt.org.umbbaServer.global.exception.CustomException;
import sopt.org.umbbaServer.global.exception.ErrorType;
import sopt.org.umbbaServer.global.util.fcm.FCMService;
import sopt.org.umbbaServer.global.util.fcm.controller.dto.FCMPushRequestDto;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
Expand Down Expand Up @@ -283,6 +285,7 @@ else if (childList.get(3) != YES || parentList.get(3) != YES) {
}
}


/*
리팩토링을 위해 아래로 뺀 메서드들 끝
*/
Expand All @@ -294,7 +297,8 @@ public GetMainViewResponseDto getMainInfo(Long userId) {

List<QnA> qnaList = getQnAListByParentchild(parentchild);

QnA lastQna = qnaList.get(parentchild.getCount() - 1);
QnA lastQna = qnaList.get(parentchild.getCount()-1);
log.info("getCount(): {}", parentchild.getCount());

return GetMainViewResponseDto.of(lastQna, parentchild.getCount());
}
Expand All @@ -321,4 +325,51 @@ private GetInvitationResponseDto invitation(Long userId) {
private GetInvitationResponseDto withdrawUser() {
return GetInvitationResponseDto.of(false);
}


/**
* 데모데이 테스트용 메서드
*/
@Transactional
public void updateDemoList(Long userId) {

User myUser = getUserById(userId);
Parentchild parentchild = getParentchildByUser(myUser);

for (int i=0; i<4; i++) {
updateDay(parentchild,
"우리 부모님은 어렸을 때부터 행복하고 좋은 기억을 많이 주셨고, 정말 행복하게 자랐어. 그 덕에 지금까지 행복하고 안정된 느낌을 받아.",
"오구 내 똥강아지~ 어렸을 때는 매일 볼 수 있었는데, 어른이 되고 나서 자주 못봐서 너무 아쉽다... 연락 잘하거라 요녀석~");
}
QnA fifthQnA = getTodayQnAByParentchild(parentchild);
log.info("💖💖💖💖Day 5 QnA: {}", fifthQnA.getId());
fcmService.multipleSendByToken(FCMPushRequestDto.sendTodayQna(
fifthQnA.getQuestion().getSection().getValue(),
fifthQnA.getQuestion().getTopic()), parentchild.getId());

}

@Transactional
public void todayUpdate(Long userId) {

User myUser = getUserById(userId);
Parentchild parentchild = getParentchildByUser(myUser);

updateDay(parentchild,
"우리 부모님은 어렸을 때부터 행복하고 좋은 기억을 많이 주셨고, 정말 행복하게 자랐어. 그 덕에 지금까지 행복하고 안정된 느낌을 받아.",
"오구 내 똥강아지~ 어렸을 때는 매일 볼 수 있었는데, 어른이 되고 나서 자주 못봐서 너무 아쉽다... 연락 잘하거라 요녀석~");

QnA todayQnA = getTodayQnAByParentchild(parentchild);
fcmService.multipleSendByToken(FCMPushRequestDto.sendTodayQna(
todayQnA.getQuestion().getSection().getValue(),
todayQnA.getQuestion().getTopic()), parentchild.getId());
}

private void updateDay(Parentchild parentchild, String childAnswer, String parentAnswer) {
QnA currentQnA = getTodayQnAByParentchild(parentchild);
log.info("💖💖💖💖Current QnA: {}", currentQnA.getId());
currentQnA.saveChildAnswer(childAnswer);
currentQnA.saveParentAnswer(parentAnswer);
parentchild.addCount();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package sopt.org.umbbaServer.global.common;

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import sopt.org.umbbaServer.domain.qna.service.QnAService;
import sopt.org.umbbaServer.global.common.dto.ApiResponse;
import sopt.org.umbbaServer.global.exception.SuccessType;

@RestController
@RequiredArgsConstructor
public class DemoController {

private final QnAService qnAService;

/**
* 데모데이 테스트용 QnA리스트 세팅 API
* - API 호출 시 4일차까지 일일문답을 완료했고, 5일차 답변을 할 차례로 만들기
* - 5일차로 변경되는 시점에서 푸시메시지 전송
* - 4일차까지의 is**Answer, **Answer 필드가 채워진 상태
*
* - 최대한 User 테이블만 보고 테스트할 수 있도록 설계
*/
@PatchMapping("/demo/list/{userId}")
@ResponseStatus(HttpStatus.OK)
public ApiResponse demoList(@PathVariable final Long userId) {

qnAService.updateDemoList(userId);
return ApiResponse.success(SuccessType.TEST_SUCCESS);
}


/**
* 데모데이 테스트용 QnA 세팅 API
* - API 호출할 때마다 일수가 증가하며 새로운 질문으로 업데이트
* - 오늘의 질문 알림 푸시 함께 전송
*
*/
@PatchMapping("/demo/qna/{userId}")
@ResponseStatus(HttpStatus.OK)
public ApiResponse demoQnA(@PathVariable final Long userId) {

qnAService.todayUpdate(userId);
return ApiResponse.success(SuccessType.TEST_SUCCESS);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ public class SecurityConfig {
"/qna/**", "onboard/**", "/home", "/dummy",
// "/log-out",
"/test", "/profile", "/health", "/actuator/health",
"/alarm/qna", "/alarm/drink"
"/alarm/qna", "/alarm/drink",
"/demo/**"
};

@Bean
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package sopt.org.umbbaServer.global.exception;

import com.google.api.Http;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
Expand All @@ -24,6 +25,7 @@ public enum SuccessType {
GET_INVITE_CODE_SUCCESS(HttpStatus.OK, "초대장을 보낼 코드 조회에 성공했습니다."),
PUSH_ALARM_SUCCESS(HttpStatus.OK, "푸시알림 전송에 성공했습니다."),
PUSH_ALARM_PERIODIC_SUCCESS(HttpStatus.OK, "오늘의 질문 푸시알림 활성에 성공했습니다."),
TEST_SUCCESS(HttpStatus.OK, "데모데이 테스트용 API 호출에 성공했습니다."),


/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,49 @@
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import sopt.org.umbbaServer.domain.parentchild.dao.ParentchildDao;
import sopt.org.umbbaServer.domain.parentchild.repository.ParentchildRepository;
import sopt.org.umbbaServer.domain.user.model.User;
import sopt.org.umbbaServer.domain.user.repository.UserRepository;
import sopt.org.umbbaServer.domain.user.social.SocialPlatform;
import sopt.org.umbbaServer.global.util.fcm.controller.dto.FCMPushRequestDto;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class FCMScheduler {

private final ParentchildRepository parentchildRepository;
private final UserRepository userRepository;
private final ParentchildDao parentchildDao;
private final FCMService fcmService;

@Scheduled(cron = "0 0 0 * * ?", zone = "Asia/Seoul") // 초기값
public String pushTodayQna() {

log.info("오늘의 질문 알람 - 유저마다 보내는 시간 다름");
// List<String> tokenList = parentchildDao.findFcmTokensById(parentchildId);


parentchildRepository.findAll().stream()
.forEach(pc -> {
.filter(pc -> {
List<String> tokenList = parentchildDao.findFcmTokensById(pc.getId());
List<User> parentChildUsers = userRepository.findUserByParentChild(pc);
return tokenList != null &&
tokenList.size() == 2 &&
parentChildUsers.stream()
.allMatch(user -> user.validateParentchild(parentChildUsers) && !user.getSocialPlatform().equals(SocialPlatform.WITHDRAW));
})
.forEach(pc -> {
log.info(pc.getId() + "번째 Parentchild");
String cronExpression = String.format("0 %s %s * * ?", pc.getPushTime().getMinute(), pc.getPushTime().getHour());
// String cronExpression = String.format("*/10 * * * * *");
// String cronExpression = String.format("0 %s %s * * ?", pc.getPushTime().getMinute(), pc.getPushTime().getHour());
String cronExpression = String.format("*/20 * * * * *");
log.info("cron: {}", cronExpression);
fcmService.schedulePushAlarm(cronExpression, pc.getId());
});
})
;
return "Today QnA messages were sent successfully";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,9 @@ public String multipleSendByToken(FCMPushRequestDto request, Long parentchildId)

List<String> tokenList = parentchildDao.findFcmTokensById(parentchildId);

log.info("tokenList: {}🌈, {}🌈",tokenList.get(0), tokenList.get(1));


MulticastMessage message = MulticastMessage.builder()
.setNotification(Notification.builder()
.setTitle(request.getTitle())
Expand Down

0 comments on commit 76b0516

Please sign in to comment.