Skip to content

Commit

Permalink
Merge pull request #87 from Donut-DONationUTile/feature/fcm
Browse files Browse the repository at this point in the history
Feature/fcm
  • Loading branch information
Ganghee-Lee-0522 authored May 1, 2024
2 parents 9a7d6b5 + 32211a7 commit a565b0a
Show file tree
Hide file tree
Showing 6 changed files with 114 additions and 30 deletions.
54 changes: 54 additions & 0 deletions src/main/java/zero/eight/donut/controller/FcmController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package zero.eight.donut.controller;

import com.google.firebase.messaging.FirebaseMessagingException;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import zero.eight.donut.common.response.ApiResponse;
import zero.eight.donut.dto.fcm.FcmTokenRequestDto;
import zero.eight.donut.exception.Success;
import zero.eight.donut.service.DonationService;
import zero.eight.donut.service.FcmService;

@RequiredArgsConstructor
@RequestMapping("/api/fcm")
@RestController
public class FcmController {

private final FcmService fcmService;
private final DonationService donationService;

@PostMapping("/token")
public ApiResponse<?> createFcmToken(@RequestBody FcmTokenRequestDto requestDto) throws Exception {
return fcmService.registerFcmToken(requestDto);
}

@PostMapping("/test/37")
public ApiResponse<?> test37() throws FirebaseMessagingException {
return ApiResponse.success(Success.FCM_TEST_SUCCESS, fcmService.imminentWallet());
}

@PostMapping("/test/7")
public ApiResponse<?> test7() throws FirebaseMessagingException {
return ApiResponse.success(Success.FCM_TEST_SUCCESS, fcmService.immminentGift());
}

@PostMapping("/test/30")
public ApiResponse<?> test30() throws FirebaseMessagingException {
return ApiResponse.success(Success.FCM_TEST_SUCCESS, donationService.autoDonate());
}

@GetMapping("/mock/37/{email}")
public ApiResponse<?> mock37(@PathVariable("email") String email, @RequestParam("product") String product) throws FirebaseMessagingException {
return ApiResponse.success(Success.FCM_TEST_SUCCESS, fcmService.mock37(email, product));
}

@GetMapping("/mock/30/{email}")
public ApiResponse<?> mock30(@PathVariable("email") String email, @RequestParam("product") String product) throws FirebaseMessagingException {
return ApiResponse.success(Success.FCM_TEST_SUCCESS, fcmService.mock30(email, product));
}

@GetMapping("/mock/7/{email}")
public ApiResponse<?> mock7(@PathVariable("email") String email, @RequestParam("product") String product) throws FirebaseMessagingException {
return ApiResponse.success(Success.FCM_TEST_SUCCESS, fcmService.mock30(email, product));
}
}
1 change: 1 addition & 0 deletions src/main/java/zero/eight/donut/exception/Success.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ public enum Success {
SUCCESS(HttpStatus.OK, "Request successfully processed"),

// 200 OK SUCCESS
FCM_TEST_SUCCESS(HttpStatus.OK, "Successfully completed test case"),
PATCH_STATUS_SUCCESS(HttpStatus.OK, "Successfully patch status"),
MYPAGE_RECEIVER_SUCCESS(HttpStatus.OK, "Get request for receiver's info completed successfully"),
MYPAGE_GIVER_SUCCESS(HttpStatus.OK, "Get request for giver's info completed successfully"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,7 @@ public interface GiftRepository extends JpaRepository<Gift, Long> {
@Query(value = "SELECT * FROM gift g WHERE g.status = 'STORED' AND g.is_assigned = false AND g.auto_donation = true AND g.due_date = :endDate", nativeQuery = true)
List<Gift> findAllByNotAssignedAndStoredAndAutoDonation(@Param("endDate") LocalDateTime endDate);

@Query(value = "SELECT * FROM gift g WHERE g.status = 'UNUSED' AND g.is_assigned = true AND g.due_date = :endDate", nativeQuery = true)
List<Gift> findAllByAssignedAndUnused(@Param("endDate") LocalDateTime endDate);

@Query(value = "SELECT * FROM gift g WHERE g.auto_donation = true AND g.status = 'STORED' AND g.giver_id = :giverId AND g.due_date >= :today", nativeQuery = true)
@Query(value = "SELECT * FROM gift g WHERE g.status = 'STORED' AND g.giver_id = :giverId AND g.due_date >= :today", nativeQuery = true)
List<Gift> findAllByGiverAndStatusAndDueDateAfterOrToday(@Param("giverId") Long giverId, @Param("today") LocalDateTime today);

@Query(value = "SELECT COUNT(*) FROM gift g WHERE g.giver_id = :giverId AND g.is_assigned = false", nativeQuery = true)
Expand Down
8 changes: 7 additions & 1 deletion src/main/java/zero/eight/donut/service/DonationService.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
Expand All @@ -29,13 +30,18 @@ public class DonationService {
@Async
@Transactional
@Scheduled(cron = "0 0 0 * * *")
public void autoDonate() throws FirebaseMessagingException {
public List<String> autoDonate() throws FirebaseMessagingException {
List<Gift> giftList = giftRepository.findAllByNotAssignedAndStatusAndDueDateBetween( "STORED", LocalDateTime.now(), LocalDateTime.now().minusDays(30));
List<String> fcmList = new ArrayList<>();

for (Gift gift : giftList) {
gift.updateStatus("UNUSED");
giftRepository.save(gift);
fcmUtils.sendMessage(gift.getGiver().getId(), "wallet: D-30", "Your item" + gift.getProduct() + "is donated now!");
fcmList.add("fcmReceiver: " + gift.getGiver().getName() + "(ROLE_GIVER), fcm title: wallet: D-30, fcm body: Your item" + gift.getProduct() + "is donated now!");
}

return fcmList;
}

public synchronized ApiResponse<?> assignGiftbox(GiftboxRequestDto giftboxRequestDto) {
Expand Down
44 changes: 35 additions & 9 deletions src/main/java/zero/eight/donut/service/FcmService.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,14 @@
import org.springframework.transaction.annotation.Transactional;
import zero.eight.donut.common.response.ApiResponse;
import zero.eight.donut.config.firebase.FcmUtils;
import zero.eight.donut.domain.FcmToken;
import zero.eight.donut.domain.Gift;
import zero.eight.donut.domain.Giftbox;
import zero.eight.donut.domain.Receiver;
import zero.eight.donut.domain.*;
import zero.eight.donut.dto.fcm.FcmMemberDto;
import zero.eight.donut.dto.fcm.FcmTokenRequestDto;
import zero.eight.donut.exception.Success;
import zero.eight.donut.repository.FcmTokenRepository;
import zero.eight.donut.repository.GiftRepository;
import zero.eight.donut.repository.GiftboxRepository;
import zero.eight.donut.repository.*;

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

@RequiredArgsConstructor
Expand All @@ -29,6 +25,8 @@ public class FcmService {
private final FcmTokenRepository fcmTokenRepository;
private final GiftRepository giftRepository;
private final GiftboxRepository giftboxRepository;
private final GiverRepository giverRepository;
private final ReceiverRepository receiverRepository;

public ApiResponse<?> registerFcmToken(FcmTokenRequestDto requestDto) throws Exception {
final String token = requestDto.getToken();
Expand All @@ -50,27 +48,55 @@ public ApiResponse<?> registerFcmToken(FcmTokenRequestDto requestDto) throws Exc
@Async
@Transactional
@Scheduled(cron = "0 0 0 * * *")
public void imminentWallet() throws FirebaseMessagingException {
public List<String> imminentWallet() throws FirebaseMessagingException {
List<Gift> giftList = giftRepository.findAllByNotAssignedAndStoredAndAutoDonation(LocalDateTime.now().plusDays(37));
List<String> fcmList = new ArrayList<>();

for (Gift gift : giftList) {
// 기프티콘의 giverId로 FCM 전송
fcmUtils.sendMessage(gift.getGiver().getId(), "wallet: D-37", "Your item" + gift.getProduct() + "is expiring soon! It will be automatically donated.");
fcmList.add("fcmReceiver: " + gift.getGiver().getName() + "(ROLE_GIVER), fcm title: wallet: D-37, fcm body: Your item" + gift.getProduct() + "is expiring soon! It will be automatically donated.");
}

return fcmList;
}

// 사용 기한 D-7 push 알림 (수혜자)
@Async
@Transactional
@Scheduled(cron = "0 0 0 * * *")
public void immminentGift() throws FirebaseMessagingException {
public List<String> immminentGift() throws FirebaseMessagingException {
// 7일 뒤 만료되는 꾸러미 찾기
List<Giftbox> giftboxList = giftboxRepository.findAllByIsAvailableAndDueDate(LocalDateTime.now().plusDays(7));
List<String> fcmList = new ArrayList<>();

for (Giftbox giftbox : giftboxList) {
// 수혜자 찾기
Receiver receiver = giftbox.getReceiver();

// 조회된 수혜자에게 FCM 전송
fcmUtils.sendMessage(receiver.getId(), "giftbox: D-7", "Your gift box is expiring soon! You can use it at" + giftbox.getStore() + ".");
fcmList.add("fcmReceiver: " + giftbox.getReceiver().getName() + "(ROLE_RECEIVER), fcm title: giftbox: D-7, fcm body: Your gift box is expiring soon! You can use it at" + giftbox.getStore() + ".");
}

return fcmList;
}

public String mock37(String email, String product) throws FirebaseMessagingException {
Giver giver = giverRepository.findByEmail(email).orElseThrow();
fcmUtils.sendMessage(giver.getId(), "wallet: D-37", "Your item" + product + "is expiring soon! It will be automatically donated.");
return "fcmReceiver: " + email + "(ROLE_GIVER), fcm title: wallet: D-37, fcm body: Your item" + product + "is expiring soon! It will be automatically donated.";
}

public String mock30(String email, String product) throws FirebaseMessagingException {
Giver giver = giverRepository.findByEmail(email).orElseThrow();
fcmUtils.sendMessage(giver.getId(), "wallet: D-30", "Your item" + product + "is donated now!");
return "fcmReceiver: " + giver.getName() + "(ROLE_GIVER), fcm title: wallet: D-30, fcm body: Your item" + product + "is donated now!";
}

public String mock7(String name, String store) throws FirebaseMessagingException {
Receiver receiver = receiverRepository.findByName(name).orElseThrow();
fcmUtils.sendMessage(receiver.getId(), "giftbox: D-7", "Your gift box is expiring soon! You can use it at" + store + ".");
return "fcmReceiver: " + receiver.getName() + "(ROLE_RECEIVER), fcm title: giftbox: D-7, fcm body: Your gift box is expiring soon! You can use it at" + store + ".";
}
}
32 changes: 16 additions & 16 deletions src/main/java/zero/eight/donut/service/MessageService.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package zero.eight.donut.service;

import com.google.firebase.messaging.FirebaseMessagingException;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zero.eight.donut.common.response.ApiResponse;
import zero.eight.donut.config.firebase.FcmUtils;
import zero.eight.donut.config.jwt.AuthUtils;
import zero.eight.donut.domain.Gift;
import zero.eight.donut.domain.Giftbox;
Expand All @@ -14,26 +18,27 @@
import zero.eight.donut.repository.GiftboxRepository;
import zero.eight.donut.repository.MessageRepository;

import java.util.List;

@Getter
@RequiredArgsConstructor
@Service
public class MessageService {

private final GiftboxRepository giftboxRepository;

private final AuthUtils authUtils;
private final FcmUtils fcmUtils;
private final MessageRepository messageRepository;
private final GiftRepository giftRepository;

public MessageService(GiftboxRepository giftboxRepository, AuthUtils authUtils, MessageRepository messageRepository, GiftRepository giftRepository) {
this.giftboxRepository = giftboxRepository;
this.authUtils = authUtils;
this.messageRepository = messageRepository;
this.giftRepository= giftRepository;
}
// public MessageService(GiftboxRepository giftboxRepository, AuthUtils authUtils, MessageRepository messageRepository, GiftRepository giftRepository) {
// this.giftboxRepository = giftboxRepository;
// this.authUtils = authUtils;
// this.messageRepository = messageRepository;
// this.giftRepository= giftRepository;
// }

@Transactional
public ApiResponse<?> sendMessage(SendMessageRequestDto requestDto) {
public ApiResponse<?> sendMessage(SendMessageRequestDto requestDto) throws FirebaseMessagingException {
// 수혜자
Receiver receiver = authUtils.getReceiver();

Expand Down Expand Up @@ -63,14 +68,9 @@ public ApiResponse<?> sendMessage(SendMessageRequestDto requestDto) {
.giver(gift.getGiver())
.build();
messageRepository.save(message);
/////////////////////////////////////
/////////////////////////////////////
/////////////////////////////////////
// 기부자에게 알림 보내기
/////////////////////////////////////
/////////////////////////////////////
/////////////////////////////////////

// 기부자에게 알림 보내기
fcmUtils.sendMessage(gift.getGiver().getId(), "message", "You've got a message!");

// 반환하기
return ApiResponse.success(Success.SEND_MESSAGE_SUCCESS);
Expand Down

0 comments on commit a565b0a

Please sign in to comment.