Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] 비콘 알림 생성 #95

Merged
merged 4 commits into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package ewha.lux.once.domain.home.controller;

import ewha.lux.once.domain.card.dto.SearchStoresRequestDto;
import ewha.lux.once.domain.home.dto.AnnounceFavoriteRequestDto;
import ewha.lux.once.domain.home.dto.BeaconRequestDto;
import ewha.lux.once.domain.home.service.HomeService;
import ewha.lux.once.global.common.CommonResponse;
import ewha.lux.once.global.common.CustomException;
Expand Down Expand Up @@ -80,5 +82,27 @@ public CommonResponse<?> nearFavorite(@AuthenticationPrincipal UserAccount user,
return new CommonResponse<>(e.getStatus());
}
}
// [Post] 알림 생성 요청
@PostMapping("/announcement")
@ResponseBody
public CommonResponse<?> announceFavorite(@AuthenticationPrincipal UserAccount user, @RequestBody AnnounceFavoriteRequestDto announceFavoriteRequestDto){
try {
homeService.postAnnounceFavorite(announceFavoriteRequestDto, user.getUsers());
return new CommonResponse<>(ResponseCode.SUCCESS);
} catch (CustomException e){
return new CommonResponse<>(e.getStatus());
}
}
// [Post] 비콘 알림 생성 요청
@PostMapping("/beacon")
@ResponseBody
public CommonResponse<?> beaconAnnouncement(@AuthenticationPrincipal UserAccount user, @RequestBody BeaconRequestDto beaconRequestDto){
try {
homeService.postBeaconAnnouncement(beaconRequestDto, user.getUsers());
return new CommonResponse<>(ResponseCode.SUCCESS);
} catch (CustomException e){
return new CommonResponse<>(e.getStatus());
}
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package ewha.lux.once.domain.home.dto;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class AnnounceFavoriteRequestDto {
private String store;
private String storeName;
private double latitude;
private double longitude;
}
17 changes: 17 additions & 0 deletions src/main/java/ewha/lux/once/domain/home/dto/BeaconRequestDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package ewha.lux.once.domain.home.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;


@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class BeaconRequestDto {
private String proximityUUID;
private Integer major;
private Integer minor;
}
40 changes: 40 additions & 0 deletions src/main/java/ewha/lux/once/domain/home/entity/Beacon.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package ewha.lux.once.domain.home.entity;


import jakarta.persistence.*;
import lombok.*;

@Entity
@Table(name="Beacon")
@Getter
@Setter
@Builder
@NoArgsConstructor(access= AccessLevel.PROTECTED)
@AllArgsConstructor
public class Beacon {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "beaconId")
private Long id;

@Column(name = "proximityUUID", nullable = false)
private String proximityUUID;

@Column(name = "major")
private Integer major;

@Column(name = "minor")
private Integer minor;

@Column(name = "name")
private String name;

@Column(name = "store")
private String store;

@Column(name = "latitude")
private String latitude;

@Column(name = "longitude")
private String longitude;
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,14 @@ public void cheeringBenefitGoalAnnounce() throws CustomException {
List<FCMToken> fcmTokens = fcmTokenRepository.findAllByUsers(users);
for ( FCMToken fcmToken : fcmTokens){
String token = fcmToken.getToken();
firebaseCloudMessageService.sendNotification(new AnnouncementRequestDto(token,"ONCE",content));
firebaseCloudMessageService.sendNotification(new AnnouncementRequestDto(token,"목표 응원 알림",content));
}
}
}

