Skip to content

Commit

Permalink
Merge pull request #188 from FOREGG-DEV/dev
Browse files Browse the repository at this point in the history
♻️ refactor: FCM 알림 로직 리팩토링
  • Loading branch information
DongJun1110 authored Jan 3, 2025
2 parents 5c00f9f + 4da68a0 commit c86b981
Show file tree
Hide file tree
Showing 10 changed files with 264 additions and 60 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ public ApiResponse<String> deleteByCount(@PathVariable(name = "count") int count
@PreAuthorize("hasRole('ROLE_WIFE')")
public ApiResponse<String> write(@RequestPart(name = "image", required = false) MultipartFile image,
@RequestPart(name = "dto") DailyRequestDTO dto) throws IOException {

dailyService.writeDaily(dto, s3Service.upload(image));
return ApiResponse.onSuccess();
}
Expand Down Expand Up @@ -176,13 +175,13 @@ public ApiResponse<String> deleteSideEffect(@PathVariable(name = "id") Long id)
return ApiResponse.onSuccess();
}

@Operation(summary = "주사 투여 완료 공유하기 API")
@Operation(summary = "의약품 투여 완료 공유하기 API")
@PreAuthorize("hasRole('ROLE_WIFE')")
@PostMapping("/shareInjection/{id}")
@PostMapping("/shareMedical/{id}")
public ApiResponse<String> sendNotificationInjection(@PathVariable(name = "id") Long id,
@RequestParam(name = "time") String time) {

injectionQueryService.shareInjection(id, time);
injectionQueryService.shareMedical(id, time);
return ApiResponse.onSuccess();
}

Expand Down
13 changes: 13 additions & 0 deletions src/main/java/foregg/foreggserver/domain/enums/NavigationType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package foregg.foreggserver.domain.enums;

