Skip to content

Commit

Permalink
♻️refactor : 알림 로직 변경 & 레코드 적용
Browse files Browse the repository at this point in the history
  • Loading branch information
DDonghyeo committed Jun 18, 2024
1 parent 10a11f4 commit 110cb35
Show file tree
Hide file tree
Showing 6 changed files with 104 additions and 27 deletions.
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package com.waither.notiservice.domain.redis;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;

import java.time.LocalDateTime;

@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
Expand All @@ -24,9 +23,19 @@ public class NotificationRecord {
//마지막 바람세기 알림 받은 시간
private LocalDateTime lastWindAlarmReceived;

//사용자 마지막 위치 (위도)
private Double lat;
//사용자 마지막 위치 (지역)
private String region;

public void setLastRainAlarmReceived(LocalDateTime lastRainAlarmReceived) {
this.lastRainAlarmReceived = lastRainAlarmReceived;
}

public void setLastWindAlarmReceived(LocalDateTime lastWindAlarmReceived) {
this.lastWindAlarmReceived = lastWindAlarmReceived;
}

public void setRegion(String region) {
this.region = region;
}

//사용자 마지막 위치 (경도)
private Double lon;
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,13 @@ public enum ErrorCode implements BaseErrorCode {
// 데이터 관련 에러
NO_USER_MEDIAN_REGISTERED(HttpStatus.NOT_FOUND, "USER404_0", "사용자 설정값이 존재하지 않습니다."),
NO_USER_DATA_REGISTERED(HttpStatus.NOT_FOUND, "USER404_1", "사용자 데이터 값이 존재하지 않습니다."),
FIREBASE_TOKEN_NOT_FOUND(HttpStatus.NOT_FOUND, "TOKEN404", "푸시알림 토큰이 존재하지 않습니다."),

//통신 과정 에러
COMMUNICATION_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON500_1", "통신 과정에서 문제가 발생했습니다.")
COMMUNICATION_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON500_1", "통신 과정에서 문제가 발생했습니다."),

//FirebaseError
FIREBASE_TOKEN_NOT_FOUND(HttpStatus.NOT_FOUND, "FB404", "푸시알림 토큰이 존재하지 않습니다."),
FIREBASE_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "FB500", "Firebase 메세지 전송 오류가 발생했습니다.")
;


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface UserDataRepository extends JpaRepository<UserData, String> {

Optional<UserData> findByEmail(String email);

List<UserData> findAllByClimateAlertIsTrue();

List<UserData> findAllByWindAlertIsTrue();

List<UserData> findAllBySnowAlertIsTrue();
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@
import org.springframework.data.repository.CrudRepository;

import javax.swing.text.html.Option;
import java.util.List;
import java.util.Optional;

public interface NotificationRecordRepository extends CrudRepository<NotificationRecord, String > {

Optional<NotificationRecord> findByEmail(String email);



}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.waither.notiservice.service;

import com.waither.notiservice.domain.redis.NotificationRecord;
import com.waither.notiservice.global.exception.CustomException;
import com.waither.notiservice.repository.redis.NotificationRecordRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

@RequiredArgsConstructor
@Service
public class NotificaitonRecordService {

private final NotificationRecordRepository notificationRecordRepository;

public void updateWindAlarm(String email) {
Optional<NotificationRecord> notificationRecord = notificationRecordRepository.findByEmail(email);

notificationRecord.ifPresentOrElse(record -> record.setLastWindAlarmReceived(LocalDateTime.now()), null);
}

public void updateRainAlarm(String email) {
Optional<NotificationRecord> notificationRecord = notificationRecordRepository.findByEmail(email);
notificationRecord.ifPresent(record -> record.setLastRainAlarmReceived(LocalDateTime.now()));
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.waither.notiservice.domain.UserData;
import com.waither.notiservice.domain.UserMedian;
import com.waither.notiservice.api.request.LocationDto;
import com.waither.notiservice.domain.redis.NotificationRecord;
import com.waither.notiservice.enums.Season;
import com.waither.notiservice.global.exception.CustomException;
import com.waither.notiservice.global.response.ErrorCode;
Expand All @@ -18,7 +19,9 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
Expand All @@ -30,6 +33,8 @@ public class NotificationService {
private final UserDataRepository userDataRepository;
private final NotificationRecordRepository notificationRecordRepository;

private final AlarmService alarmService;


@Transactional(readOnly = true)
public List<NotificationResponse> getNotifications(String email) {
Expand Down Expand Up @@ -58,14 +63,16 @@ public String sendGoOutAlarm(String email) {

Season currentSeason = TemperatureUtils.getCurrentSeason();

String finalMessage = "";
LocalDateTime now = LocalDateTime.now();
String title = now.getMonth() + "월 " + now.getDayOfMonth() + "일 날씨 정보입니다.";
StringBuilder sb = new StringBuilder();

/**
* 1. 기본 메세지 시작 형식
*/
//TODO : 날씨 정보 가져오기 & 날씨별 멘트 정리
String nickName = userData.getNickName();
finalMessage += nickName + "님, 오늘은 ";
sb.append(nickName).append("님, 오늘은 ");


/**
Expand All @@ -79,10 +86,10 @@ public String sendGoOutAlarm(String email) {
UserMedian userMedian = userMedianRepository.findByEmailAndSeason(email, currentSeason).orElseThrow(
() -> new CustomException(ErrorCode.NO_USER_MEDIAN_REGISTERED));

finalMessage += TemperatureUtils.createUserDataMessage(userMedian, temperature);
sb.append(TemperatureUtils.createUserDataMessage(userMedian, temperature));
} else {
//사용자 맞춤 알림이 off라면 -> 하루 평균 온도 정보 제공
finalMessage += "평균 온도가 "+temperature+"도예요.";
sb.append("평균 온도가 ").append(temperature).append("도입니다.");
}


Expand All @@ -96,39 +103,57 @@ public String sendGoOutAlarm(String email) {
* 3. 강수 정보 가져오기 - Weather Service
*/
//TODO : 강수량 확인, 멘트
finalMessage += " 오후 6시부터 8시까지 120mm의 비가 올 예정입니다.";
sb.append(" 오후 6시부터 8시까지 120mm의 비가 올 예정입니다.");

/**
* 4. 꽃가루 정보 가져오기 - Weather Service
*/
//TODO : 꽃가루 확인
finalMessage += " 꽃가루는 없습니다. ";
sb.append(" 꽃가루는 없습니다. ") ;

/**
* 알림 전송
*/
//TODO : FireBase 알림 보내기
log.info("[ Notification Service ] Final Message ---> {}", finalMessage);

//알림 저장
notificationRepository.save(Notification.builder()
.email(email)
.title("출근 날씨 알림")
.content(finalMessage)
.build());
log.info("[ Notification Service ] Final Message ---> {}", sb.toString());

return finalMessage;
//알림 보내기
alarmService.sendSingleAlarm(email, title, sb.toString());
return sb.toString();
}

//현재 위치 업데이트
@Transactional
public void checkCurrentAlarm(String email, LocationDto locationDto) {

log.info("[ Notification Service ] email ---> {}", email);
log.info("[ Notification Service ] 현재 위치 위도 (lat) ---> {}", locationDto.getLat());
log.info("[ Notification Service ] 현재 위치 경도 (lon) ---> {}", locationDto.getLon());
log.info("[ Notification Service ] 현재 위치 위도 (lat) ---> {}", locationDto.lat());
log.info("[ Notification Service ] 현재 위치 경도 (lon) ---> {}", locationDto.lon());

Optional<NotificationRecord> notiRecord = notificationRecordRepository.findByEmail(email);

//TODO : 위도 경도 -> 지역 변환
String region = "서울특별시";

if (notiRecord.isPresent()) {
NotificationRecord notificationRecord = notiRecord.get();

if (!notiRecord.get().getRegion().equals(region)) {
//만약 위치가 이동됐다면 알림 시간 초기화
notificationRecord.setLastWindAlarmReceived(LocalDateTime.now().minusHours(4));
notificationRecord.setLastRainAlarmReceived(LocalDateTime.now().minusHours(4));
}
notificationRecord.setRegion(region);

} else notificationRecordRepository.save(
NotificationRecord.builder()
.email(email)
.region(region)
.lastRainAlarmReceived(LocalDateTime.now().minusHours(4))
.lastWindAlarmReceived(LocalDateTime.now().minusHours(4))
.build()
);

notificationRecordRepository.findByEmail(email);



Expand Down

0 comments on commit 110cb35

Please sign in to comment.