Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…erver into feature/donation/receiver
  • Loading branch information
Kang1221 committed May 1, 2024
2 parents 339733a + 11ce126 commit 935a4c6
Show file tree
Hide file tree
Showing 23 changed files with 224 additions and 76 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
#FirebaseConfig.*
#FcmUtils.*
#FirebaseConfig.*
#FcmController.*
#FcmService.*

HELP.md
.gradle
build/
Expand Down
2 changes: 1 addition & 1 deletion Donut-Server-yml
15 changes: 12 additions & 3 deletions src/main/java/zero/eight/donut/config/firebase/FcmUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ public class FcmUtils {
private final GiverRepository giverRepository;
private final ReceiverRepository receiverRepository;
private final FcmTokenRepository fcmTokenRepository;
private final FirebaseMessaging firebaseMessaging;



Expand Down Expand Up @@ -60,10 +59,20 @@ public FcmMemberDto getMemberDto() throws Exception {
public String sendMessage(Long memberId, String title, String body) throws FirebaseMessagingException {
// 알림 수신자의 FCM 토큰 조회
String fcmToken = getFcmToken(memberId);
log.info("fcmToken -> {}", fcmToken);

// FCM 메세지 생성
Message message = makeMessage(fcmToken, title, body);
log.info("message -> {}", message);

// FCM 발신
return firebaseMessaging.send(message);
//return firebaseMessaging.send(message);
try {
return FirebaseMessaging.getInstance().send(message);
} catch (Exception e) {
log.info(e.getMessage());
return "Falied to send notification";
}
}

public String getFcmToken(Long memberId) {
Expand Down Expand Up @@ -92,4 +101,4 @@ public Message makeMessage(String targetToken, String title, String body) {
.setToken(targetToken)
.build();
}
}
}
29 changes: 25 additions & 4 deletions src/main/java/zero/eight/donut/config/firebase/FirebaseConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,21 @@
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

@Configuration
public class FirebaseConfig {

String filepath = System.getenv("FIREBASE_CONFIG_FILE");
@PostConstruct
public void init() {
try {
FileInputStream serviceAccount =
new FileInputStream("src/main/resources/serviceAccountKey.json");
new FileInputStream(filepath != null ? filepath : "src/main/resources/serviceAccountKey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();
Expand All @@ -25,4 +26,24 @@ public void init() {
e.printStackTrace();
}
}
}


@Bean
public FirebaseMessaging firebaseMessaging() {
try {
FileInputStream serviceAccount =
new FileInputStream(filepath != null ? filepath : "src/main/resources/serviceAccountKey.json");

FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();

if (FirebaseApp.getApps().isEmpty()) { // FirebaseApp의 중복 초기화 방지.
FirebaseApp.initializeApp(options);
}
return FirebaseMessaging.getInstance();
} catch (Exception e) {
throw new IllegalStateException("Firebase Messaging 서비스를 초기화하는 동안 문제가 발생했습니다.", e);
}
}
}
41 changes: 36 additions & 5 deletions src/main/java/zero/eight/donut/controller/FcmController.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package zero.eight.donut.controller;

import com.google.firebase.messaging.FirebaseMessagingException;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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
Expand All @@ -15,9 +15,40 @@
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(name = "email") String email, @RequestParam(name = "product") String product) throws FirebaseMessagingException {
return ApiResponse.success(Success.FCM_TEST_SUCCESS, fcmService.mock37(email, product));
}

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

@GetMapping("/mock/7/{name}")
public ApiResponse<?> mock7(@PathVariable(name = "name") String name, @RequestParam(name = "store") String store) throws FirebaseMessagingException {
return ApiResponse.success(Success.FCM_TEST_SUCCESS, fcmService.mock7(name, store));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ public class HistoryGiverController {
private final AuthService authService;

@GetMapping("/info/{donateDate}")
public ApiResponse<?> getDonationList(@PathVariable("donateDate")LocalDateTime donateDate){
public ApiResponse<?> getDonationList(@PathVariable(name = "donateDate")LocalDateTime donateDate){
return historyGiverService.getDonationList(donateDate);
}

@GetMapping("/info/detail/{giftId}")
public ApiResponse<?> getDonationDetail(@PathVariable("giftId")Long giftId){
public ApiResponse<?> getDonationDetail(@PathVariable(name = "giftId")Long giftId){
return historyGiverService.getDonationDetail(giftId);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ public ApiResponse<?> receiverHome(){
}

@GetMapping("/box/{boxId}")
public ApiResponse<?> receiverGetOneBox(@PathVariable("boxId") Long boxId){
public ApiResponse<?> receiverGetOneBox(@PathVariable(name = "boxId") Long boxId){
return homeReceiverService.receiverGetOneBox(boxId);
}

@GetMapping("/gift/{giftId}")
public ApiResponse<?> receiverGetOneGuft(@PathVariable("giftId") Long giftId){
public ApiResponse<?> receiverGetOneGuft(@PathVariable(name = "giftId") Long giftId){
return homeReceiverService.receiverGetOneGift(giftId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public ApiResponse<?> walletDetail(@PathVariable Long giftId) {
}

@PostMapping
public ApiResponse<?> walletUpload(@RequestBody WalletUploadRequestDto requestDto) throws IOException {
public ApiResponse<?> walletUpload(WalletUploadRequestDto requestDto) throws IOException {
return walletService.walletUpload(requestDto);
}
}
2 changes: 1 addition & 1 deletion src/main/java/zero/eight/donut/domain/FcmToken.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ public void updateToken(String token, Role role) {
this.token = token;
this.role = role;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@

@Getter
public class SendMessageRequestDto {
private Long boxId; // 꾸러미 고유 ID
private Long giftId; // 기프티콘 고유 ID
private String content; // 메세지 본문
}
2 changes: 1 addition & 1 deletion src/main/java/zero/eight/donut/dto/fcm/FcmMemberDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@
public class FcmMemberDto {
private Long id;
private Role role;
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package zero.eight.donut.dto.fcm;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Getter
public class FcmTokenRequestDto {
private final String token;
}
private String token;
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ public class GiverDonationDetailResponseDto {
private LocalDateTime dueDate;
private Store store;
private String receiver;
private String giver;
private Boolean isAssigned;
private Status status;
private String message;
private LocalDateTime donateDate;
private LocalDateTime receivedDate;
}
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 @@ -13,7 +13,7 @@ public interface BenefitRepository extends JpaRepository<Benefit, Long> {
Optional<Benefit> findByReceiver(Receiver receiver);

@Query("SELECT b FROM Benefit b WHERE b.receiver.id =?1 AND b.year = ?2 AND b.month= ?3")
Benefit findByReceiverIdAndThisMonth(Long receiverId, Integer year, Integer month);
Optional<Benefit> findByReceiverIdAndThisMonth(Long receiverId, Integer year, Integer month);

@Query(value = "SELECT SUM(b.sum) FROM benefit b WHERE b.receiver_id = :receiverId", nativeQuery = true)
Integer sumBenefitByReceiverId(@Param("receiverId") Long receiverId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@

public interface FcmTokenRepository extends JpaRepository<FcmToken, Long> {
Optional<FcmToken> findByMemberId(Long memberId);
}
}
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
9 changes: 7 additions & 2 deletions src/main/java/zero/eight/donut/service/DonationService.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,32 @@

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

@Slf4j
@RequiredArgsConstructor
@Service
public class DonationService {

private final FcmUtils fcmUtils;
private final SerialDonationService donationService;
private final GiftRepository giftRepository;

@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
Loading

0 comments on commit 935a4c6

Please sign in to comment.