From ea7cce2e22a411c7667a6d86396cc7f3eb8d609a Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Fri, 3 Nov 2023 01:48:31 +0900 Subject: [PATCH 01/16] =?UTF-8?q?:sparkles:=20feat:=20=EC=9E=84=EC=8B=9C?= =?UTF-8?q?=20=EC=A0=90=EC=88=98=20=EA=B3=84=EC=82=B0=20=EB=B0=8F=20?= =?UTF-8?q?=EA=B7=B8=EB=9E=98=ED=94=84=20=EB=8D=B0=EC=9D=B4=ED=84=B0=20?= =?UTF-8?q?=EB=A1=9C=EC=A7=81=20=EA=B5=AC=ED=98=84=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 69 ++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/food/service/FoodService.java b/src/main/java/com/diareat/diareat/food/service/FoodService.java index be3f3cf..892fcb9 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -185,9 +185,76 @@ public ResponseFoodRankDto getWorstFoodByWeek(Long userId) { // 잔여 기능 구현 부분 - // 유저의 구체적인 점수 현황과 Best3, Worst3 조회 + @Transactional(readOnly = true) + public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId){ + validateUser(userId); + double kcalScore = 0.0; + double carbohydrateScore = 0.0; + double proteinScore = 0.0; + double fatScore = 0.0; + + User targetUser = userRepository.getReferenceById(userId); + + HashMap> nutritionSumOfUserFromMonday = getNutritionSumByDateMap(userId, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()); + for (LocalDate date : nutritionSumOfUserFromMonday.keySet()) { + // 해당 날짜에 먹은 음식들의 영양성분 총합 계산 + int totalKcal = nutritionSumOfUserFromMonday.get(date).stream().mapToInt(BaseNutrition::getKcal).sum(); + int totalCarbohydrate = nutritionSumOfUserFromMonday.get(date).stream().mapToInt(BaseNutrition::getCarbohydrate).sum(); + int totalProtein = nutritionSumOfUserFromMonday.get(date).stream().mapToInt(BaseNutrition::getProtein).sum(); + int totalFat = nutritionSumOfUserFromMonday.get(date).stream().mapToInt(BaseNutrition::getFat).sum(); + + // 기준섭취량 대비 섭취 비율에 매핑되는 식습관 점수 계산 + proteinScore += calculateNutriRatioAndScore(totalProtein, targetUser.getBaseNutrition().getProtein(), 0); + fatScore += calculateNutriRatioAndScore(totalFat, targetUser.getBaseNutrition().getFat(), 1); + carbohydrateScore += calculateNutriRatioAndScore(totalCarbohydrate, targetUser.getBaseNutrition().getCarbohydrate(), 1); + kcalScore += calculateNutriRatioAndScore(totalKcal, targetUser.getBaseNutrition().getKcal(), 1); + } + + List simpleBestFoodList = getBestFoodByWeek(userId).getRankFoodList().stream() + .map(food -> ResponseSimpleFoodDto.from(getFoodById(food.getFoodId()))).collect(Collectors.toList()); + + List simpleWorstFoodList = getWorstFoodByWeek(userId).getRankFoodList().stream() + .map(food -> ResponseSimpleFoodDto.from(getFoodById(food.getFoodId()))).collect(Collectors.toList()); + + return ResponseScoreBestWorstDto.of(kcalScore, carbohydrateScore, proteinScore, fatScore, kcalScore + carbohydrateScore + proteinScore + fatScore, simpleBestFoodList, simpleWorstFoodList); + } + + // 유저의 일기 분석 그래프 데이터 및 식습관 totalScore 조회 + @Transactional(readOnly = true) + public ResponseAnalysisDto getAnalysisOfUser(Long userId){ + validateUser(userId); + User user = userRepository.getReferenceById(userId); + + HashMap> nutritionSumOfUserByWeek = getNutritionSumByDateMap(userId, LocalDate.now().minusWeeks(1), LocalDate.now()); + double totalScore = calculateUserScoreThisWeek(user, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()).getTotalScore(); + + + List calorieLastSevenDays = new ArrayList<>(); + List calorieLastFourWeek = new ArrayList<>(); + List carbohydrateLastSevenDays = new ArrayList<>(); + List carbohydrateLastFourWeek = new ArrayList<>(); + List proteinLastSevenDays = new ArrayList<>(); + List proteinLastFourWeek = new ArrayList<>(); + List fatLastSevenDays = new ArrayList<>(); + List fatLastFourWeek = new ArrayList<>(); + + for (LocalDate date : nutritionSumOfUserByWeek.keySet()) { + int totalKcal = nutritionSumOfUserByWeek.get(date).stream().mapToInt(BaseNutrition::getKcal).sum(); + int totalCarbohydrate = nutritionSumOfUserByWeek.get(date).stream().mapToInt(BaseNutrition::getCarbohydrate).sum(); + int totalProtein = nutritionSumOfUserByWeek.get(date).stream().mapToInt(BaseNutrition::getProtein).sum(); + int totalFat = nutritionSumOfUserByWeek.get(date).stream().mapToInt(BaseNutrition::getFat).sum(); + + calorieLastSevenDays.add((double) totalKcal); + carbohydrateLastSevenDays.add((double) totalCarbohydrate); + proteinLastSevenDays.add((double) totalProtein); + fatLastSevenDays.add((double) totalFat); + } + + + } + @Cacheable(value = "ResponseRankUserDto", key = "#userId", cacheManager = "diareatCacheManager") From c5ccc1e00b28b2aa4a13789e38524f809a5f7373 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sat, 4 Nov 2023 21:47:59 +0900 Subject: [PATCH 02/16] =?UTF-8?q?:sparkles:=20feat:=20=EB=A1=9C=EC=A7=81?= =?UTF-8?q?=EC=9D=98=20=EA=B3=BC=EB=8F=84=ED=95=9C=20=EB=B3=B5=EC=9E=A1?= =?UTF-8?q?=EC=84=B1=EC=9C=BC=EB=A1=9C=20=EC=9D=B8=ED=95=B4=20Best,=20Wors?= =?UTF-8?q?t=20=EC=9D=8C=EC=8B=9D=20dto=20=EC=88=98=EC=A0=95=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ResponseFoodDto -> ResponseSimpleFoodDto --- .../diareat/food/dto/ResponseFoodRankDto.java | 4 +- .../diareat/food/service/FoodService.java | 28 ++++++------- .../diareat/service/FoodServiceTest.java | 42 ++++++++++++++++++- 3 files changed, 56 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java index 03d74b8..32101a3 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java @@ -14,11 +14,11 @@ public class ResponseFoodRankDto { private Long userId; - private List rankFoodList; + private List rankFoodList; private LocalDate startDate; //해당 날짜로부터 7일전까지 private boolean isBest; //isBest = true 이면 Best 3, false 이면 Worst 3 - public static ResponseFoodRankDto of(Long userId, List rankFoodList, LocalDate startDate, boolean isBest) { + public static ResponseFoodRankDto of(Long userId, List rankFoodList, LocalDate startDate, boolean isBest) { return new ResponseFoodRankDto(userId, rankFoodList, startDate, isBest); } } diff --git a/src/main/java/com/diareat/diareat/food/service/FoodService.java b/src/main/java/com/diareat/diareat/food/service/FoodService.java index 892fcb9..6a3d5d7 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -153,8 +153,9 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId) { //사용한 기준은, 고단백과 저지방의 점수 반영 비율을 7:3으로 측정하고, 단백질량이 높을 수록, 지방량이 낮을 수록 점수가 높음. 이후, 내림차순 정렬 // ** Best 3 기준 논의 필요 ** - List top3FoodsDtoList = top3Foods.stream() - .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getDate(), food.getTime(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); + List top3FoodsDtoList = top3Foods.stream() + .map(food -> ResponseSimpleFoodDto.of(food.getName(), food.getBaseNutrition().getKcal(), food.getBaseNutrition().getCarbohydrate(), + food.getBaseNutrition().getProtein(), food.getBaseNutrition().getFat(), food.getDate())).collect(Collectors.toList()); return ResponseFoodRankDto.of(userId, top3FoodsDtoList, endDate, true); } @@ -176,25 +177,27 @@ public ResponseFoodRankDto getWorstFoodByWeek(Long userId) { // ** 이점은 논의가 필요할 듯? ** // 우선 임시로 지방 비율을 높게 설정 - List worst3FoodDtoList = worst3Foods.stream() - .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getDate(), food.getTime(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); - + List worst3FoodDtoList = worst3Foods.stream() + .map(food -> ResponseSimpleFoodDto.of(food.getName(), food.getBaseNutrition().getKcal(), food.getBaseNutrition().getCarbohydrate(), + food.getBaseNutrition().getProtein(), food.getBaseNutrition().getFat(), food.getDate())).collect(Collectors.toList()); return ResponseFoodRankDto.of(userId, worst3FoodDtoList, endDate, false); } // 잔여 기능 구현 부분 + //유저의 식습관 점수 및 Best 3와 Worst 3 계산 @Transactional(readOnly = true) public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId){ - validateUser(userId); + validateUser(userId); //유저 객체 검증 double kcalScore = 0.0; double carbohydrateScore = 0.0; double proteinScore = 0.0; double fatScore = 0.0; - User targetUser = userRepository.getReferenceById(userId); + User targetUser = userRepository.getReferenceById(userId); //검증된 id로 유저 객체 불러오기 + //월요일부터 지금까지의 음식 정보 불러오기 HashMap> nutritionSumOfUserFromMonday = getNutritionSumByDateMap(userId, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()); for (LocalDate date : nutritionSumOfUserFromMonday.keySet()) { // 해당 날짜에 먹은 음식들의 영양성분 총합 계산 @@ -210,11 +213,9 @@ public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId kcalScore += calculateNutriRatioAndScore(totalKcal, targetUser.getBaseNutrition().getKcal(), 1); } - List simpleBestFoodList = getBestFoodByWeek(userId).getRankFoodList().stream() - .map(food -> ResponseSimpleFoodDto.from(getFoodById(food.getFoodId()))).collect(Collectors.toList()); - - List simpleWorstFoodList = getWorstFoodByWeek(userId).getRankFoodList().stream() - .map(food -> ResponseSimpleFoodDto.from(getFoodById(food.getFoodId()))).collect(Collectors.toList()); + //Dto의 형식에 맞게 Best3와 Worst3 음식 계산 + List simpleBestFoodList = getBestFoodByWeek(userId).getRankFoodList(); + List simpleWorstFoodList = getWorstFoodByWeek(userId).getRankFoodList(); return ResponseScoreBestWorstDto.of(kcalScore, carbohydrateScore, proteinScore, fatScore, kcalScore + carbohydrateScore + proteinScore + fatScore, simpleBestFoodList, simpleWorstFoodList); } @@ -251,8 +252,7 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId){ proteinLastSevenDays.add((double) totalProtein); fatLastSevenDays.add((double) totalFat); } - - + return null; } diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index d44077f..6bd9a14 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -9,6 +9,7 @@ import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; import com.diareat.diareat.user.dto.response.ResponseRankUserDto; +import com.diareat.diareat.user.dto.response.ResponseSimpleUserDto; import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; import org.junit.jupiter.api.DisplayName; @@ -282,7 +283,7 @@ void getBest3FoodTest() { // when ResponseFoodRankDto response = foodService.getBestFoodByWeek(user.getId()); - List top3Foods = response.getRankFoodList(); + List top3Foods = response.getRankFoodList(); // then assertEquals(3, top3Foods.size()); @@ -309,7 +310,7 @@ void getWorst3FoodsTest() { // when ResponseFoodRankDto response = foodService.getWorstFoodByWeek(user.getId()); - List top3Foods = response.getRankFoodList(); + List top3Foods = response.getRankFoodList(); // then assertEquals(3, top3Foods.size()); @@ -357,4 +358,41 @@ void getUserRankByWeek() { verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(eq(1L), any(LocalDate.class), any(LocalDate.class)); verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(eq(2L), any(LocalDate.class), any(LocalDate.class)); } + + @Test + void testGetScoreOfUserWithBestAndWorstFoods(){ + // given + User user = User.createUser("testUser", "testImage","testPassword", 1, 180, 80, 18, BaseNutrition.createNutrition(2000,400,100,50)); + Food food1 = Food.createFood( "Food1", user, BaseNutrition.createNutrition(100, 100 ,10, 1)); + Food food2 = Food.createFood( "Food2", user, BaseNutrition.createNutrition(100, 100 ,8, 2)); + Food food3 = Food.createFood( "Food3", user, BaseNutrition.createNutrition(100, 100 ,6, 3)); + Food food4 = Food.createFood( "Food4", user, BaseNutrition.createNutrition(100, 100 ,4, 4)); + Food food5 = Food.createFood( "Food5", user, BaseNutrition.createNutrition(100, 100 ,2, 5)); + user.setId(1L); + + List foodList = List.of(food1, food2, food3, food4, food5); + + given(userRepository.existsById(user.getId())).willReturn(true); + given(userRepository.getReferenceById(any(Long.class))).willReturn(user); + given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(foodList); + + // when + ResponseScoreBestWorstDto response = foodService.getScoreOfUserWithBestAndWorstFoods(user.getId()); + List top3Foods = response.getBest(); + List worst3Foods = response.getWorst(); + double totalScore = response.getTotalScore(); + double calorieScore = response.getCalorieScore(); + double carbohydrateScore = response.getCarbohydrateScore(); + double proteinScore = response.getProteinScore(); + double fatScore = response.getFatScore(); + + // then + assertEquals(3, top3Foods.size()); + assertEquals(3, worst3Foods.size()); + assertEquals(174.3, totalScore); + assertEquals(27.750000000000004, calorieScore); + assertEquals(83.25000000000001, carbohydrateScore); + assertEquals(30.0, proteinScore); + assertEquals(33.300000000000004, fatScore); + } } From 1c100ffced8bc7bae6a199f72e2c59a7384ea912 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 5 Nov 2023 03:13:22 +0900 Subject: [PATCH 03/16] =?UTF-8?q?:sparkles:=20feat:=20=EC=9C=A0=EC=A0=80?= =?UTF-8?q?=20=EA=B8=B0=EB=A1=9D=20=EB=B6=84=EC=84=9D=20=EB=B0=8F=20totals?= =?UTF-8?q?core=20=EA=B5=AC=ED=98=84=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/service/FoodService.java b/src/main/java/com/diareat/diareat/food/service/FoodService.java index 6a3d5d7..27bfd81 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -133,7 +133,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusMonths(1), endDate); return calculateNutritionSumAndRatio(userId, foodList, endDate, 30); } @@ -199,6 +199,8 @@ public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId //월요일부터 지금까지의 음식 정보 불러오기 HashMap> nutritionSumOfUserFromMonday = getNutritionSumByDateMap(userId, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()); + ResponseNutritionSumByDateDto nutritionSumOfUserFromLastMonth = getNutritionSumByMonth(userId); + for (LocalDate date : nutritionSumOfUserFromMonday.keySet()) { // 해당 날짜에 먹은 음식들의 영양성분 총합 계산 int totalKcal = nutritionSumOfUserFromMonday.get(date).stream().mapToInt(BaseNutrition::getKcal).sum(); @@ -229,7 +231,9 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId){ User user = userRepository.getReferenceById(userId); HashMap> nutritionSumOfUserByWeek = getNutritionSumByDateMap(userId, LocalDate.now().minusWeeks(1), LocalDate.now()); - double totalScore = calculateUserScoreThisWeek(user, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()).getTotalScore(); + HashMap> nutritionSumOfUserByMonth = getNutritionSumByDateMap(userId, LocalDate.now().minusMonths(1), LocalDate.now()); + + double totalWeekScore = calculateUserScoreThisWeek(user, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()).getTotalScore(); List calorieLastSevenDays = new ArrayList<>(); @@ -241,6 +245,7 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId){ List fatLastSevenDays = new ArrayList<>(); List fatLastFourWeek = new ArrayList<>(); + //최근 7일의 식습관 for (LocalDate date : nutritionSumOfUserByWeek.keySet()) { int totalKcal = nutritionSumOfUserByWeek.get(date).stream().mapToInt(BaseNutrition::getKcal).sum(); int totalCarbohydrate = nutritionSumOfUserByWeek.get(date).stream().mapToInt(BaseNutrition::getCarbohydrate).sum(); @@ -252,7 +257,21 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId){ proteinLastSevenDays.add((double) totalProtein); fatLastSevenDays.add((double) totalFat); } - return null; + + //최근 한달간의 식습관 + for (LocalDate date : nutritionSumOfUserByMonth.keySet()) { + int totalKcal = nutritionSumOfUserByMonth.get(date).stream().mapToInt(BaseNutrition::getKcal).sum(); + int totalCarbohydrate = nutritionSumOfUserByMonth.get(date).stream().mapToInt(BaseNutrition::getCarbohydrate).sum(); + int totalProtein = nutritionSumOfUserByMonth.get(date).stream().mapToInt(BaseNutrition::getProtein).sum(); + int totalFat = nutritionSumOfUserByMonth.get(date).stream().mapToInt(BaseNutrition::getFat).sum(); + + calorieLastFourWeek.add((double) totalKcal); + carbohydrateLastFourWeek.add((double) totalCarbohydrate); + proteinLastFourWeek.add((double) totalProtein); + fatLastFourWeek.add((double) totalFat); + } + + return ResponseAnalysisDto.of(totalWeekScore, calorieLastSevenDays, calorieLastFourWeek, carbohydrateLastSevenDays, carbohydrateLastFourWeek, proteinLastSevenDays, proteinLastFourWeek, fatLastSevenDays, fatLastFourWeek); } From 90477d6667a2eab9e43d1bf2a23601958aac6bee Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 6 Nov 2023 18:32:28 +0900 Subject: [PATCH 04/16] =?UTF-8?q?:sparkles:=20feat:=20FoodServiceTest?= =?UTF-8?q?=EB=A5=BC=20=EC=9C=84=ED=95=9C=20setDate()=20=EC=B6=94=EA=B0=80?= =?UTF-8?q?=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/food/domain/Food.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/diareat/diareat/food/domain/Food.java b/src/main/java/com/diareat/diareat/food/domain/Food.java index 8d9f9e2..639ef69 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -57,4 +57,6 @@ public boolean isFavorite() { } public void setId(long id) {this.id = id;} + + public void setDate(LocalDate date) {this.date = date;} //food test를 위한 date } From f10745217d51ced62416cc94c77672e41c04d946 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 6 Nov 2023 18:47:31 +0900 Subject: [PATCH 05/16] =?UTF-8?q?:sparkles:=20feat:=20=EB=82=A0=EC=A7=9C?= =?UTF-8?q?=EB=B3=84=201=EC=A3=BC,=20=ED=95=9C=EB=8B=AC=20=EC=9D=8C?= =?UTF-8?q?=EC=8B=9D=20=EC=A0=95=EB=A0=AC=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/food/service/FoodService.java b/src/main/java/com/diareat/diareat/food/service/FoodService.java index 27bfd81..d8625a8 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -230,12 +230,23 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId){ validateUser(userId); User user = userRepository.getReferenceById(userId); + //최근 1주간 유저가 먹은 음식들의 날짜별 HashMap HashMap> nutritionSumOfUserByWeek = getNutritionSumByDateMap(userId, LocalDate.now().minusWeeks(1), LocalDate.now()); - HashMap> nutritionSumOfUserByMonth = getNutritionSumByDateMap(userId, LocalDate.now().minusMonths(1), LocalDate.now()); + HashMap> nutritionSumOfUserByMonth = getNutritionSumByDateMap(userId, LocalDate.now().minusWeeks(3).with(DayOfWeek.MONDAY), LocalDate.now()); double totalWeekScore = calculateUserScoreThisWeek(user, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()).getTotalScore(); + //날짜 기준으로 정렬 (가장 최근 날짜가 맨 앞으로 오도록) + nutritionSumOfUserByMonth = nutritionSumOfUserByMonth.entrySet().stream() + .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new)); + + nutritionSumOfUserByMonth = nutritionSumOfUserByMonth.entrySet().stream() + .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new)); + + List calorieLastSevenDays = new ArrayList<>(); List calorieLastFourWeek = new ArrayList<>(); List carbohydrateLastSevenDays = new ArrayList<>(); @@ -258,6 +269,7 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId){ fatLastSevenDays.add((double) totalFat); } + //최근 한달간의 식습관 for (LocalDate date : nutritionSumOfUserByMonth.keySet()) { int totalKcal = nutritionSumOfUserByMonth.get(date).stream().mapToInt(BaseNutrition::getKcal).sum(); @@ -271,6 +283,8 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId){ fatLastFourWeek.add((double) totalFat); } + totalWeekScore = Math.round(totalWeekScore * 100.0) / 100.0; //3번째 자리에서 반올림 + return ResponseAnalysisDto.of(totalWeekScore, calorieLastSevenDays, calorieLastFourWeek, carbohydrateLastSevenDays, carbohydrateLastFourWeek, proteinLastSevenDays, proteinLastFourWeek, fatLastSevenDays, fatLastFourWeek); } From ca114f57a54b20afec7e226cd8d50a4267c17679 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 6 Nov 2023 18:47:54 +0900 Subject: [PATCH 06/16] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20foodserv?= =?UTF-8?q?icetest=20=EA=B5=AC=ED=98=84=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/FoodServiceTest.java | 104 ++++++++++++++++-- 1 file changed, 95 insertions(+), 9 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 6bd9a14..8517f5b 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -20,6 +20,7 @@ import org.mockito.junit.jupiter.MockitoExtension; +import java.time.DayOfWeek; import java.time.LocalDate; import java.util.List; import java.util.Optional; @@ -362,18 +363,19 @@ void getUserRankByWeek() { @Test void testGetScoreOfUserWithBestAndWorstFoods(){ // given - User user = User.createUser("testUser", "testImage","testPassword", 1, 180, 80, 18, BaseNutrition.createNutrition(2000,400,100,50)); - Food food1 = Food.createFood( "Food1", user, BaseNutrition.createNutrition(100, 100 ,10, 1)); - Food food2 = Food.createFood( "Food2", user, BaseNutrition.createNutrition(100, 100 ,8, 2)); - Food food3 = Food.createFood( "Food3", user, BaseNutrition.createNutrition(100, 100 ,6, 3)); - Food food4 = Food.createFood( "Food4", user, BaseNutrition.createNutrition(100, 100 ,4, 4)); - Food food5 = Food.createFood( "Food5", user, BaseNutrition.createNutrition(100, 100 ,2, 5)); + User user = User.createUser("testUser", "testImage","testPassword", 1, 180, 80, 18, BaseNutrition.createNutrition(2000,400,100,100)); + Food food1 = Food.createFood( "Food1", user, BaseNutrition.createNutrition(100, 100 ,10, 44)); + Food food2 = Food.createFood( "Food2", user, BaseNutrition.createNutrition(100, 100 ,20, 33)); + Food food3 = Food.createFood( "Food3", user, BaseNutrition.createNutrition(100, 100 ,30, 22)); + Food food4 = Food.createFood( "Food4", user, BaseNutrition.createNutrition(100, 100 ,40, 11)); + Food food5 = Food.createFood( "Food5", user, BaseNutrition.createNutrition(100, 100 ,50, 55)); user.setId(1L); List foodList = List.of(food1, food2, food3, food4, food5); given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.getReferenceById(any(Long.class))).willReturn(user); + given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(foodList); // when @@ -389,10 +391,94 @@ void testGetScoreOfUserWithBestAndWorstFoods(){ // then assertEquals(3, top3Foods.size()); assertEquals(3, worst3Foods.size()); - assertEquals(174.3, totalScore); + assertEquals(249.85, totalScore); assertEquals(27.750000000000004, calorieScore); assertEquals(83.25000000000001, carbohydrateScore); - assertEquals(30.0, proteinScore); - assertEquals(33.300000000000004, fatScore); + assertEquals(100.0, proteinScore); + assertEquals(38.85, fatScore); + } + + @Test + void testGetAnalysisOfUser(){ + // given + User user = User.createUser("testUser", "testImage","testPassword", 1, 180, 80, 18, BaseNutrition.createNutrition(2000,400,100,50)); + Food food1 = Food.createFood( "Food1", user, BaseNutrition.createNutrition(100, 100 ,10, 1)); + Food food1_1 = Food.createFood( "Food1_1", user, BaseNutrition.createNutrition(130, 100 ,8, 2)); + Food food2 = Food.createFood( "Food2", user, BaseNutrition.createNutrition(150, 100 ,8, 2)); + Food food3 = Food.createFood( "Food3", user, BaseNutrition.createNutrition(200, 100 ,6, 3)); + Food food4 = Food.createFood( "Food4", user, BaseNutrition.createNutrition(250, 100 ,4, 4)); + Food food5 = Food.createFood( "Food5", user, BaseNutrition.createNutrition(300, 100 ,2, 5)); + user.setId(1L); + + food1.setDate(LocalDate.now()); + food1_1.setDate(LocalDate.now()); + food2.setDate(LocalDate.now().minusDays(2)); + food3.setDate(LocalDate.now().minusDays(3)); + food4.setDate(LocalDate.now().minusWeeks(1)); + food5.setDate(LocalDate.now().minusWeeks(2)); + + + + List foodListOfWeek = List.of(food1,food1_1, food2, food3); + List foodListOfMonth = List.of(food1, food1_1,food2, food3, food4, food5); + + + + given(userRepository.existsById(user.getId())).willReturn(true); + given(userRepository.getReferenceById(any(Long.class))).willReturn(user); + given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().minusWeeks(1), LocalDate.now())).willReturn(foodListOfWeek); + given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().minusWeeks(3).with(DayOfWeek.MONDAY), LocalDate.now())).willReturn(foodListOfMonth); + given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now())).willReturn(foodListOfWeek); + + + // when + ResponseAnalysisDto response = foodService.getAnalysisOfUser(user.getId()); + + double totalScore = response.getTotalScore(); + List calorieLastSevenDays = response.getCalorieLastSevenDays(); + List proteinLastSevenDays = response.getProteinLastSevenDays(); + List calorieLastFourWeeks = response.getCalorieLastFourWeek(); + List proteinLastFourWeeks = response.getProteinLastFourWeek(); + + + // then + assertEquals(192.95, totalScore); + + //갯수 확인 + assertEquals(3, calorieLastSevenDays.size()); //일주일동안의 음식 -> 3개 + assertEquals(5, calorieLastFourWeeks.size()); //한달동안의 음식 -> 5개 + + + //날짜 정렬 확인 (1주) + assertEquals(230, calorieLastSevenDays.get(0)); + assertEquals(18, proteinLastSevenDays.get(0)); + + assertEquals(150, calorieLastSevenDays.get(1)); + assertEquals(8, proteinLastSevenDays.get(1)); + + assertEquals(200, calorieLastSevenDays.get(2)); + assertEquals(6, proteinLastSevenDays.get(2)); + + //날짜 정렬 확인 (2주) + assertEquals(230, calorieLastFourWeeks.get(0)); + assertEquals(18, proteinLastFourWeeks.get(0)); + + assertEquals(150, calorieLastFourWeeks.get(1)); + assertEquals(8, proteinLastFourWeeks.get(1)); + + assertEquals(200, calorieLastFourWeeks.get(2)); + assertEquals(6, proteinLastFourWeeks.get(2)); + + assertEquals(250, calorieLastFourWeeks.get(3)); + assertEquals(4, proteinLastFourWeeks.get(3)); + + assertEquals(300, calorieLastFourWeeks.get(4)); + assertEquals(2, proteinLastFourWeeks.get(4)); + + + verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().minusWeeks(1), LocalDate.now()); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().minusWeeks(3).with(DayOfWeek.MONDAY), LocalDate.now()); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()); + } } From 08e45612164ae17f164267878b1f14537e6a1072 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 6 Nov 2023 18:53:38 +0900 Subject: [PATCH 07/16] =?UTF-8?q?:fire:=20feat:=20=EC=9D=BC=EA=B8=B0=20?= =?UTF-8?q?=EB=B6=84=EC=84=9D=EC=97=90=20best,=20worst=20=EC=9D=8C?= =?UTF-8?q?=EC=8B=9D=20=EB=B0=98=ED=99=98=20=EC=9C=84=ED=95=9C=20=EA=B8=B0?= =?UTF-8?q?=EC=A1=B4=20best,=20worst=20api=20=EC=82=AD=EC=A0=9C=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/controller/FoodController.java | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/controller/FoodController.java b/src/main/java/com/diareat/diareat/food/controller/FoodController.java index 5e7d6cc..17c0926 100644 --- a/src/main/java/com/diareat/diareat/food/controller/FoodController.java +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -111,18 +111,5 @@ public ApiResponse getNutritionSumByMonth(@PathVa } - //7일간의 Best 3 조회 - @Operation(summary = "[음식] 최근 7일 간 먹은 Top3 음식 조회",description = "최근 7일 간 유저가 먹은 음식들 중에서 Top3에 해당한 음식들을 조회합니다.") - @GetMapping("/{userId}/best") - public ApiResponse getBestFoodByWeek(@PathVariable Long userId){ - return ApiResponse.success(foodService.getBestFoodByWeek(userId),ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); - } - - //7일간의 Worst 3 조회 - @Operation(summary = "[음식] 최근 7일 간 먹은 Worst3 음식 조회",description = "최근 7일 간 유저가 먹은 음식들 중에서 Worst3에 해당한 음식들을 조회합니다.") - @GetMapping("/{userId}/worst") - public ApiResponse getWorstFoodByWeek(@PathVariable Long userId){ - return ApiResponse.success(foodService.getWorstFoodByWeek(userId),ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); - } } From 251c370a56426ad09ac6e3c5667f13715704d489 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 6 Nov 2023 19:09:41 +0900 Subject: [PATCH 08/16] =?UTF-8?q?:recycle:=20refactor:=20=EC=A0=90?= =?UTF-8?q?=EC=88=98=20=EA=B3=84=EC=82=B0=20=EB=A1=9C=EC=A7=81=20=EA=B0=84?= =?UTF-8?q?=EC=86=8C=ED=99=94=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/service/FoodService.java b/src/main/java/com/diareat/diareat/food/service/FoodService.java index d8625a8..372b10c 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -190,6 +190,7 @@ public ResponseFoodRankDto getWorstFoodByWeek(Long userId) { @Transactional(readOnly = true) public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId){ validateUser(userId); //유저 객체 검증 + double totalScore = 0.0; double kcalScore = 0.0; double carbohydrateScore = 0.0; double proteinScore = 0.0; @@ -197,29 +198,28 @@ public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId User targetUser = userRepository.getReferenceById(userId); //검증된 id로 유저 객체 불러오기 - //월요일부터 지금까지의 음식 정보 불러오기 - HashMap> nutritionSumOfUserFromMonday = getNutritionSumByDateMap(userId, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()); - ResponseNutritionSumByDateDto nutritionSumOfUserFromLastMonth = getNutritionSumByMonth(userId); + ResponseRankUserDto scoresOfUser = calculateUserScoreThisWeek(targetUser, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()); - for (LocalDate date : nutritionSumOfUserFromMonday.keySet()) { - // 해당 날짜에 먹은 음식들의 영양성분 총합 계산 - int totalKcal = nutritionSumOfUserFromMonday.get(date).stream().mapToInt(BaseNutrition::getKcal).sum(); - int totalCarbohydrate = nutritionSumOfUserFromMonday.get(date).stream().mapToInt(BaseNutrition::getCarbohydrate).sum(); - int totalProtein = nutritionSumOfUserFromMonday.get(date).stream().mapToInt(BaseNutrition::getProtein).sum(); - int totalFat = nutritionSumOfUserFromMonday.get(date).stream().mapToInt(BaseNutrition::getFat).sum(); + totalScore = scoresOfUser.getTotalScore(); + kcalScore = scoresOfUser.getCalorieScore(); + carbohydrateScore = scoresOfUser.getCarbohydrateScore(); + proteinScore = scoresOfUser.getProteinScore(); + fatScore = scoresOfUser.getFatScore(); - // 기준섭취량 대비 섭취 비율에 매핑되는 식습관 점수 계산 - proteinScore += calculateNutriRatioAndScore(totalProtein, targetUser.getBaseNutrition().getProtein(), 0); - fatScore += calculateNutriRatioAndScore(totalFat, targetUser.getBaseNutrition().getFat(), 1); - carbohydrateScore += calculateNutriRatioAndScore(totalCarbohydrate, targetUser.getBaseNutrition().getCarbohydrate(), 1); - kcalScore += calculateNutriRatioAndScore(totalKcal, targetUser.getBaseNutrition().getKcal(), 1); - } //Dto의 형식에 맞게 Best3와 Worst3 음식 계산 List simpleBestFoodList = getBestFoodByWeek(userId).getRankFoodList(); List simpleWorstFoodList = getWorstFoodByWeek(userId).getRankFoodList(); - return ResponseScoreBestWorstDto.of(kcalScore, carbohydrateScore, proteinScore, fatScore, kcalScore + carbohydrateScore + proteinScore + fatScore, simpleBestFoodList, simpleWorstFoodList); + //반올림 + totalScore = Math.round(totalScore * 100.0) / 100.0; + kcalScore = Math.round(kcalScore * 100.0) / 100.0; + carbohydrateScore = Math.round(carbohydrateScore * 100.0) / 100.0; + proteinScore = Math.round(proteinScore * 100.0) / 100.0; + fatScore = Math.round(fatScore * 100.0) / 100.0; + + + return ResponseScoreBestWorstDto.of(kcalScore, carbohydrateScore, proteinScore, fatScore, totalScore, simpleBestFoodList, simpleWorstFoodList); } @@ -283,7 +283,7 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId){ fatLastFourWeek.add((double) totalFat); } - totalWeekScore = Math.round(totalWeekScore * 100.0) / 100.0; //3번째 자리에서 반올림 + totalWeekScore = Math.round(totalWeekScore * 100.0) / 100.0; return ResponseAnalysisDto.of(totalWeekScore, calorieLastSevenDays, calorieLastFourWeek, carbohydrateLastSevenDays, carbohydrateLastFourWeek, proteinLastSevenDays, proteinLastFourWeek, fatLastSevenDays, fatLastFourWeek); } From a8e3b3c012cdae4c03f0f6b390fdab3cc7859649 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 6 Nov 2023 19:23:49 +0900 Subject: [PATCH 09/16] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EA=B8=B0=EB=8C=80=EA=B0=92=20?= =?UTF-8?q?=EB=B3=80=EA=B2=BD=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/FoodServiceTest.java | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 8517f5b..b011034 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -363,19 +363,22 @@ void getUserRankByWeek() { @Test void testGetScoreOfUserWithBestAndWorstFoods(){ // given - User user = User.createUser("testUser", "testImage","testPassword", 1, 180, 80, 18, BaseNutrition.createNutrition(2000,400,100,100)); - Food food1 = Food.createFood( "Food1", user, BaseNutrition.createNutrition(100, 100 ,10, 44)); - Food food2 = Food.createFood( "Food2", user, BaseNutrition.createNutrition(100, 100 ,20, 33)); - Food food3 = Food.createFood( "Food3", user, BaseNutrition.createNutrition(100, 100 ,30, 22)); - Food food4 = Food.createFood( "Food4", user, BaseNutrition.createNutrition(100, 100 ,40, 11)); - Food food5 = Food.createFood( "Food5", user, BaseNutrition.createNutrition(100, 100 ,50, 55)); + User user = User.createUser("testUser", "testImage","testPassword", 1, 180, 80, 18, BaseNutrition.createNutrition(2000,400,100,50)); + Food food1 = Food.createFood( "Food1", user, BaseNutrition.createNutrition(100, 100 ,10, 1)); + Food food1_1 = Food.createFood( "Food1_1", user, BaseNutrition.createNutrition(130, 100 ,8, 2)); + Food food2 = Food.createFood( "Food2", user, BaseNutrition.createNutrition(150, 100 ,8, 2)); + Food food3 = Food.createFood( "Food3", user, BaseNutrition.createNutrition(200, 100 ,6, 3)); user.setId(1L); - List foodList = List.of(food1, food2, food3, food4, food5); + food1.setDate(LocalDate.now()); + food1_1.setDate(LocalDate.now()); + food2.setDate(LocalDate.now().minusDays(2)); + food3.setDate(LocalDate.now().minusDays(3)); + + List foodList = List.of(food1, food1_1, food2, food3); given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.getReferenceById(any(Long.class))).willReturn(user); - given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(foodList); // when @@ -391,11 +394,11 @@ void testGetScoreOfUserWithBestAndWorstFoods(){ // then assertEquals(3, top3Foods.size()); assertEquals(3, worst3Foods.size()); - assertEquals(249.85, totalScore); - assertEquals(27.750000000000004, calorieScore); - assertEquals(83.25000000000001, carbohydrateScore); - assertEquals(100.0, proteinScore); - assertEquals(38.85, fatScore); + assertEquals(192.95, totalScore); + assertEquals(32.19, calorieScore); + assertEquals(111.0, carbohydrateScore); + assertEquals(32.0, proteinScore); + assertEquals(17.76, fatScore); } @Test From 79822da12e7ae01140c9cd660de56d7b41d9b903 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 6 Nov 2023 19:30:48 +0900 Subject: [PATCH 10/16] =?UTF-8?q?:sparkles:=20feat:=20=EB=9E=AD=ED=82=B9?= =?UTF-8?q?=20=EC=A1=B0=ED=9A=8C=20=EC=84=B1=EA=B3=B5=20Response=20Code=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/util/api/ResponseCode.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/diareat/diareat/util/api/ResponseCode.java b/src/main/java/com/diareat/diareat/util/api/ResponseCode.java index d80d3de..994fcd2 100644 --- a/src/main/java/com/diareat/diareat/util/api/ResponseCode.java +++ b/src/main/java/com/diareat/diareat/util/api/ResponseCode.java @@ -49,6 +49,8 @@ public enum ResponseCode { FOOD_FAVORITE_UPDATE_SUCCESS(HttpStatus.OK, true, "즐겨찾기 음식 수정 성공"), FOOD_FAVORITE_DELETE_SUCCESS(HttpStatus.OK, true, "즐겨찾기 음식 삭제 성공"), + FOOD_RANK_READ_SUCCESS(HttpStatus.OK, true, "식습관 점수 기반 랭킹 조회 성공"), + TOKEN_CHECK_SUCCESS(HttpStatus.OK, true, "토큰 검증 완료"), From 369d9d2488e401b3802e2f43fd7b7349673f1b4c Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 6 Nov 2023 19:31:18 +0900 Subject: [PATCH 11/16] =?UTF-8?q?:sparkles:=20feat:=20=EC=9E=94=EC=97=AC?= =?UTF-8?q?=20=EA=B8=B0=EB=8A=A5=20(=EC=8B=9D=EC=8A=B5=EA=B4=80=20?= =?UTF-8?q?=EC=A0=90=EC=88=98,=20best=20&=20worst,=20=EA=B7=B8=EB=9E=98?= =?UTF-8?q?=ED=94=84,=20=EB=9E=AD=ED=82=B9)=20api=20=EA=B5=AC=ED=98=84=20(?= =?UTF-8?q?#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../food/controller/FoodController.java | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/controller/FoodController.java b/src/main/java/com/diareat/diareat/food/controller/FoodController.java index 17c0926..c86a418 100644 --- a/src/main/java/com/diareat/diareat/food/controller/FoodController.java +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -2,10 +2,12 @@ import com.diareat.diareat.food.dto.*; import com.diareat.diareat.food.service.FoodService; +import com.diareat.diareat.user.dto.response.ResponseRankUserDto; import com.diareat.diareat.util.api.ApiResponse; import com.diareat.diareat.util.api.ResponseCode; import io.swagger.annotations.Api; import io.swagger.v3.oas.annotations.Operation; +import lombok.Getter; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; @@ -93,23 +95,42 @@ public ApiResponse getNutritionSumByDate(@PathVar @RequestParam int mm, @RequestParam int dd){ LocalDate date = LocalDate.of(yy,mm,dd); - return ApiResponse.success(foodService.getNutritionSumByDate(userId,date),ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); + return ApiResponse.success(foodService.getNutritionSumByDate(userId,date),ResponseCode.FOOD_READ_SUCCESS.getMessage()); } //"" 7일간 총합 조회 @Operation(summary = "[음식] 최근 7일간 먹은 음식들의 영양성분 총합 조회",description = "최근 7일 간 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") @GetMapping("/{userId}/nutrition/recentWeek") public ApiResponse getNutritionSumByWeek(@PathVariable Long userId){ - return ApiResponse.success(foodService.getNutritionSumByWeek(userId),ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); + return ApiResponse.success(foodService.getNutritionSumByWeek(userId),ResponseCode.FOOD_READ_SUCCESS.getMessage()); } //"" 30일간 (1달간) 총합 조회 @Operation(summary = "[음식] 최근 한달 간 먹은 음식들의 영양성분 총합 조회",description = "최근 한달 간 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") @GetMapping("/{userId}/nutrition/recentMonth") public ApiResponse getNutritionSumByMonth(@PathVariable Long userId){ - return ApiResponse.success(foodService.getNutritionSumByMonth(userId),ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); + return ApiResponse.success(foodService.getNutritionSumByMonth(userId),ResponseCode.FOOD_READ_SUCCESS.getMessage()); } + //유저의 주간 식습관 점수와 best3, worst3 음식 조회 + @Operation(summary = "[음식] 유저의 주간 식습관 점수와 best3, worst3 음식 조회",description = "유저의 주간 식습관 점수와 best3, worst3 음식을 조회합니다.") + @GetMapping("/{userId}/score") + public ApiResponse getScoreOfUserWithBestAndWorstFoods(@PathVariable Long userId){ + return ApiResponse.success(foodService.getScoreOfUserWithBestAndWorstFoods(userId),ResponseCode.FOOD_READ_SUCCESS.getMessage()); + } + + //유저의 일기 분석 그래프 데이터 및 식습관 totalScore 조회 + @Operation(summary = "[음식] 유저의 일기 분석 그래프 데이터 및 주간 식습관 점수 조회",description = "유저의 일기 분석 그래프 데이터 및 식습관 점수를 조회합니다.") + @GetMapping("/{userId}/analysis") + public ApiResponse getAnalysisOfUser(@PathVariable Long userId){ + return ApiResponse.success(foodService.getAnalysisOfUser(userId),ResponseCode.FOOD_READ_SUCCESS.getMessage()); + } + //유저의 식습관 점수를 기반으로 한 주간 랭킹 조회 + @Operation(summary = "[음식] 유저의 식습관 점수를 기반으로 한 주간 랭킹 조회",description = "유저의 식습관 점수를 기반으로 한 주간 랭킹을 조회합니다. (팔로잉 상대 기반)") + @GetMapping("/{userId}/rank") + public ApiResponse> getUserRankByWeek(@PathVariable Long userId){ + return ApiResponse.success(foodService.getUserRankByWeek(userId),ResponseCode.FOOD_RANK_READ_SUCCESS.getMessage()); + } } From 6948b0907b2ae5291c2fc6468f0a834a6e916f68 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 6 Nov 2023 22:21:51 +0900 Subject: [PATCH 12/16] =?UTF-8?q?:sparkles:=20feat:=20ResponseFavoriteFood?= =?UTF-8?q?Dto=EC=97=90=EC=84=9C=20=EB=88=84=EB=9D=BD=EB=90=9C=20User=20Id?= =?UTF-8?q?=20=EC=86=8D=EC=84=B1=20=EC=B6=94=EA=B0=80=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/dto/ResponseFavoriteFoodDto.java | 6 ++++-- .../java/com/diareat/diareat/food/service/FoodService.java | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java index 3d33ca4..bbb4c06 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java @@ -9,17 +9,19 @@ @AllArgsConstructor public class ResponseFavoriteFoodDto { + private Long userId; private Long favoriteFoodId; private String name; private BaseNutrition baseNutrition; private int count; - public static ResponseFavoriteFoodDto of(Long favoriteFoodId, String name, BaseNutrition baseNutrition, int count) { - return new ResponseFavoriteFoodDto(favoriteFoodId, name, baseNutrition, count); + public static ResponseFavoriteFoodDto of(Long userId, Long favoriteFoodId, String name, BaseNutrition baseNutrition, int count) { + return new ResponseFavoriteFoodDto(userId, favoriteFoodId, name, baseNutrition, count); } public static ResponseFavoriteFoodDto from(FavoriteFood favoriteFood) { return new ResponseFavoriteFoodDto( + favoriteFood.getUser().getId(), favoriteFood.getId(), favoriteFood.getName(), favoriteFood.getBaseNutrition(), diff --git a/src/main/java/com/diareat/diareat/food/service/FoodService.java b/src/main/java/com/diareat/diareat/food/service/FoodService.java index 372b10c..ebd1626 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -88,7 +88,7 @@ public List getFavoriteFoodList(Long userId){ validateUser(userId); List foodList = favoriteFoodRepository.findAllByUserId(userId); return foodList.stream() - .map(favoriteFood -> ResponseFavoriteFoodDto.of(favoriteFood.getId(), favoriteFood.getName(), + .map(favoriteFood -> ResponseFavoriteFoodDto.of(favoriteFood.getUser().getId(),favoriteFood.getId(), favoriteFood.getName(), favoriteFood.getBaseNutrition(), favoriteFood.getCount())).collect(Collectors.toList()); } From 139b0ac4bb9fccf13dcad89b2879cc60d56c8a75 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 6 Nov 2023 22:57:40 +0900 Subject: [PATCH 13/16] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20FoodCont?= =?UTF-8?q?rollerTest=20=EA=B5=AC=ED=98=84=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/FoodControllerTest.java | 450 ++++++++++++++++++ 1 file changed, 450 insertions(+) create mode 100644 src/test/java/com/diareat/diareat/controller/FoodControllerTest.java diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java new file mode 100644 index 0000000..510995b --- /dev/null +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -0,0 +1,450 @@ +package com.diareat.diareat.controller; + +import com.diareat.diareat.food.controller.FoodController; +import com.diareat.diareat.food.domain.FavoriteFood; +import com.diareat.diareat.food.domain.Food; +import com.diareat.diareat.food.dto.*; +import com.diareat.diareat.food.service.FoodService; +import com.diareat.diareat.user.domain.BaseNutrition; +import com.diareat.diareat.user.domain.User; +import com.diareat.diareat.user.dto.response.ResponseRankUserDto; +import com.diareat.diareat.util.api.ApiResponse; +import com.diareat.diareat.util.api.ResponseCode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@WebMvcTest(controllers = FoodController.class) +public class FoodControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + @MockBean + private FoodService foodService; + + private final Long testUserId = 1L; + private final Long testFoodId = 2L; + private final Long testFavoriteFoodId = 3L; + private final ObjectMapper mapper = new ObjectMapper(); + + private final User testUser = User.createUser("test", "test", "test", 180, 70, 0, 20, BaseNutrition.createNutrition(2000, 300, 80, 80)); + private final Food testFood = Food.createFood("testFood", testUser, BaseNutrition.createNutrition(500, 50, 30, 10)); + private final FavoriteFood testFavoriteFood = FavoriteFood.createFavoriteFood("testFavoriteFood", testUser, BaseNutrition.createNutrition(500, 50, 30, 10)); + private final BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(500, 50, 30, 10); + + @BeforeEach + void setUp() { + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + testUser.setId(testUserId); + testFood.setId(testFoodId); + testFavoriteFood.setId(testFavoriteFoodId); + mapper.registerModule(new JavaTimeModule()); + } + + @DisplayName("음식 정보 저장") + @Test + @WithMockUser("test") + void testSaveFood() throws Exception { + //Given + CreateFoodDto createFoodDto = CreateFoodDto.of(testUserId, "test", testBaseNutrition, LocalDate.now()); + + when(foodService.saveFood(any(CreateFoodDto.class))).thenReturn(testFoodId); + ApiResponse expectedResponse = ApiResponse.success(foodService.saveFood(createFoodDto), ResponseCode.FOOD_CREATE_SUCCESS.getMessage()); + + + String json = mapper.writeValueAsString(createFoodDto); + + //When & Then + mockMvc.perform(MockMvcRequestBuilders + .post("/api/food/save") + .contentType(MediaType.APPLICATION_JSON) + .content(json) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data").value(expectedResponse.getData())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); + } + + + @DisplayName("음식 정보 날짜별 조회") + @Test + @WithMockUser("test") + void testGetFoodListByDate() throws Exception { + //Given + LocalDate date = LocalDate.now(); + + ResponseFoodDto food1 = ResponseFoodDto.of(testFoodId, testUserId,"test", LocalDate.now(), LocalTime.now(),testBaseNutrition,false); + + when(foodService.getFoodListByDate(any(Long.class), any(LocalDate.class))).thenReturn(List.of(food1)); + ApiResponse> expectedResponse = ApiResponse.success(List.of(food1), ResponseCode.FOOD_READ_SUCCESS.getMessage());; + + //When & Then + mockMvc.perform(MockMvcRequestBuilders + .get("/api/food/{userId}", testUserId) + .param("yy", String.valueOf(date.getYear())) + .param("mm", String.valueOf(date.getMonthValue())) + .param("dd", String.valueOf(date.getDayOfMonth())) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].name").value(expectedResponse.getData().get(0).getName())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].date").value(expectedResponse.getData().get(0).getDate().toString())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].time").value(expectedResponse.getData().get(0).getTime().toString())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].baseNutrition.kcal").value(expectedResponse.getData().get(0).getBaseNutrition().getKcal())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].baseNutrition.carbohydrate").value(expectedResponse.getData().get(0).getBaseNutrition().getCarbohydrate())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].baseNutrition.protein").value(expectedResponse.getData().get(0).getBaseNutrition().getProtein())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].baseNutrition.fat").value(expectedResponse.getData().get(0).getBaseNutrition().getFat())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); + } + + @DisplayName("음식 정보 수정") + @Test + @WithMockUser("test") + void testUpdateFood() throws Exception { + //Given + ApiResponse expectedResponse = ApiResponse.success(null, ResponseCode.FOOD_UPDATE_SUCCESS.getMessage()); + UpdateFoodDto updateFoodDto = UpdateFoodDto.of(testFoodId, testUserId, "testFood", testBaseNutrition); + String json = mapper.writeValueAsString(updateFoodDto); + + mockMvc.perform(MockMvcRequestBuilders + .post("/api/food/update") + .contentType(MediaType.APPLICATION_JSON) + .content(json) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); + + } + + @DisplayName("음식 정보 삭제") + @Test + @WithMockUser("test") + void testDeleteFood() throws Exception { + //Given + ApiResponse expectedResponse = ApiResponse.success(null, ResponseCode.FOOD_DELETE_SUCCESS.getMessage()); + + mockMvc.perform(MockMvcRequestBuilders + .delete("/api/food/{foodId}/delete", testFoodId) + .header("userId", testUserId) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); + } + + @DisplayName("즐겨찾기에 음식 저장") + @Test + @WithMockUser("test") + void testSaveFavoriteFood() throws Exception { + //Given + ApiResponse expectedResponse = ApiResponse.success(testFavoriteFoodId, ResponseCode.FOOD_FAVORITE_CREATE_SUCCESS.getMessage()); + CreateFavoriteFoodDto createFavoriteFoodDto = CreateFavoriteFoodDto.of(testFoodId, testUserId, "test", testBaseNutrition); + String json = mapper.writeValueAsString(createFavoriteFoodDto); + when(foodService.saveFavoriteFood(any(CreateFavoriteFoodDto.class))).thenReturn(testFavoriteFoodId); + + mockMvc.perform(MockMvcRequestBuilders + .post("/api/food/favorite") + .contentType(MediaType.APPLICATION_JSON) + .content(json) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data").value(expectedResponse.getData())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); + } + + @DisplayName("즐겨찾기 음식 리스트 반환") + @Test + @WithMockUser("test") + void testGetFavoriteFoodList() throws Exception { + //Given + ResponseFavoriteFoodDto food1 = ResponseFavoriteFoodDto.of(testUserId, testFavoriteFoodId,"test",testBaseNutrition,0); + + ApiResponse> expectedResponse = ApiResponse.success(List.of(food1), ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); + when(foodService.getFavoriteFoodList(any(Long.class))).thenReturn(List.of(food1)); + + //When & Then + mockMvc.perform(MockMvcRequestBuilders + .get("/api/food/favorite/{userId}", testUserId) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].name").value(expectedResponse.getData().get(0).getName())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].baseNutrition.kcal").value(expectedResponse.getData().get(0).getBaseNutrition().getKcal())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].baseNutrition.carbohydrate").value(expectedResponse.getData().get(0).getBaseNutrition().getCarbohydrate())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].baseNutrition.protein").value(expectedResponse.getData().get(0).getBaseNutrition().getProtein())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].baseNutrition.fat").value(expectedResponse.getData().get(0).getBaseNutrition().getFat())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); + } + + @DisplayName("즐겨찾기 음식 수정") + @Test + @WithMockUser("test") + void testUpdateFavoriteFood() throws Exception { + //Given + ApiResponse expectedResponse = ApiResponse.success(null, ResponseCode.FOOD_FAVORITE_UPDATE_SUCCESS.getMessage()); + UpdateFavoriteFoodDto updateFavoriteFoodDto = UpdateFavoriteFoodDto.of(testFavoriteFoodId, testUserId, "testFavoriteFood", testBaseNutrition); + String json = mapper.writeValueAsString(updateFavoriteFoodDto); + + mockMvc.perform(MockMvcRequestBuilders + .post("/api/food/favorite/update") + .contentType(MediaType.APPLICATION_JSON) + .content(json) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); + } + + @DisplayName("즐겨찾기 음식 삭제") + @Test + @WithMockUser("test") + void testDeleteFavoriteFood() throws Exception { + //Given + ApiResponse expectedResponse = ApiResponse.success(null, ResponseCode.FOOD_FAVORITE_DELETE_SUCCESS.getMessage()); + + mockMvc.perform(MockMvcRequestBuilders + .delete("/api/food/favorite/{favoriteFoodId}", testFavoriteFoodId) + .header("userId", testUserId) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); + } + + //특정 날짜에 먹은 음식들의 영양성분별 총합 조회 + @DisplayName("특정 날짜에 먹은 음식들의 영양성분별 총합 조회") + @Test + @WithMockUser("test") + void testGetNutritionSumByDate() throws Exception{ + //Given + LocalDate date = LocalDate.now(); + ResponseNutritionSumByDateDto responseNutritionSumByDateDto = ResponseNutritionSumByDateDto.of(testUserId,date,1 + ,500,100,50,50,0.2,0.3,0.4,0.5); + ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto,ResponseCode.FOOD_READ_SUCCESS.getMessage()); + when(foodService.getNutritionSumByDate(any(Long.class),any(LocalDate.class))).thenReturn(responseNutritionSumByDateDto); + + String json = mapper.writeValueAsString(responseNutritionSumByDateDto); + + //When + mockMvc.perform(MockMvcRequestBuilders + .get("/api/food/{userId}/nutrition", testUserId) + .param("yy", String.valueOf(date.getYear())) + .param("mm", String.valueOf(date.getMonthValue())) + .param("dd", String.valueOf(date.getDayOfMonth()))) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.userId").value(expectedResponse.getData().getUserId())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.checkDate").value(expectedResponse.getData().getCheckDate().toString())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.nutritionSumType").value(expectedResponse.getData().getNutritionSumType())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalKcal").value(expectedResponse.getData().getTotalKcal())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalCarbohydrate").value(expectedResponse.getData().getTotalCarbohydrate())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalProtein").value(expectedResponse.getData().getTotalProtein())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalFat").value(expectedResponse.getData().getTotalFat())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.ratioKcal").value(expectedResponse.getData().getRatioKcal())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.ratioCarbohydrate").value(expectedResponse.getData().getRatioCarbohydrate())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.ratioProtein").value(expectedResponse.getData().getRatioProtein())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.ratioFat").value(expectedResponse.getData().getRatioFat())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); + } + + //최근 7일간 먹은 음식들의 영양성분별 총합 조회 + @DisplayName("최근 7일간 먹은 음식들의 영양성분별 총합 조회") + @Test + @WithMockUser("test") + void testGetNutritionSumByWeek() throws Exception { + //Given + LocalDate date = LocalDate.now(); + ResponseNutritionSumByDateDto responseNutritionSumByDateDto = ResponseNutritionSumByDateDto.of(testUserId, date, 7 + , 500, 100, 50, 50, 0.2, 0.3, 0.4, 0.5); + ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); + when(foodService.getNutritionSumByWeek(any(Long.class))).thenReturn(responseNutritionSumByDateDto); + + String json = mapper.writeValueAsString(responseNutritionSumByDateDto); + + //When + mockMvc.perform(MockMvcRequestBuilders + .get("/api/food/{userId}/nutrition/recentWeek", testUserId)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.userId").value(expectedResponse.getData().getUserId())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.checkDate").value(expectedResponse.getData().getCheckDate().toString())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.nutritionSumType").value(expectedResponse.getData().getNutritionSumType())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalKcal").value(expectedResponse.getData().getTotalKcal())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalCarbohydrate").value(expectedResponse.getData().getTotalCarbohydrate())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalProtein").value(expectedResponse.getData().getTotalProtein())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalFat").value(expectedResponse.getData().getTotalFat())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.ratioKcal").value(expectedResponse.getData().getRatioKcal())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.ratioCarbohydrate").value(expectedResponse.getData().getRatioCarbohydrate())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.ratioProtein").value(expectedResponse.getData().getRatioProtein())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.ratioFat").value(expectedResponse.getData().getRatioFat())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); + } + + //최근 한달간 먹은 음식들의 영양성분별 총합 조회 + @DisplayName("최근 한달간 먹은 음식들의 영양성분별 총합 조회") + @Test + @WithMockUser("test") + void testGetNutritionSumByMonth() throws Exception { + //Given + LocalDate date = LocalDate.now(); + ResponseNutritionSumByDateDto responseNutritionSumByDateDto = ResponseNutritionSumByDateDto.of(testUserId, date, 30 + , 500, 100, 50, 50, 0.2, 0.3, 0.4, 0.5); + ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); + when(foodService.getNutritionSumByMonth(any(Long.class))).thenReturn(responseNutritionSumByDateDto); + + String json = mapper.writeValueAsString(responseNutritionSumByDateDto); + + //When + mockMvc.perform(MockMvcRequestBuilders + .get("/api/food/{userId}/nutrition/recentMonth", testUserId)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.userId").value(expectedResponse.getData().getUserId())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.checkDate").value(expectedResponse.getData().getCheckDate().toString())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.nutritionSumType").value(expectedResponse.getData().getNutritionSumType())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalKcal").value(expectedResponse.getData().getTotalKcal())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalCarbohydrate").value(expectedResponse.getData().getTotalCarbohydrate())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalProtein").value(expectedResponse.getData().getTotalProtein())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalFat").value(expectedResponse.getData().getTotalFat())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.ratioKcal").value(expectedResponse.getData().getRatioKcal())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.ratioCarbohydrate").value(expectedResponse.getData().getRatioCarbohydrate())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.ratioProtein").value(expectedResponse.getData().getRatioProtein())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.ratioFat").value(expectedResponse.getData().getRatioFat())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); + } + + //유저의 주간 식습관 점수와 best3, worst3 음식 조회 + @DisplayName("유저의 주간 식습관 점수와 best3, worst3 음식 조회") + @Test + @WithMockUser("test") + void testGetScoreOfUserWithBestAndWorstFoods() throws Exception{ + //Given + ResponseSimpleFoodDto food1 = ResponseSimpleFoodDto.of("test1", 100, 100, 100, 100, LocalDate.now()); + ResponseSimpleFoodDto food2 = ResponseSimpleFoodDto.of("test", 100, 100, 100, 100, LocalDate.now()); + ResponseSimpleFoodDto food3 = ResponseSimpleFoodDto.of("test", 100, 100, 100, 100, LocalDate.now()); + ResponseSimpleFoodDto food4 = ResponseSimpleFoodDto.of("test4", 100, 100, 100, 100, LocalDate.now()); + ResponseSimpleFoodDto food5 = ResponseSimpleFoodDto.of("test", 100, 100, 100, 100, LocalDate.now()); + ResponseSimpleFoodDto food6 = ResponseSimpleFoodDto.of("test", 100, 100, 100, 100, LocalDate.now()); + + ResponseScoreBestWorstDto responseScoreBestWorstDto = ResponseScoreBestWorstDto.of(testUserId, 100, 80 + , 60, 240, List.of(food1, food2,food3), List.of(food4, food5, food6)); + ApiResponse expectedResponse = ApiResponse.success(responseScoreBestWorstDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); + when(foodService.getScoreOfUserWithBestAndWorstFoods(any(Long.class))).thenReturn(responseScoreBestWorstDto); + + String json = mapper.writeValueAsString(responseScoreBestWorstDto); + + //When + mockMvc.perform(MockMvcRequestBuilders + .get("/api/food/{userId}/score", testUserId)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalScore").value(expectedResponse.getData().getTotalScore())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.calorieScore").value(expectedResponse.getData().getCalorieScore())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.carbohydrateScore").value(expectedResponse.getData().getCarbohydrateScore())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.proteinScore").value(expectedResponse.getData().getProteinScore())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.fatScore").value(expectedResponse.getData().getFatScore())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.best[0].name").value(expectedResponse.getData().getBest().get(0).getName())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.worst[0].name").value(expectedResponse.getData().getWorst().get(0).getName())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); + } + + //유저의 일기 분석 그래프 데이터 및 식습관 totalScore 조회 + @DisplayName("유저의 일기 분석 그래프 데이터 및 식습관 totalScore 조회") + @Test + @WithMockUser("test") + void testGetAnalysisOfUser() throws Exception { + //Given + ResponseAnalysisDto responseAnalysisDto = ResponseAnalysisDto.of(100, List.of(100.0, 100.0), + List.of(100.0, 100.0), List.of(100.0, 100.0), List.of(100.0, 100.0), List.of(100.0, 100.0), + List.of(100.0, 100.0), List.of(100.0, 100.0), List.of(100.0, 100.0)); + + ApiResponse expectedResponse = ApiResponse.success(responseAnalysisDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); + when(foodService.getAnalysisOfUser(any(Long.class))).thenReturn(responseAnalysisDto); + String json = mapper.writeValueAsString(responseAnalysisDto); + + //When + mockMvc.perform(MockMvcRequestBuilders + .get("/api/food/{userId}/analysis", testUserId)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.calorieLastSevenDays[0]").value(expectedResponse.getData().getCalorieLastSevenDays().get(0))) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.carbohydrateLastSevenDays[0]").value(expectedResponse.getData().getCarbohydrateLastSevenDays().get(0))) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.proteinLastSevenDays[0]").value(expectedResponse.getData().getProteinLastSevenDays().get(0))) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.fatLastSevenDays[0]").value(expectedResponse.getData().getFatLastSevenDays().get(0))) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.calorieLastFourWeek[0]").value(expectedResponse.getData().getCalorieLastFourWeek().get(0))) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.carbohydrateLastFourWeek[0]").value(expectedResponse.getData().getCarbohydrateLastFourWeek().get(0))) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.proteinLastFourWeek[0]").value(expectedResponse.getData().getProteinLastFourWeek().get(0))) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.fatLastFourWeek[0]").value(expectedResponse.getData().getFatLastFourWeek().get(0))) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.totalScore").value(expectedResponse.getData().getTotalScore())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); + + } + + //식습관 점수 기반 주간 랭킹 조회 + @DisplayName("식습관 점수 기반 주간 랭킹 조회") + @Test + @WithMockUser("test") + void testGetUserRankByWeek() throws Exception{ + //Given + ResponseRankUserDto responseRankUserDto1 = ResponseRankUserDto.of(1L, "test", "image", 100, 100, 100, 100, 400); + ResponseRankUserDto responseRankUserDto2 = ResponseRankUserDto.of(2L, "test", "image", 100, 100, 100, 100, 400); + List responseRankUserDtoList = List.of(responseRankUserDto1, responseRankUserDto2); + + ApiResponse> expectedResponse = ApiResponse.success(responseRankUserDtoList, ResponseCode.FOOD_READ_SUCCESS.getMessage()); + when(foodService.getUserRankByWeek(testUserId)).thenReturn(responseRankUserDtoList); + + //When + mockMvc.perform(MockMvcRequestBuilders + .get("/api/food/{userId}/rank", testUserId)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].userId").value(expectedResponse.getData().get(0).getUserId())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].image").value(expectedResponse.getData().get(0).getImage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].totalScore").value(expectedResponse.getData().get(0).getTotalScore())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].calorieScore").value(expectedResponse.getData().get(0).getCalorieScore())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].carbohydrateScore").value(expectedResponse.getData().get(0).getCarbohydrateScore())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].proteinScore").value(expectedResponse.getData().get(0).getProteinScore())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].fatScore").value(expectedResponse.getData().get(0).getFatScore())); + } +} From 33aa1f42bf24ce66462197416ac2e0fd01abab54 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 6 Nov 2023 23:08:10 +0900 Subject: [PATCH 14/16] =?UTF-8?q?:sparkles:=20feat:=20=EC=9D=8C=EC=8B=9D?= =?UTF-8?q?=20=EC=9D=B4=EB=A6=84=20=EC=A4=91=EB=B3=B5=20=EC=97=AC=EB=B6=80?= =?UTF-8?q?=20=EB=A1=9C=EC=A7=81=20=EA=B5=AC=ED=98=84=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/food/repository/FoodRepository.java | 1 + .../java/com/diareat/diareat/food/service/FoodService.java | 3 +++ src/main/java/com/diareat/diareat/util/api/ResponseCode.java | 1 + .../com/diareat/diareat/controller/FoodControllerTest.java | 5 ----- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java b/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java index b206e45..ce4dada 100644 --- a/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java +++ b/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java @@ -8,6 +8,7 @@ public interface FoodRepository extends JpaRepository { boolean existsByIdAndUserId(Long id, Long userId); // 유저가 먹은 음식인지 확인 + boolean existsByName(String name); List findAllByUserIdAndDate(Long userId, LocalDate date); //유저가 특정 날짜에 먹은 음식 반환 List findAllByUserIdAndDateBetween(Long userId, LocalDate startDate, LocalDate endDate); // 유저가 특정 기간 내에 먹은 음식 반환 } diff --git a/src/main/java/com/diareat/diareat/food/service/FoodService.java b/src/main/java/com/diareat/diareat/food/service/FoodService.java index ebd1626..c345ded 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -38,6 +38,9 @@ public class FoodService { @CacheEvict(value = "ResponseFoodDto", key = "#createFoodDto.getUserId()+#createFoodDto.getDate()", cacheManager = "diareatCacheManager") @Transactional public Long saveFood(CreateFoodDto createFoodDto) { + if (foodRepository.existsByName(createFoodDto.getName())){ + throw new FoodException(ResponseCode.FOOD_NAME_ALREADY_EXIST); + } User user = getUserById(createFoodDto.getUserId()); Food food = Food.createFood(createFoodDto.getName(), user, createFoodDto.getBaseNutrition()); return foodRepository.save(food).getId(); diff --git a/src/main/java/com/diareat/diareat/util/api/ResponseCode.java b/src/main/java/com/diareat/diareat/util/api/ResponseCode.java index 994fcd2..e9d88c2 100644 --- a/src/main/java/com/diareat/diareat/util/api/ResponseCode.java +++ b/src/main/java/com/diareat/diareat/util/api/ResponseCode.java @@ -30,6 +30,7 @@ public enum ResponseCode { FOLLOWED_ALREADY(HttpStatus.CONFLICT, false, "이미 팔로우한 사용자입니다."), UNFOLLOWED_ALREADY(HttpStatus.CONFLICT, false, "이미 언팔로우한 사용자입니다."), FAVORITE_ALREADY_EXIST(HttpStatus.CONFLICT, false, "이미 즐겨찾기에 존재하는 음식입니다."), + FOOD_NAME_ALREADY_EXIST(HttpStatus.CONFLICT, false, "이미 존재하는 음식 이름입니다."), // 500 Internal Server Error INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, false, "서버에 오류가 발생하였습니다."), diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index 510995b..7d00fcb 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -258,7 +258,6 @@ void testGetNutritionSumByDate() throws Exception{ ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto,ResponseCode.FOOD_READ_SUCCESS.getMessage()); when(foodService.getNutritionSumByDate(any(Long.class),any(LocalDate.class))).thenReturn(responseNutritionSumByDateDto); - String json = mapper.writeValueAsString(responseNutritionSumByDateDto); //When mockMvc.perform(MockMvcRequestBuilders @@ -295,7 +294,6 @@ void testGetNutritionSumByWeek() throws Exception { ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); when(foodService.getNutritionSumByWeek(any(Long.class))).thenReturn(responseNutritionSumByDateDto); - String json = mapper.writeValueAsString(responseNutritionSumByDateDto); //When mockMvc.perform(MockMvcRequestBuilders @@ -329,7 +327,6 @@ void testGetNutritionSumByMonth() throws Exception { ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); when(foodService.getNutritionSumByMonth(any(Long.class))).thenReturn(responseNutritionSumByDateDto); - String json = mapper.writeValueAsString(responseNutritionSumByDateDto); //When mockMvc.perform(MockMvcRequestBuilders @@ -369,7 +366,6 @@ void testGetScoreOfUserWithBestAndWorstFoods() throws Exception{ ApiResponse expectedResponse = ApiResponse.success(responseScoreBestWorstDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); when(foodService.getScoreOfUserWithBestAndWorstFoods(any(Long.class))).thenReturn(responseScoreBestWorstDto); - String json = mapper.writeValueAsString(responseScoreBestWorstDto); //When mockMvc.perform(MockMvcRequestBuilders @@ -399,7 +395,6 @@ void testGetAnalysisOfUser() throws Exception { ApiResponse expectedResponse = ApiResponse.success(responseAnalysisDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); when(foodService.getAnalysisOfUser(any(Long.class))).thenReturn(responseAnalysisDto); - String json = mapper.writeValueAsString(responseAnalysisDto); //When mockMvc.perform(MockMvcRequestBuilders From 13c8eee72a62e084bad5140445464e653a629599 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Tue, 7 Nov 2023 00:02:01 +0900 Subject: [PATCH 15/16] =?UTF-8?q?:fire:=20feat:=20ResponseFavoriteFoodDto?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=ED=95=84=EC=9A=94=EC=97=86=EB=8A=94=20Use?= =?UTF-8?q?rId=20=EC=86=8D=EC=84=B1=20=EC=A0=9C=EA=B1=B0=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/dto/ResponseFavoriteFoodDto.java | 6 ++---- .../java/com/diareat/diareat/food/service/FoodService.java | 2 +- .../com/diareat/diareat/controller/FoodControllerTest.java | 2 +- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java index bbb4c06..3d33ca4 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java @@ -9,19 +9,17 @@ @AllArgsConstructor public class ResponseFavoriteFoodDto { - private Long userId; private Long favoriteFoodId; private String name; private BaseNutrition baseNutrition; private int count; - public static ResponseFavoriteFoodDto of(Long userId, Long favoriteFoodId, String name, BaseNutrition baseNutrition, int count) { - return new ResponseFavoriteFoodDto(userId, favoriteFoodId, name, baseNutrition, count); + public static ResponseFavoriteFoodDto of(Long favoriteFoodId, String name, BaseNutrition baseNutrition, int count) { + return new ResponseFavoriteFoodDto(favoriteFoodId, name, baseNutrition, count); } public static ResponseFavoriteFoodDto from(FavoriteFood favoriteFood) { return new ResponseFavoriteFoodDto( - favoriteFood.getUser().getId(), favoriteFood.getId(), favoriteFood.getName(), favoriteFood.getBaseNutrition(), diff --git a/src/main/java/com/diareat/diareat/food/service/FoodService.java b/src/main/java/com/diareat/diareat/food/service/FoodService.java index c345ded..bbab88f 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -91,7 +91,7 @@ public List getFavoriteFoodList(Long userId){ validateUser(userId); List foodList = favoriteFoodRepository.findAllByUserId(userId); return foodList.stream() - .map(favoriteFood -> ResponseFavoriteFoodDto.of(favoriteFood.getUser().getId(),favoriteFood.getId(), favoriteFood.getName(), + .map(favoriteFood -> ResponseFavoriteFoodDto.of(favoriteFood.getUser().getId(),favoriteFood.getName(), favoriteFood.getBaseNutrition(), favoriteFood.getCount())).collect(Collectors.toList()); } diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index 7d00fcb..100dc7f 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -188,7 +188,7 @@ void testSaveFavoriteFood() throws Exception { @WithMockUser("test") void testGetFavoriteFoodList() throws Exception { //Given - ResponseFavoriteFoodDto food1 = ResponseFavoriteFoodDto.of(testUserId, testFavoriteFoodId,"test",testBaseNutrition,0); + ResponseFavoriteFoodDto food1 = ResponseFavoriteFoodDto.of(testFavoriteFoodId,"test",testBaseNutrition,0); ApiResponse> expectedResponse = ApiResponse.success(List.of(food1), ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); when(foodService.getFavoriteFoodList(any(Long.class))).thenReturn(List.of(food1)); From 7ee25035d57279e3c36dc988bda0fadf6ff0861b Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Tue, 7 Nov 2023 00:05:19 +0900 Subject: [PATCH 16/16] =?UTF-8?q?:recycle:=20refactor:=20=EB=B0=98?= =?UTF-8?q?=EC=98=AC=EB=A6=BC=20=EA=B0=84=EC=86=8C=ED=99=94=20(#50)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/service/FoodService.java b/src/main/java/com/diareat/diareat/food/service/FoodService.java index bbab88f..824baed 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -203,25 +203,17 @@ public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId ResponseRankUserDto scoresOfUser = calculateUserScoreThisWeek(targetUser, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()); - totalScore = scoresOfUser.getTotalScore(); - kcalScore = scoresOfUser.getCalorieScore(); - carbohydrateScore = scoresOfUser.getCarbohydrateScore(); - proteinScore = scoresOfUser.getProteinScore(); - fatScore = scoresOfUser.getFatScore(); + totalScore = Math.round((scoresOfUser.getTotalScore() * 100.0))/ 100.0; + kcalScore = Math.round((scoresOfUser.getCalorieScore() * 100.0)) / 100.0; + carbohydrateScore = Math.round((scoresOfUser.getCarbohydrateScore() * 100.0)) / 100.0; + proteinScore = Math.round((scoresOfUser.getProteinScore() * 100.0)) / 100.0; + fatScore = Math.round((scoresOfUser.getFatScore() * 100.0 ))/ 100.0; //Dto의 형식에 맞게 Best3와 Worst3 음식 계산 List simpleBestFoodList = getBestFoodByWeek(userId).getRankFoodList(); List simpleWorstFoodList = getWorstFoodByWeek(userId).getRankFoodList(); - //반올림 - totalScore = Math.round(totalScore * 100.0) / 100.0; - kcalScore = Math.round(kcalScore * 100.0) / 100.0; - carbohydrateScore = Math.round(carbohydrateScore * 100.0) / 100.0; - proteinScore = Math.round(proteinScore * 100.0) / 100.0; - fatScore = Math.round(fatScore * 100.0) / 100.0; - - return ResponseScoreBestWorstDto.of(kcalScore, carbohydrateScore, proteinScore, fatScore, totalScore, simpleBestFoodList, simpleWorstFoodList); }