public enum NavigationType {
daily_hugg_graph,
calendar_graph,
inj_med_info_screen, // inj_med_info_screen/INJECTION/{id}/{time} or inj_med_info_screen/MEDICINE/{id}/{time}
account_graph,
create_daily_hugg,
reply_daily_hugg, //reply_daily_hugg/{데일리 허그 생성날짜}
myChallenge,
challenge_support, //challenge_support/{id}
home_graph
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
import foregg.foreggserver.domain.ChallengeParticipation;
import foregg.foreggserver.domain.Notification;
import foregg.foreggserver.domain.User;
import foregg.foreggserver.domain.enums.NavigationType;
import foregg.foreggserver.domain.enums.NotificationType;
import foregg.foreggserver.dto.challengeDTO.ChallengeResponseDTO.MyChallengeTotalDTO.MyChallengeDTO;
import foregg.foreggserver.repository.ChallengeParticipationRepository;
import foregg.foreggserver.repository.ChallengeRepository;
import foregg.foreggserver.repository.NotificationRepository;
import foregg.foreggserver.repository.UserRepository;
import foregg.foreggserver.service.fcmService.FcmService;
import foregg.foreggserver.service.notificationService.NotificationService;
import foregg.foreggserver.service.userService.UserQueryService;
import foregg.foreggserver.util.DateUtil;
Expand All @@ -22,6 +24,7 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
Expand All @@ -42,6 +45,7 @@ public class ChallengeService {
private final ChallengeQueryService challengeQueryService;
private final NotificationService notificationService;
private final NotificationRepository notificationRepository;
private final FcmService fcmService;

public void participate(Long id) {
User user = userQueryService.getUser();
Expand Down Expand Up @@ -184,6 +188,26 @@ public void cheer(Long receiverId, NotificationType type, Long challengeId) {

Notification notification = notificationService.createNotification(type, receiver, sender.getChallengeName(), challengeId);
notificationRepository.save(notification);
cheerAlarm(receiver, sender, type, challengeId);
}

private void cheerAlarm(User receiver, User sender, NotificationType type, Long challengeId) {
String alarmType;
String rear;
if (type.equals(NotificationType.SUPPORT)) {
alarmType = "응원";
rear = "이";
}else{
alarmType = "박수";
rear = "가";
}
try {
fcmService.sendMessageTo(receiver.getFcmToken(), String.format("다른 사용자로부터 %s받았을 때",alarmType), String.format("%s님으로부터 %s%s 도착했어요. 오늘의 챌린지를 달성하러 가볼까요?",sender.getChallengeName(),alarmType,rear), NavigationType.challenge_support.toString()+"/"+challengeId, null, null, null);
log.info("FCM 푸시 알림이 성공적으로 {}에게 전송되었습니다.", receiver.getNickname());
} catch (IOException e) {
log.error("FCM 푸시 알림을 보내는 도중 오류 발생: {}", e.getMessage());
throw new RuntimeException(e);
}
}

private void catchCheerException(ChallengeParticipation challengeParticipation, NotificationType notificationType) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import foregg.foreggserver.converter.DailyConverter;
import foregg.foreggserver.domain.*;
import foregg.foreggserver.domain.Record;
import foregg.foreggserver.domain.enums.NavigationType;
import foregg.foreggserver.domain.enums.NotificationType;
import foregg.foreggserver.dto.dailyDTO.DailyRequestDTO;
import foregg.foreggserver.dto.dailyDTO.DailyRequestDTO.DailyReplyRequestDTO;
Expand Down Expand Up @@ -57,14 +58,18 @@ public class DailyService {
public void writeDaily(DailyRequestDTO dto, String imageUrl) {
User user = userQueryService.getUser();
Daily daily = dailyRepository.findByDateAndUser(DateUtil.formatLocalDateTime(LocalDate.now()),user);
String navigation = NavigationType.daily_hugg_graph.toString();
if (daily.getReply() == null) {
navigation = NavigationType.reply_daily_hugg.toString() + "/" + daily.getDate();
}
int count = myPageQueryService.getSurgeryCount();
if (daily != null) {
throw new RecordHandler(ALREADY_WRITTEN);
}
User spouse = userQueryService.returnSpouse();
if (spouse != null) {
try {
fcmService.sendMessageTo(spouse.getFcmToken(), "새로운 하루기록이 등록되었습니다", String.format("%s님의 하루 기록이 도착했어요.", user.getNickname()), "today record male", null, null, null);
fcmService.sendMessageTo(spouse.getFcmToken(), "여자, 데일리허그 작성 완료", String.format("%s님으로부터 데일리 허그가 도착했어요. 답장을 남겨주세요!", user.getNickname()), navigation, null, null, null);
log.info("FCM 푸시 알림이 성공적으로 {}에게 전송되었습니다.", spouse.getNickname());
} catch (IOException e) {
log.error("FCM 푸시 알림을 보내는 도중 오류 발생: {}", e.getMessage());
Expand Down Expand Up @@ -101,6 +106,11 @@ public void reply(DailyReplyRequestDTO dto) {
daily.setReply(reply);
Notification notification = notificationService.createNotification(NotificationType.REPLY, wife, userQueryService.getUser().getNickname(), daily.getId());
notificationRepository.save(notification);
try {
fcmService.sendMessageTo(wife.getFcmToken(), "남자, 데일리 허그 답장 작성 완료", String.format("%s님으로부터 답장이 도착했어요.", userQueryService.getUser().getNickname()), NavigationType.daily_hugg_graph.toString(), null, null, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

public void writeSideEffect(SideEffectRequestDTO dto) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class InjectionQueryService {
private final RecordRepository recordRepository;
private final RepeatTimeRepository repeatTimeRepository;

public void shareInjection(Long id, String time) {
public void shareMedical(Long id, String time) {
User user = userQueryService.getUser();
Optional<Record> foundRecord = recordRepository.findByIdAndUser(id, user);
if (foundRecord.isEmpty()) {
Expand All @@ -45,7 +45,7 @@ public void shareInjection(Long id, String time) {
User spouse = userQueryService.returnSpouse();
if (spouse != null) {
try {
fcmService.sendMessageTo(spouse.getFcmToken(), "주사 푸시 알림입니다", String.format("%s님이 일정을 완료했어요.", user.getNickname(),foundRecord.get().getName()),"inj_med_info_screen", id.toString(), time, null);
fcmService.sendMessageTo(spouse.getFcmToken(), "투여 완료 공유 알림입니다", String.format("%s님이 일정을 완료했어요.", user.getNickname(),foundRecord.get().getName()),"inj_med_info_screen", id.toString(), time, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
Expand Down
Loading

0 comments on commit c86b981

Please sign in to comment.