Skip to content

Commit

Permalink
Feat: 재난 발생 이벤트 핸들러 기초 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
versatile0010 committed Nov 21, 2023
1 parent 57ff821 commit bac76e2
Show file tree
Hide file tree
Showing 6 changed files with 148 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package com.numberone.backend.domain.admin.controller;

import com.numberone.backend.domain.admin.dto.request.CreateDisasterEventDto;
import com.numberone.backend.domain.admin.dto.response.GetAddressResponse;
import com.numberone.backend.domain.admin.service.AdminService;
import com.numberone.backend.domain.disaster.dto.request.SaveDisasterRequest;
import com.numberone.backend.domain.disaster.event.DisasterEvent;
import com.numberone.backend.domain.disaster.service.DisasterService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.util.List;
Expand All @@ -19,6 +21,7 @@
public class AdminController {

private final AdminService adminService;
private final DisasterService disasterService;

@Operation(summary = "서버에 지역별 대피소 정보 Json 파일로 업로드하기", description =
"""
Expand Down Expand Up @@ -58,4 +61,11 @@ public ResponseEntity<List<GetAddressResponse>> getAllAddressInfo() {
return ResponseEntity.ok(adminService.getAllAddressInfo());
}

@Operation(summary = "(테스트용) 재난 발생시키기")
@PostMapping("/disaster")
public ResponseEntity<SaveDisasterRequest> createDisaster(@RequestBody SaveDisasterRequest request){
disasterService.save(request);
return ResponseEntity.ok(request);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.numberone.backend.domain.admin.dto.request;

import com.numberone.backend.domain.disaster.util.DisasterType;
import lombok.*;

@ToString
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class CreateDisasterEventDto {
DisasterType type;
String location;
String message;
Long disasterNum;
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.numberone.backend.domain.notificationregion.repository.NotificationRegionRepository;
import com.numberone.backend.exception.notfound.NotFoundMemberException;
import com.numberone.backend.support.fcm.service.FcmMessageProvider;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
Expand All @@ -27,12 +28,13 @@ public class DisasterEventHandler {
private final NotificationRepository notificationRepository;
private final NotificationRegionRepository notificationRegionRepository;

@Transactional(jakarta.transaction.Transactional.TxType.REQUIRES_NEW)
@TransactionalEventListener
public void sendFcmMessagesByPresentLocation(DisasterEvent disasterEvent) {
log.info("[신규 재난 발생! Disaster event handler 가 동작합니다.]");
log.info("[sendFcmMessagesByPresentLocation]");

String type = disasterEvent.getType().toString();
String type = disasterEvent.getType().code2kor();
String location = disasterEvent.getLocation();
Long disasterNum = disasterEvent.getDisasterNum();
String title = String.format("[긴급] %s %s 발생", location, type);
Expand All @@ -45,10 +47,10 @@ public void sendFcmMessagesByPresentLocation(DisasterEvent disasterEvent) {
List<String> targetMemberFcmTokens = memberIdListByPresentLocation.stream().map(memberId -> {
Member member = memberRepository.findById(memberId)
.orElseThrow(NotFoundMemberException::new);
notificationRepository.save(
NotificationEntity savedNotificationEntity = notificationRepository.save(
new NotificationEntity(member, disasterEvent.getType(), disasterEvent.getMessage(), true)
);
log.info("received member id: {}", member.getId());
log.info("received member id: {} Notification id: {} ", member.getId(), savedNotificationEntity.getId());
log.info(title);
log.info(message);
return member.getFcmToken();
Expand All @@ -57,6 +59,7 @@ public void sendFcmMessagesByPresentLocation(DisasterEvent disasterEvent) {
// fcm 메세지 일괄 전송
fcmMessageProvider.sendFcmToMembers(targetMemberFcmTokens, title, message, NotificationTag.DISASTER);


log.info("위험 지역에 위치한 회원의 가족에게 알림을 보냅니다.");
// 해당 회원의 가족에게 알림을 보낸다.
String messageToFriend = "";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ public void save(SaveDisasterRequest saveDisasterRequest) {
dateTime
)
);
log.info("재난 발생 이벤트 발행");
eventPublisher.publishEvent(DisasterEvent.of(savedDisaster)); // 신규 재난 발생 이벤트
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,114 @@ public static DisasterType kor2code(String kor) {
}
throw new InvalidDisasterTypeException();
}

public String code2kor() {
switch (this) {
case DROUGHT -> {
return "가뭄";
}
case STRONG_WIND -> {
return "강풍";
}
case DRYNESS -> {
return "건조";
}
case HEAVY_SNOWFALL -> {
return "대설";
}
case TIDAL_WAVE -> {
return "대조기";
}
case FINE_DUST -> {
return "미세먼지";
}
case WILDFIRE -> {
return "산불";
}
case LANDSLIDE -> {
return "산사태";
}
case FOG -> {
return "안개";
}
case EARTHQUAKE -> {
return "지진";
}
case TYPHOON -> {
return "태풍";
}
case HEATWAVE -> {
return " 폭염";
}
case ROUGH_SEA -> {
return "풍랑";
}
case COLD_WAVE -> {
return "한파";
}
case HEAVY_RAIN -> {
return "호우";
}
case FLOOD -> {
return "홍수";
}
case GAS -> {
return "가스";
}
case TRAFFIC -> {
return "교통";
}
case FINANCE -> {
return "금융";
}
case COLLAPSE -> {
return "붕괴";
}
case WATER_SUPPLY -> {
return "수도";
}
case ENERGY -> {
return "에너지";
}
case MEDICAL -> {
return "의료";
}
case INFECTIOUS_DISEASE -> {
return "전염병";
}
case POWER_OUTAGE -> {
return "정전";
}
case COMMUNICATION -> {
return "통신";
}
case EXPLOSION -> {
return "폭발";
}
case FIRE -> {
return "화재";
}
case ENVIRONMENTAL_POLLUTION -> {
return "환경오염사고";
}
case AI -> {
return "AI";
}
case EMERGENCY -> {
return "비상사태";
}
case TERROR -> {
return "테러";
}
case CHEMICAL -> {
return "화생방사고";
}
case MISSING -> {
return "실종";
}
default -> {
return "기타";
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.numberone.backend.support.notification.NotificationMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
Expand Down Expand Up @@ -125,6 +126,7 @@ public void sendFcmToMembers(List<String> tokens, FcmNotificationDto fcmDto) {

public void sendFcmToMembers(List<String> tokens, String title, String body, NotificationTag tag) {
log.info("{} 건의 푸시알람을 전송합니다.", tokens.size());
if(tokens.isEmpty()) return;
List<Message> messages = tokens.stream().map(
token -> Message.builder()
.putData("time", LocalDateTime.now().toString())
Expand Down Expand Up @@ -155,7 +157,7 @@ public void sendFcmToMembers(List<String> tokens, String title, String body, Not
log.info("Fcm 푸시 알람을 전송하였습니다.");
} catch (Exception e) {
log.error("Fcm 푸시 알람을 전송하는 도중에 에러가 발생했습니다. {}", e.getMessage());
throw new FirebaseMessageSendException();
//throw new FirebaseMessageSendException();
}
}

Expand Down

0 comments on commit bac76e2

Please sign in to comment.