Skip to content

Commit

Permalink
Merge pull request #121 from CAUSOLDOUTMEN/feat/120-date-food
Browse files Browse the repository at this point in the history
Feat: 일별 음식에서 해당 날짜 없으면 0 반환 및 한 주 단위로 묶어 데이터 반환 (#120)
  • Loading branch information
win-luck authored Nov 26, 2023
2 parents a8418f8 + d3922c1 commit f1348c2
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,26 @@
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ResponseAnalysisDto { // 그래프 + 점수에 사용되는 DTO

private double totalScore;
private List<Double> calorieLastSevenDays; // 최근 7일간의 칼로리 (7개 과거부터 나열)
private List<Map<LocalDate, Double>> calorieLastSevenDays; // 최근 7일간의 칼로리 (7개 과거부터 나열)
private List<Double> calorieLastFourWeek; // 최근 4주간의 칼로리 (4개 과거부터 나열)
private List<Double> carbohydrateLastSevenDays; // 최근 7일간의 탄수화물
private List<Map<LocalDate, Double>> carbohydrateLastSevenDays; // 최근 7일간의 탄수화물
private List<Double> carbohydrateLastFourWeek; // 최근 4주간의 탄수화물
private List<Double> proteinLastSevenDays; // 최근 7일간의 단백질
private List<Map<LocalDate, Double>> proteinLastSevenDays; // 최근 7일간의 단백질
private List<Double> proteinLastFourWeek; // 최근 4주간의 단백질
private List<Double> fatLastSevenDays; // 최근 7일간의 지방
private List<Map<LocalDate, Double>> fatLastSevenDays; // 최근 7일간의 지방
private List<Double> fatLastFourWeek; // 최근 4주간의 지방

public static ResponseAnalysisDto of(double totalScore, List<Double> calorieLastSevenDays, List<Double> calorieLastFourWeek, List<Double> carbohydrateLastSevenDays, List<Double> carbohydrateLastFourWeek, List<Double> proteinLastSevenDays, List<Double> proteinLastFourWeek, List<Double> fatLastSevenDays, List<Double> fatLastFourWeek) {
public static ResponseAnalysisDto of(double totalScore, List<Map<LocalDate, Double>> calorieLastSevenDays, List<Double> calorieLastFourWeek,List<Map<LocalDate, Double>> carbohydrateLastSevenDays, List<Double> carbohydrateLastFourWeek,List<Map<LocalDate, Double>> proteinLastSevenDays, List<Double> proteinLastFourWeek, List<Map<LocalDate, Double>> fatLastSevenDays, List<Double> fatLastFourWeek) {
return new ResponseAnalysisDto(totalScore, calorieLastSevenDays, calorieLastFourWeek, carbohydrateLastSevenDays, carbohydrateLastFourWeek, proteinLastSevenDays, proteinLastFourWeek, fatLastSevenDays, fatLastFourWeek);
}
}
68 changes: 43 additions & 25 deletions src/main/java/com/diareat/diareat/food/service/FoodService.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cglib.core.Local;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand Down Expand Up @@ -247,42 +248,59 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId, int year, int month, i
validateUser(userId);
User user = userRepository.getReferenceById(userId);

//현재 날짜
LocalDate currentDate = LocalDate.of(year,month,day);

//최근 1주간 유저가 먹은 음식들의 날짜별 HashMap
HashMap<LocalDate, List<BaseNutrition>> nutritionSumOfUserByWeek = getNutritionSumByDateMap(userId, LocalDate.of(year,month,day).minusWeeks(1), LocalDate.of(year, month, day));
HashMap<LocalDate, List<BaseNutrition>> nutritionSumOfUserByMonth = getNutritionSumByDateMap(userId, LocalDate.of(year,month,day).minusWeeks(3).with(DayOfWeek.MONDAY), LocalDate.of(year, month ,day));
HashMap<LocalDate, List<BaseNutrition>> nutritionSumOfUserByWeek = getNutritionSumByDateMap(userId, currentDate.minusWeeks(1), currentDate);
HashMap<LocalDate, List<BaseNutrition>> nutritionSumOfUserByMonth = getNutritionSumByDateMap(userId, currentDate.minusWeeks(3).with(DayOfWeek.MONDAY), currentDate);

double totalWeekScore = calculateUserScoreThisWeek(user, LocalDate.of(year, month, day).with(DayOfWeek.MONDAY), LocalDate.of(year, month, day)).getTotalScore();

List<Double> calorieLastSevenDays = new ArrayList<>();
List<Map<LocalDate,Double>>calorieLastSevenDays = new ArrayList<>();
List<Double> calorieLastFourWeek = new ArrayList<>();
List<Double> carbohydrateLastSevenDays = new ArrayList<>();
List<Map<LocalDate,Double>> carbohydrateLastSevenDays = new ArrayList<>();
List<Double> carbohydrateLastFourWeek = new ArrayList<>();
List<Double> proteinLastSevenDays = new ArrayList<>();
List<Map<LocalDate,Double>> proteinLastSevenDays = new ArrayList<>();
List<Double> proteinLastFourWeek = new ArrayList<>();
List<Double> fatLastSevenDays = new ArrayList<>();
List<Map<LocalDate,Double>> fatLastSevenDays = new ArrayList<>();
List<Double> 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();
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);
//최근 7일간의 식습관, 비어있으면 0으로 반환
for (LocalDate date = currentDate.minusWeeks(1); date.isBefore(currentDate); date = date.plusDays(1)){
if(!nutritionSumOfUserByWeek.containsKey(date)){ //해당 날짜에 먹은 음식이 없는 경우는 0으로 반환
calorieLastSevenDays.add(Map.of(date, 0.0));
carbohydrateLastSevenDays.add(Map.of(date, 0.0));
proteinLastSevenDays.add(Map.of(date, 0.0));
fatLastSevenDays.add(Map.of(date, 0.0));
}else{
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(Map.of(date, (double) totalKcal));
carbohydrateLastSevenDays.add(Map.of(date, (double) totalCarbohydrate));
proteinLastSevenDays.add(Map.of(date, (double) totalProtein));
fatLastSevenDays.add(Map.of(date, (double) totalFat));
}
}


//최근 한달간의 식습관
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();

//최근 한달간의 식습관. 총 4주간의 데이터를 반환하며, 한주 단위로 묶어서 반환
for (LocalDate date = currentDate.minusWeeks(3).with(DayOfWeek.MONDAY); date.isBefore(currentDate); date = date.plusWeeks(1)){
int totalKcal = 0;
int totalCarbohydrate = 0;
int totalProtein = 0;
int totalFat = 0;
//해당 주에 먹은 음식들을 모두 합해서 계산
for (LocalDate inner_date = date; inner_date.isBefore(date.plusWeeks(1)); inner_date = inner_date.plusDays(1)){
if(nutritionSumOfUserByMonth.containsKey(inner_date)){
totalKcal += nutritionSumOfUserByMonth.get(inner_date).stream().mapToInt(BaseNutrition::getKcal).sum();
totalCarbohydrate += nutritionSumOfUserByMonth.get(inner_date).stream().mapToInt(BaseNutrition::getCarbohydrate).sum();
totalProtein += nutritionSumOfUserByMonth.get(inner_date).stream().mapToInt(BaseNutrition::getProtein).sum();
totalFat += nutritionSumOfUserByMonth.get(inner_date).stream().mapToInt(BaseNutrition::getFat).sum();
}
}
calorieLastFourWeek.add((double) totalKcal);
carbohydrateLastFourWeek.add((double) totalCarbohydrate);
proteinLastFourWeek.add((double) totalProtein);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import com.diareat.diareat.util.api.ResponseCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.hibernate.validator.internal.util.privilegedactions.LoadClass;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
Expand All @@ -29,6 +30,7 @@

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
Expand Down Expand Up @@ -424,9 +426,9 @@ void testGetScoreOfUserWithBestAndWorstFoods() throws Exception{
@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));
ResponseAnalysisDto responseAnalysisDto = ResponseAnalysisDto.of(100, List.of(Map.of(LocalDate.of(2021, 10, 10), 100.0)),
List.of(100.0, 100.0), List.of(Map.of(LocalDate.of(2021, 10, 10), 100.0)), List.of(100.0, 100.0), List.of(Map.of(LocalDate.of(2021, 10, 10), 100.0)),
List.of(100.0, 100.0), List.of(Map.of(LocalDate.of(2021, 10, 10), 100.0)), List.of(100.0, 100.0));

ApiResponse<ResponseAnalysisDto> expectedResponse = ApiResponse.success(responseAnalysisDto, ResponseCode.FOOD_READ_SUCCESS.getMessage());
when(foodService.getAnalysisOfUser(any(Long.class), any(int.class), any(int.class), any(int.class))).thenReturn(responseAnalysisDto);
Expand All @@ -440,10 +442,10 @@ void testGetAnalysisOfUser() throws Exception {
.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.calorieLastSevenDays[0]['2021-10-10']").value(expectedResponse.getData().getCalorieLastSevenDays().get(0).get(LocalDate.of(2021, 10, 10))))
.andExpect(MockMvcResultMatchers.jsonPath("$.data.carbohydrateLastSevenDays[0]['2021-10-10']").value(expectedResponse.getData().getCarbohydrateLastSevenDays().get(0).get(LocalDate.of(2021, 10, 10))))
.andExpect(MockMvcResultMatchers.jsonPath("$.data.proteinLastSevenDays[0]['2021-10-10']").value(expectedResponse.getData().getProteinLastSevenDays().get(0).get(LocalDate.of(2021, 10, 10))))
.andExpect(MockMvcResultMatchers.jsonPath("$.data.fatLastSevenDays[0]['2021-10-10']").value(expectedResponse.getData().getFatLastSevenDays().get(0).get(LocalDate.of(2021, 10, 10))))
.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)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;
Expand Down Expand Up @@ -453,16 +454,16 @@ void testGetAnalysisOfUser(){
ResponseAnalysisDto response = foodService.getAnalysisOfUser(user.getId(), fixedDate.getYear(), fixedDate.getMonthValue(), fixedDate.getDayOfMonth());

double totalScore = response.getTotalScore();
List<Double> calorieLastSevenDays = response.getCalorieLastSevenDays();
List<Map<LocalDate, Double>> calorieLastSevenDays = response.getCalorieLastSevenDays();
List<Double> calorieLastFourWeeks = response.getCalorieLastFourWeek();


// then
assertEquals(192.95, totalScore);

//갯수 확인
assertEquals(3, calorieLastSevenDays.size()); //일주일동안의 음식 -> 3개
assertEquals(5, calorieLastFourWeeks.size()); //한달동안의 음식 -> 5개
assertEquals(7, calorieLastSevenDays.size()); //일주일동안의 음식 -> 7개 고정
assertEquals(4, calorieLastFourWeeks.size()); //한달동안의 음식 -> 5개


verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(1), fixedDate);
Expand Down

0 comments on commit f1348c2

Please sign in to comment.