Skip to content

Commit

Permalink
bug: 로깅 삭제 및 알림 형식 수정
Browse files Browse the repository at this point in the history
테스트 알림도 삭제
  • Loading branch information
kanguk01 committed Nov 13, 2024
1 parent 4d28632 commit 4bc01fd
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 74 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -26,45 +26,37 @@
@RequiredArgsConstructor
public class NotificationScheduler {

private static final ZoneId ZONE_ID_SEOUL = ZoneId.of("Asia/Seoul");
private final PlanRepository planRepository;
private final FcmTokenRepository fcmTokenRepository;
private final NotificationLogRepository notificationLogRepository;
private final NotificationService notificationService;
private final QueryPerformanceService queryPerformanceService;

private static final ZoneId ZONE_ID_SEOUL = ZoneId.of("Asia/Seoul");

@Scheduled(fixedRate = 60000)
public void sendScheduledNotifications() {
LocalDateTime now = LocalDateTime.now(ZONE_ID_SEOUL);
log.info("Scheduler started at {}", now);

List<Plan> upcomingPlans = planRepository.findUpcomingPlans(now);
log.info("Found {} upcoming plans", upcomingPlans.size());

Set<Long> userIds = upcomingPlans.stream()
.map(plan -> plan.getUser().getId())
.collect(Collectors.toSet());
log.info("Collected user IDs: {}", userIds);

List<FcmToken> allFcmTokens = fcmTokenRepository.findByUserIdIn(userIds);
log.info("Fetched {} FCM tokens", allFcmTokens.size());

Map<Long, List<FcmToken>> userFcmTokenMap = allFcmTokens.stream()
.collect(Collectors.groupingBy(fcmToken -> fcmToken.getUser().getId()));

Set<Long> planIds = upcomingPlans.stream()
.map(Plan::getId)
.collect(Collectors.toSet());
log.info("Collected plan IDs: {}", planIds);

Set<Long> fcmTokenIds = allFcmTokens.stream()
.map(FcmToken::getId)
.collect(Collectors.toSet());
log.info("Collected FCM token IDs: {}", fcmTokenIds);

List<NotificationLog> notificationLogs = notificationLogRepository.findByFcmTokenIdInAndPlanIdIn(fcmTokenIds, planIds);
log.info("Found {} notification logs for existing notifications", notificationLogs.size());

Set<String> sentNotificationKeys = notificationLogs.stream()
.map(log -> log.getFcmToken().getId() + ":" + log.getPlan().getId())
Expand All @@ -73,27 +65,18 @@ public void sendScheduledNotifications() {
for (Plan plan : upcomingPlans) {
Long userId = plan.getUser().getId();
List<FcmToken> fcmTokens = userFcmTokenMap.getOrDefault(userId, Collections.emptyList());
log.info("Processing plan ID {} for user ID {}, FCM tokens: {}", plan.getId(), userId, fcmTokens.size());

for (FcmToken fcmToken : fcmTokens) {
if (Boolean.TRUE.equals(fcmToken.getIsNotificationEnabled())) {
LocalDateTime notificationTime = plan.getStartDate().atZone(ZONE_ID_SEOUL).toLocalDateTime().minusMinutes(fcmToken.getNotificationOffset());
log.info("Evaluating notification for FCM token ID {} at notificationTime: {}", fcmToken.getId(), notificationTime);

if (notificationTime.isAfter(now.minusMinutes(5)) && notificationTime.isBefore(now.plusMinutes(1))) {
String notificationKey = fcmToken.getId() + ":" + plan.getId();

if (!sentNotificationKeys.contains(notificationKey)) {
log.info("Sending notification for FCM token ID {} and plan ID {}", fcmToken.getId(), plan.getId());
notificationService.sendNotification(fcmToken, plan);
} else {
log.info("Notification already sent for FCM token ID {} and plan ID {}", fcmToken.getId(), plan.getId());
}
} else {
log.info("Notification time {} does not match the required range for now: {}", notificationTime, now);
}
} else {
log.info("Notification disabled for FCM token ID {}", fcmToken.getId());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
Expand All @@ -29,53 +29,29 @@ public NotificationService(FcmTokenRepository fcmTokenRepository, FirebaseMessag
}

public void sendNotification(FcmToken fcmToken, Plan plan) {
String title = "곧 시작하는 플랜: " + plan.getTitle();
String body = "곧 시작하는 플랜이 있어요! " + plan.getDescription();
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH시 mm분");

String nickname = plan.getUser().getNickname();

String startTime = plan.getStartDate().toLocalTime().format(timeFormatter);
String endTime = plan.getEndDate().toLocalTime().format(timeFormatter);

String title = "🗓️ " + nickname + "님! " + plan.getTitle() + " 시간이에요! ";
String body = startTime + " - " + endTime + " \n" +
(plan.getDescription() != null ? plan.getDescription() : " ");

Notification notification = new Notification(title, body);

Message message = Message.builder()
.setToken(fcmToken.getToken())
.setNotification(notification)
.putData("title", plan.getTitle())
.putData("title", plan.getDescription())
.putData("startDate", plan.getStartDate().toString())
.build();
Message message = Message.builder().setToken(fcmToken.getToken()).setNotification(notification).putData("title", plan.getTitle()).putData("title", plan.getDescription()).putData("startDate", plan.getStartDate().toString()).build();
try {
String response = firebaseMessaging.send(message);
log.info("알림을 정상적으로 전송하였습니다. : {}", response);

// 알림 전송 기록 저장
NotificationLog logEntry = NotificationLog.builder()
.fcmToken(fcmToken)
.plan(plan)
.sentAt(LocalDateTime.now())
.build();
NotificationLog logEntry = NotificationLog.builder().fcmToken(fcmToken).plan(plan).sentAt(LocalDateTime.now()).build();
notificationLogRepository.save(logEntry);

} catch (Exception e) {
log.error("FCM 알림 전송 실패 ", e);
}
}

// 알림 테스트를 위한 메소드 (추후 삭제)
public void sendTestNotification(Long userId) {
List<FcmToken> fcmTokens = fcmTokenRepository.findByUserId(userId);

for (FcmToken fcmToken : fcmTokens) {
Notification notification = new Notification("테스트 알림", "이것은 테스트 알림입니다.");

Message message = Message.builder()
.setToken(fcmToken.getToken())
.setNotification(notification)
.build();

try {
String response = firebaseMessaging.send(message);
log.info("Successfully sent message: {}", response);
} catch (Exception e) {
log.error("Failed to send FCM notification", e);
}
}
}
}

0 comments on commit 4bc01fd

Please sign in to comment.