@Scheduled(cron = "0 0 21 10,15,25 * ?")
public void cardPerformanceAnnounce() throws CustomException {
String currentDate = String.valueOf(LocalDate.now().getMonthValue());;
List<OwnedCard> ownedCardList = ownedCardRepository.findOwnedCardByIsMain(true);
for (OwnedCard card : ownedCardList) {
// 실적 업데이트
Expand All @@ -97,12 +98,12 @@ public void cardPerformanceAnnounce() throws CustomException {

ownedCardRepository.save(card);
String res = String.valueOf(Math.max(card.getPerformanceCondition()-card.getCurrentPerformance(),0));
String content = "이번 달 "+card.getCard().getName()+" 실적까지 "+res+"원 남았어요!";
String content = "이번 달 "+card.getCard().getName()+" 실적까지\n"+res+"원 남았어요!";
String moreInfo = card.getCard().getImgUrl();

Announcement announcement = Announcement.builder()
.users(users)
.type(1)
.type(3)
.content(content)
.moreInfo(moreInfo)
.hasCheck(false)
Expand All @@ -111,7 +112,7 @@ public void cardPerformanceAnnounce() throws CustomException {
List<FCMToken> fcmTokens = fcmTokenRepository.findAllByUsers(users);
for ( FCMToken fcmToken : fcmTokens){
String token = fcmToken.getToken();
firebaseCloudMessageService.sendNotification(new AnnouncementRequestDto(token,"ONCE",content));
firebaseCloudMessageService.sendNotification(new AnnouncementRequestDto(token,currentDate+"월 실적 알림",content));
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,8 @@ public List<String> GetHistory(String code, String connectedId,String cardName,
for (Object obj : dataArray) {
JSONObject dataObject = (JSONObject) obj;
String storeName = (String) dataObject.get("resMemberStoreName");
String storeAddr = (String) dataObject.get("resMemberStoreAddr");
String storeKey = storeName + "#" + storeAddr; // 고유 키 생성
// String storeAddr = (String) dataObject.get("resMemberStoreAddr");
String storeKey = storeName; // 고유 키 생성

// 맵에 있는지 확인하고 카운트 업데이트
storeCountMap.put(storeKey, storeCountMap.getOrDefault(storeKey, 0) + 1);
Expand All @@ -265,11 +265,11 @@ public List<String> GetHistory(String code, String connectedId,String cardName,
List<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(storeCountMap.entrySet());
sortedEntries.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));

// 상위 5개의 매장 정보 추출
// 상위 10개의 매장 정보 추출
List<String> topStores = new ArrayList<>();
int count = 0;
for (Map.Entry<String, Integer> entry : sortedEntries) {
if (count >= 5) break;
if (count >= 10) break;
topStores.add(entry.getKey());
count++;
}
Expand Down Expand Up @@ -381,4 +381,4 @@ private static String encryptRSA(String plainText, String base64PublicKey)
return encrypted;

}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,18 @@
import ewha.lux.once.domain.card.dto.Place;
import ewha.lux.once.domain.card.dto.GoogleMapPlaceResponseDto;
import ewha.lux.once.domain.card.entity.OwnedCard;
import ewha.lux.once.domain.home.dto.OpenaiChatRequest;
import ewha.lux.once.domain.home.dto.OpenaiChatResponse;
import ewha.lux.once.domain.home.entity.Favorite;
import ewha.lux.once.domain.user.entity.Users;
import ewha.lux.once.global.common.CustomException;
import ewha.lux.once.global.common.ResponseCode;
import ewha.lux.once.global.repository.FavoriteRepository;
import ewha.lux.once.global.repository.OwnedCardRepository;
import ewha.lux.once.global.repository.UsersRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
Expand All @@ -30,58 +35,41 @@ public class CODEFAsyncService {
private final CODEFAPIService codefapi;
private final FavoriteRepository favoriteRepository;
private final UsersRepository usersRepository;
private final RestTemplate restTemplate;
// private final RestTemplate restTemplate;
private final OwnedCardRepository ownedCardRepository;

@Value("${openai.api.url}")
private String apiUrl;

@Qualifier("openaiRestTemplate")
@Autowired
private RestTemplate restTemplate;

@Async
public void saveFavorite(String code, String connectedId, OwnedCard ownedCard, Users nowUser, String cardNo) throws CustomException {
// // 승인 내역 조회 -> 단골 가게 카드별 5개
// List<String> favorites = codefapi.GetHistory(code,connectedId,ownedCard.getCard().getName(),cardNo);
//
// Map<String, Store> existingStores = storeRepository.findByNameIn(favorites.stream()
// .map(favorite -> favorite.split("#")[0])
// .collect(Collectors.toList()))
// .stream()
// .collect(Collectors.toMap(Store::getName, Function.identity()));
//
// List<Favorite> newFavorites = new ArrayList<>();
// for (String favorite : favorites) {
// String[] parts = favorite.split("#");
// String storeName = parts[0];
// String storeAddr = (parts.length > 1) ? parts[1] : "";
//
// Store existingStore = existingStores.get(storeName);
// if (existingStore == null) {
// HashMap<String,Object> placeInfo = searchStoreAddr(storeName);
// if(storeAddr==""){
// storeAddr = (String) placeInfo.get("formattedAddress");
// }
// Store store = Store.builder()
// .name(storeName)
// .address(storeAddr)
// .build();
//
// if(placeInfo.get("x") != null && placeInfo.get("y") != null) {
// double x = (double) placeInfo.get("x");
// double y = (double) placeInfo.get("y");
// store.setX(x);
// store.setY(y);
// }
// storeRepository.save(store);
//
// newFavorites.add(Favorite.builder()
// .store(store)
// .users(nowUser)
// .build());
// } else {
// if (!favoriteRepository.existsByStoreAndUsers(existingStore, nowUser)) {
// newFavorites.add(Favorite.builder()
// .store(existingStore)
// .users(nowUser)
// .build());
// }
// }
// }
// favoriteRepository.saveAll(newFavorites);
// 승인 내역 조회 -> 단골 가게 카드별 10개
List<String> favorites = codefapi.GetHistory(code,connectedId,ownedCard.getCard().getName(),cardNo);

String system ="입력받은 가맹점명에서 브랜드 이름을 찾아서 뽑아줘. 출력은 단어만, 알아낼 수 없다면 null을 반환해줘.";
for (String keyword : favorites){
OpenaiChatRequest request = new OpenaiChatRequest("gpt-4-turbo", system, keyword);
OpenaiChatResponse response = restTemplate.postForObject(apiUrl, request, OpenaiChatResponse.class);
if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
throw new CustomException(ResponseCode.FAILED_TO_OPENAI);
}
String result = response.getChoices().get(0).getMessage().getContent();
System.out.println(result);
if (!"null".equals(result)) {
boolean exists = favoriteRepository.existsByNameAndUsers(result,nowUser);
if (!exists) {
Favorite favorite = Favorite.builder()
.users(nowUser)
.name(result)
.build();
favoriteRepository.save(favorite);
}
}
}
}
@Async
public void deleteConnectedID(Users nowUser,OwnedCard ownedCard) throws CustomException {
Expand Down Expand Up @@ -148,4 +136,4 @@ public void updateOwnedCardsPerformanceCodef(Users nowUser)throws CustomExceptio
}
}
}
}
}
Loading
Loading