From 77c2ff89b7647a4eaac6be3b7af2a33773a8c95f Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 15 Sep 2023 00:03:48 +0900 Subject: [PATCH 001/371] =?UTF-8?q?=E2=9E=95=20chore:=20DB=20=EA=B4=80?= =?UTF-8?q?=EB=A0=A8=20=EC=9D=98=EC=A1=B4=EC=84=B1=20=EC=B6=94=EA=B0=80=20?= =?UTF-8?q?(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 ++ build.gradle | 6 +++--- src/main/resources/application.properties | 3 ++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index c2065bc..cf851a2 100644 --- a/.gitignore +++ b/.gitignore @@ -35,3 +35,5 @@ out/ ### VS Code ### .vscode/ + +application-db.properties diff --git a/build.gradle b/build.gradle index e1b0b09..c7c7a25 100644 --- a/build.gradle +++ b/build.gradle @@ -22,8 +22,8 @@ repositories { } dependencies { - // implementation 'org.springframework.boot:spring-boot-starter-data-jpa' - // implementation 'org.springframework.boot:spring-boot-starter-jdbc' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-jdbc' implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' @@ -31,7 +31,7 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-websocket' implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5' compileOnly 'org.projectlombok:lombok' - // runtimeOnly 'com.mysql:mysql-connector-j' + runtimeOnly 'com.mysql:mysql-connector-j' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.security:spring-security-test' diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8b13789..3e18c96 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1 +1,2 @@ - +# db +spring.profiles.include = db From 6cf7fc78f2243a684e830f95b4bc1dc623688d8d Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 15 Sep 2023 00:08:47 +0900 Subject: [PATCH 002/371] =?UTF-8?q?=E2=9C=A8=20feat:=20API=20=EB=B0=8F=20E?= =?UTF-8?q?xception=20=EA=B0=9D=EC=B2=B4=20=EC=B6=94=EA=B0=80=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/util/api/ApiBody.java | 16 +++++++++ .../diareat/diareat/util/api/ApiHeader.java | 23 ++++++++++++ .../diareat/diareat/util/api/ApiResponse.java | 31 ++++++++++++++++ .../diareat/util/api/ResponseCode.java | 36 +++++++++++++++++++ .../diareat/util/exception/BaseException.java | 17 +++++++++ .../util/exception/FavoriteException.java | 9 +++++ .../diareat/util/exception/FoodException.java | 9 +++++ .../exception/GlobalExceptionHandler.java | 29 +++++++++++++++ .../diareat/util/exception/UserException.java | 9 +++++ 9 files changed, 179 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/util/api/ApiBody.java create mode 100644 src/main/java/com/diareat/diareat/util/api/ApiHeader.java create mode 100644 src/main/java/com/diareat/diareat/util/api/ApiResponse.java create mode 100644 src/main/java/com/diareat/diareat/util/api/ResponseCode.java create mode 100644 src/main/java/com/diareat/diareat/util/exception/BaseException.java create mode 100644 src/main/java/com/diareat/diareat/util/exception/FavoriteException.java create mode 100644 src/main/java/com/diareat/diareat/util/exception/FoodException.java create mode 100644 src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java create mode 100644 src/main/java/com/diareat/diareat/util/exception/UserException.java diff --git a/src/main/java/com/diareat/diareat/util/api/ApiBody.java b/src/main/java/com/diareat/diareat/util/api/ApiBody.java new file mode 100644 index 0000000..d4fca17 --- /dev/null +++ b/src/main/java/com/diareat/diareat/util/api/ApiBody.java @@ -0,0 +1,16 @@ +package com.diareat.diareat.util.api; + +public class ApiBody { + + private final T data; + private final T msg; + + public ApiBody(T data, T msg) { + this.data = data; + this.msg = msg; + } + + public T getData() { + return data; + } +} diff --git a/src/main/java/com/diareat/diareat/util/api/ApiHeader.java b/src/main/java/com/diareat/diareat/util/api/ApiHeader.java new file mode 100644 index 0000000..f6c4fb9 --- /dev/null +++ b/src/main/java/com/diareat/diareat/util/api/ApiHeader.java @@ -0,0 +1,23 @@ +package com.diareat.diareat.util.api; + +public class ApiHeader { + + private int code; + private String message; + + public ApiHeader(int code, String message) { + this.code = code; + this.message = message; + } + + public ApiHeader() { + } + + public int getCode() { + return code; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/com/diareat/diareat/util/api/ApiResponse.java b/src/main/java/com/diareat/diareat/util/api/ApiResponse.java new file mode 100644 index 0000000..4fe2374 --- /dev/null +++ b/src/main/java/com/diareat/diareat/util/api/ApiResponse.java @@ -0,0 +1,31 @@ +package com.diareat.diareat.util.api; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public class ApiResponse { + + private ApiHeader header; + private ApiBody body; + + private static final int SUCCESS = 200; + + public ApiResponse(ApiHeader header, ApiBody body) { + this.header = header; + this.body = body; + } + + public ApiResponse(ApiHeader header) { + this.header = header; + } + + public static ApiResponse success(T data, String message) { + return new ApiResponse(new ApiHeader(SUCCESS, "SUCCESS"), new ApiBody(data, message)); + } + + public static ApiResponse fail(ResponseCode responseCode) { + return new ApiResponse(new ApiHeader(responseCode.getHttpStatusCode(), responseCode.getMessage()), new ApiBody(null, responseCode.getMessage())); + } +} \ No newline at end of file diff --git a/src/main/java/com/diareat/diareat/util/api/ResponseCode.java b/src/main/java/com/diareat/diareat/util/api/ResponseCode.java new file mode 100644 index 0000000..450a24a --- /dev/null +++ b/src/main/java/com/diareat/diareat/util/api/ResponseCode.java @@ -0,0 +1,36 @@ +package com.diareat.diareat.util.api; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +public enum ResponseCode { + + // 400 Bad Request + BAD_REQUEST(HttpStatus.BAD_REQUEST, false, "잘못된 요청입니다."), + + // 403 Forbidden + FORBIDDEN(HttpStatus.FORBIDDEN, false, "권한이 없습니다."), + + // 404 Not Found + USER_NOT_FOUND(HttpStatus.NOT_FOUND, false,"사용자를 찾을 수 없습니다."), + FOOD_NOT_FOUND(HttpStatus.NOT_FOUND, false,"음식을 찾을 수 없습니다."), + FAVORITE_NOT_FOUND(HttpStatus.NOT_FOUND, false,"즐겨찾기를 찾을 수 없습니다."), + + // 405 Method Not Allowed + METHOD_NOT_ALLOWED(HttpStatus.METHOD_NOT_ALLOWED, false,"허용되지 않은 메소드입니다."), + + // 500 Internal Server Error + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, false,"서버에 오류가 발생하였습니다."); + + private final HttpStatus httpStatus; + private final Boolean success; + private final String message; + + public int getHttpStatusCode() { + return httpStatus.value(); + } + } diff --git a/src/main/java/com/diareat/diareat/util/exception/BaseException.java b/src/main/java/com/diareat/diareat/util/exception/BaseException.java new file mode 100644 index 0000000..fade27c --- /dev/null +++ b/src/main/java/com/diareat/diareat/util/exception/BaseException.java @@ -0,0 +1,17 @@ +package com.diareat.diareat.util.exception; + +import com.diareat.diareat.util.api.ResponseCode; +import lombok.AllArgsConstructor; +import lombok.Getter; + +@AllArgsConstructor +@Getter +public class BaseException extends RuntimeException { + + private final ResponseCode responseCode; + + @Override + public String getMessage() { + return responseCode.getMessage(); + } +} diff --git a/src/main/java/com/diareat/diareat/util/exception/FavoriteException.java b/src/main/java/com/diareat/diareat/util/exception/FavoriteException.java new file mode 100644 index 0000000..7b66855 --- /dev/null +++ b/src/main/java/com/diareat/diareat/util/exception/FavoriteException.java @@ -0,0 +1,9 @@ +package com.diareat.diareat.util.exception; + +import com.diareat.diareat.util.api.ResponseCode; + +public class FavoriteException extends BaseException{ + public FavoriteException(ResponseCode responseCode) { + super(responseCode); + } +} diff --git a/src/main/java/com/diareat/diareat/util/exception/FoodException.java b/src/main/java/com/diareat/diareat/util/exception/FoodException.java new file mode 100644 index 0000000..3291c75 --- /dev/null +++ b/src/main/java/com/diareat/diareat/util/exception/FoodException.java @@ -0,0 +1,9 @@ +package com.diareat.diareat.util.exception; + +import com.diareat.diareat.util.api.ResponseCode; + +public class FoodException extends BaseException { + public FoodException(ResponseCode responseCode) { + super(responseCode); + } +} diff --git a/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java b/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..d8e5cad --- /dev/null +++ b/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java @@ -0,0 +1,29 @@ +package com.diareat.diareat.util.exception; + +import com.diareat.diareat.util.api.ApiResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +@Slf4j +@ControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(UserException.class) + public ApiResponse handleUserException(UserException e) { + log.info("UserException: {}", e.getMessage()); + return ApiResponse.fail(e.getResponseCode()); + } + + @ExceptionHandler(FavoriteException.class) + public ApiResponse handleFavoriteException(FavoriteException e) { + log.info("FavoriteException: {}", e.getMessage()); + return ApiResponse.fail(e.getResponseCode()); + } + + @ExceptionHandler(FoodException.class) + public ApiResponse handleFoodException(FoodException e) { + log.info("FoodException: {}", e.getMessage()); + return ApiResponse.fail(e.getResponseCode()); + } +} diff --git a/src/main/java/com/diareat/diareat/util/exception/UserException.java b/src/main/java/com/diareat/diareat/util/exception/UserException.java new file mode 100644 index 0000000..a6d58bb --- /dev/null +++ b/src/main/java/com/diareat/diareat/util/exception/UserException.java @@ -0,0 +1,9 @@ +package com.diareat.diareat.util.exception; + +import com.diareat.diareat.util.api.ResponseCode; + +public class UserException extends BaseException { + public UserException(ResponseCode responseCode) { + super(responseCode); + } +} From 8e2e3d53802ea7f639c1b7e733c1a8fc6abdeb3d Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 15 Sep 2023 00:29:29 +0900 Subject: [PATCH 003/371] =?UTF-8?q?=E2=9C=A8feat:=20=EC=A3=BC=EC=9A=94=20J?= =?UTF-8?q?PA=20Entity=20=EA=B5=AC=ED=98=84=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/domain/FavoriteFood.java | 39 ++++++++++++ .../com/diareat/diareat/food/domain/Food.java | 50 ++++++++++++++++ .../diareat/user/domain/BaseNutrition.java | 36 +++++++++++ .../com/diareat/diareat/user/domain/User.java | 59 +++++++++++++++++++ 4 files changed, 184 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java create mode 100644 src/main/java/com/diareat/diareat/food/domain/Food.java create mode 100644 src/main/java/com/diareat/diareat/user/domain/BaseNutrition.java create mode 100644 src/main/java/com/diareat/diareat/user/domain/User.java diff --git a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java new file mode 100644 index 0000000..444ae2b --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java @@ -0,0 +1,39 @@ +package com.diareat.diareat.food.domain; + +import com.diareat.diareat.user.domain.BaseNutrition; +import com.diareat.diareat.user.domain.User; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.time.LocalDate; +import java.time.LocalTime; + +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Entity +public class FavoriteFood { + + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "favorite_food_id") + private Long id; + + private String name; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "food_id") + private Food food; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + + private LocalDate date; + + private LocalTime time; + + private BaseNutrition baseNutrition; + +} diff --git a/src/main/java/com/diareat/diareat/food/domain/Food.java b/src/main/java/com/diareat/diareat/food/domain/Food.java new file mode 100644 index 0000000..3d0ad0e --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -0,0 +1,50 @@ +package com.diareat.diareat.food.domain; + +import com.diareat.diareat.user.domain.BaseNutrition; +import com.diareat.diareat.user.domain.User; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.time.LocalDate; +import java.time.LocalTime; + +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Entity +public class Food { + + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "food_id") + private Long id; + + private String name; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + private LocalDate date; + + private LocalTime time; + + private BaseNutrition baseNutrition; + + // 생성 메서드 + public static Food createFood(String name, User user, LocalDate date, LocalTime time, BaseNutrition baseNutrition) { + Food food = new Food(); + food.name = name; + food.user = user; + food.date = date; + food.time = time; + food.baseNutrition = baseNutrition; + return food; + } + + // 음식 정보 수정 + public void updateFood(String name, BaseNutrition baseNutrition) { + this.name = name; + this.baseNutrition = baseNutrition; + } +} diff --git a/src/main/java/com/diareat/diareat/user/domain/BaseNutrition.java b/src/main/java/com/diareat/diareat/user/domain/BaseNutrition.java new file mode 100644 index 0000000..ed23ef2 --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/domain/BaseNutrition.java @@ -0,0 +1,36 @@ +package com.diareat.diareat.user.domain; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.persistence.Embeddable; + +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Embeddable // 값 타입 +public class BaseNutrition { // 기본 영양소 4종만 포함 + + private int kcal = 0; // 칼로리 + private int carbohydrate = 0; // 탄수화물 + private int protein = 0; // 단백질 + private int fat = 0; // 지방 + + // 생성 메서드 + public static BaseNutrition createNutrition(int kcal, int carbohydrate, int protein, int fat) { + BaseNutrition baseNutrition = new BaseNutrition(); + baseNutrition.kcal = kcal; + baseNutrition.carbohydrate = carbohydrate; + baseNutrition.protein = protein; + baseNutrition.fat = fat; + return baseNutrition; + } + + // 영양소 수정 + public void updateNutrition(int kcal, int carbohydrate, int protein, int fat) { + this.kcal = kcal; + this.carbohydrate = carbohydrate; + this.protein = protein; + this.fat = fat; + } +} diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java new file mode 100644 index 0000000..4cacc4d --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -0,0 +1,59 @@ +package com.diareat.diareat.user.domain; + +import com.diareat.diareat.food.domain.Food; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.util.ArrayList; +import java.util.List; + +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Entity +public class User { + + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "user_id") + private Long id; + + private String name; // 닉네임 + + @JsonIgnore + private String keyCode; // 로그인 식별키 + + private int tall; // 키 + + private int weight; // 몸무게 + + private int age; // 나이 + + private BaseNutrition baseNutrition; // 영양소 + + @OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) // 유저가 탈퇴하면 촬영한 음식도 삭제 + private List foods = new ArrayList<>(); + + // 생성 메서드 + public static User createUser(String name, String keyCode, int tall, int weight, int age, BaseNutrition baseNutrition) { + User user = new User(); + user.name = name; + user.keyCode = keyCode; + user.tall = tall; + user.weight = weight; + user.age = age; + user.baseNutrition = baseNutrition; + return user; + } + + // 회원정보 수정 및 수정에 따른 영양소 재계산 + public void updateUser(String name, int tall, int weight, int age, BaseNutrition baseNutrition) { + this.name = name; + this.tall = tall; + this.weight = weight; + this.age = age; + // 계산공식 추후 추가 + this.baseNutrition = baseNutrition; + } +} From 651184871e965cc09f452614dc01b2fb5b860ff3 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 15 Sep 2023 00:30:10 +0900 Subject: [PATCH 004/371] =?UTF-8?q?=F0=9F=93=A6feat:=20=EA=B3=84=EC=B8=B5?= =?UTF-8?q?=ED=98=95=20=ED=8C=A8=ED=82=A4=EC=A7=80=20user=20&=20food=20?= =?UTF-8?q?=EB=8F=84=EC=9E=85=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/controller/FoodController.java | 4 ++++ .../diareat/food/repository/FavoriteFoodRepository.java | 7 +++++++ .../diareat/diareat/food/repository/FoodRepository.java | 7 +++++++ .../java/com/diareat/diareat/food/service/FoodService.java | 4 ++++ .../diareat/diareat/user/controller/UserController.java | 4 ++++ .../diareat/diareat/user/repository/UserRepository.java | 7 +++++++ .../java/com/diareat/diareat/user/service/UserService.java | 4 ++++ 7 files changed, 37 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/food/controller/FoodController.java create mode 100644 src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java create mode 100644 src/main/java/com/diareat/diareat/food/repository/FoodRepository.java create mode 100644 src/main/java/com/diareat/diareat/food/service/FoodService.java create mode 100644 src/main/java/com/diareat/diareat/user/controller/UserController.java create mode 100644 src/main/java/com/diareat/diareat/user/repository/UserRepository.java create mode 100644 src/main/java/com/diareat/diareat/user/service/UserService.java diff --git a/src/main/java/com/diareat/diareat/food/controller/FoodController.java b/src/main/java/com/diareat/diareat/food/controller/FoodController.java new file mode 100644 index 0000000..6d97ca5 --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -0,0 +1,4 @@ +package com.diareat.diareat.food.controller; + +public class FoodController { +} diff --git a/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java b/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java new file mode 100644 index 0000000..d90278b --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java @@ -0,0 +1,7 @@ +package com.diareat.diareat.food.repository; + +import com.diareat.diareat.food.domain.FavoriteFood; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface FavoriteFoodRepository extends JpaRepository { +} diff --git a/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java b/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java new file mode 100644 index 0000000..ee9d2b3 --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java @@ -0,0 +1,7 @@ +package com.diareat.diareat.food.repository; + +import com.diareat.diareat.food.domain.Food; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface FoodRepository extends JpaRepository { +} diff --git a/src/main/java/com/diareat/diareat/food/service/FoodService.java b/src/main/java/com/diareat/diareat/food/service/FoodService.java new file mode 100644 index 0000000..282da96 --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -0,0 +1,4 @@ +package com.diareat.diareat.food.service; + +public class FoodService { +} diff --git a/src/main/java/com/diareat/diareat/user/controller/UserController.java b/src/main/java/com/diareat/diareat/user/controller/UserController.java new file mode 100644 index 0000000..278d037 --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/controller/UserController.java @@ -0,0 +1,4 @@ +package com.diareat.diareat.user.controller; + +public class UserController { +} diff --git a/src/main/java/com/diareat/diareat/user/repository/UserRepository.java b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java new file mode 100644 index 0000000..57b3beb --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java @@ -0,0 +1,7 @@ +package com.diareat.diareat.user.repository; + +import com.diareat.diareat.user.domain.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { +} diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java new file mode 100644 index 0000000..12743fd --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -0,0 +1,4 @@ +package com.diareat.diareat.user.service; + +public class UserService { +} From 9073f1cc2857937cb44c50b4497f5f82ffe320f9 Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 24 Sep 2023 01:56:48 +0900 Subject: [PATCH 005/371] =?UTF-8?q?:heavy=5Fplus=5Fsign:=20Chore:=20?= =?UTF-8?q?=EB=A1=9C=EA=B7=B8=EC=9D=B8=20=EA=B4=80=EB=A0=A8=20=EA=B8=B0?= =?UTF-8?q?=EB=8A=A5=20=EB=B3=84=EB=8F=84=20Service=EB=A1=9C=20=EB=B6=84?= =?UTF-8?q?=EB=A6=AC=20=EB=B0=8F=20=EC=9D=98=EC=A1=B4=EC=84=B1=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20(#3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/auth/AuthService.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/auth/AuthService.java diff --git a/src/main/java/com/diareat/diareat/auth/AuthService.java b/src/main/java/com/diareat/diareat/auth/AuthService.java new file mode 100644 index 0000000..cadde6e --- /dev/null +++ b/src/main/java/com/diareat/diareat/auth/AuthService.java @@ -0,0 +1,22 @@ +package com.diareat.diareat.auth; + +import com.diareat.diareat.user.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@RequiredArgsConstructor +@Service +public class AuthService { // 회원가입 및 로그인 기능 전담 + + private final UserRepository userRepository; + + // 회원가입 + public void signUp() { + + } + + // 로그인 + public void signIn() { + + } +} From 6ea6541c251f76512fd8a57427c63c50634d3362 Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 24 Sep 2023 01:58:55 +0900 Subject: [PATCH 006/371] =?UTF-8?q?:heavy=5Fplus=5Fsign:=20Chore:=20FoodSe?= =?UTF-8?q?rvice/Controller=20=EC=9D=98=EC=A1=B4=EC=84=B1=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20=EB=B0=8F=20=EC=9A=94=EA=B5=AC=EC=82=AC=ED=95=AD?= =?UTF-8?q?=EC=97=90=20=EB=94=B0=EB=A5=B8=20=EB=A9=94=EC=84=9C=EB=93=9C=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1=20(#3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../food/controller/FoodController.java | 5 ++ .../diareat/food/service/FoodService.java | 47 +++++++++++++++++++ 2 files changed, 52 insertions(+) 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 6d97ca5..06feadc 100644 --- a/src/main/java/com/diareat/diareat/food/controller/FoodController.java +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -1,4 +1,9 @@ package com.diareat.diareat.food.controller; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.RestController; + +@RequiredArgsConstructor +@RestController public class FoodController { } 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 282da96..a0702b2 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -1,4 +1,51 @@ package com.diareat.diareat.food.service; +import com.diareat.diareat.food.repository.FavoriteFoodRepository; +import com.diareat.diareat.food.repository.FoodRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@RequiredArgsConstructor +@Service public class FoodService { + + private final FoodRepository foodRepository; // 유저:음식은 1:다 + private final FavoriteFoodRepository favoriteFoodRepository; // 유저:즐찾음식은 1:다 + + // 촬영 후, 음식 정보 저장 + public Long saveFood() { + return null; + } + + // 음식 정보 수정 + public void updateFood() { + + } + + // 음식 삭제 + public void deleteFood() { + + } + + // 즐겨찾기에 음식 저장 + public Long saveFavoriteFood() { + return null; + } + + // 즐겨찾기 음식 수정 + public void updateFavoriteFood() { + + } + + // 즐겨찾기 해제 + public void deleteFavoriteFood() { + + } + + /** + * 메서드 구현 유의사항 + * 1. 메서드명은 동사로 시작 + * 2. 유효성 검사는 private void validateUser의 형태로 분리 + * 3. Repository에서 가져오고 OrElseThrow로 예외처리하는 부분이 반복되는 경우 private ??? get???ById 형태 메서드로 분리 + */ } From fee2f4d27f58cab91cbfdaebe0901e55e073b8c8 Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 24 Sep 2023 01:59:46 +0900 Subject: [PATCH 007/371] =?UTF-8?q?:heavy=5Fplus=5Fsign:=20Chore:=20UserSe?= =?UTF-8?q?rvice/Controller=20=EC=9D=98=EC=A1=B4=EC=84=B1=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20=EB=B0=8F=20=EC=9A=94=EA=B5=AC=EC=82=AC=ED=95=AD?= =?UTF-8?q?=EC=97=90=20=EB=94=B0=EB=A5=B8=20=EB=A9=94=EC=84=9C=EB=93=9C=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1=20(#3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/controller/UserController.java | 5 ++ .../diareat/user/service/UserService.java | 79 +++++++++++++++++++ 2 files changed, 84 insertions(+) diff --git a/src/main/java/com/diareat/diareat/user/controller/UserController.java b/src/main/java/com/diareat/diareat/user/controller/UserController.java index 278d037..d7be5f3 100644 --- a/src/main/java/com/diareat/diareat/user/controller/UserController.java +++ b/src/main/java/com/diareat/diareat/user/controller/UserController.java @@ -1,4 +1,9 @@ package com.diareat.diareat.user.controller; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.RestController; + +@RequiredArgsConstructor +@RestController public class UserController { } diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 12743fd..b86bd84 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -1,4 +1,83 @@ package com.diareat.diareat.user.service; +import com.diareat.diareat.food.domain.Food; +import com.diareat.diareat.food.repository.FavoriteFoodRepository; +import com.diareat.diareat.food.repository.FoodRepository; +import com.diareat.diareat.user.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@RequiredArgsConstructor +@Service public class UserService { + + private final UserRepository userRepository; + private final FoodRepository foodRepository; + private final FavoriteFoodRepository favoriteFoodRepository; + + // 회원정보 조회 + @Transactional(readOnly = true) + public void getUserInfo(Long userId) { + + } + + // 회원정보 수정 + @Transactional + public void updateUserInfo(Long userId) { + + } + + // 회원 탈퇴 + @Transactional + public void deleteUser(Long userId) { + + } + + // 유저가 특정 날짜에 섭취한 음식 조회 + @Transactional(readOnly = true) + public List getFoodByDate(Long userId, String date) { // 클라이언트가 넘길 날짜의 자료형 협의 필요 + + return null; + } + + // 유저가 특정 날짜에 섭취한 음식의 칼탄단지 총합 및 유저의 권장섭취량, 탄/단/지 구성 비율 조회 + @Transactional(readOnly = true) + public void getFoodNutrientByDate(Long userId, String date) { + + } + + // 유저의 주간 영양소 섭취량 및 탄/단/지 구성 비율 조회 + @Transactional(readOnly = true) + public void getNutrientInfoByWeek(Long userId, String week) { + + } + + // 유저의 월간 영양소 섭취량 및 탄/단/지 구성 비율 조회 + @Transactional(readOnly = true) + public void getNutrientInfoByMonth(Long userId, String month) { + + } + + // 최근 7일간 Best 3 음식 조회 + @Transactional(readOnly = true) + public void getBestThreeFoodByDate(Long userId, String date) { + + } + + // 최근 7일간 Worst 3 음식 조회 + @Transactional(readOnly = true) + public void getWorstThreeFoodByDate(Long userId, String date) { + + } + + /** + * 위 메서드 외 누락된 메서드가 존재할 수 있으며, 아래와 같은 추가적인 부가 기능을 구현할 가능성 있음 + * 1. 친구 추가 기능 + * 2. 친구 목록에 나를 포함하여 각 사람의 칼탄단지 섭취량 기준으로 정렬하는 랭킹 기능 + * 3. 주간 미션 기능 + * void라고 적혀있어도 실제 구현시 반환값이 필요하면 Dto를 생성해야 한다. + */ } From 938cc6c2186852df70d4cc770f58361ac5605bfb Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 12:22:04 +0900 Subject: [PATCH 008/371] =?UTF-8?q?=F0=9F=A9=B9Fix:=20User=20=EA=B0=9D?= =?UTF-8?q?=EC=B2=B4=20=EC=86=8D=EC=84=B1=EA=B0=92=20=EC=88=98=EC=A0=95=20?= =?UTF-8?q?(#5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/user/domain/User.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index 4cacc4d..8f4a99e 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -24,10 +24,12 @@ public class User { @JsonIgnore private String keyCode; // 로그인 식별키 - private int tall; // 키 + private int height; // 키 private int weight; // 몸무게 + private int gender; // 성별 (0: 남자, 1: 여자) + private int age; // 나이 private BaseNutrition baseNutrition; // 영양소 @@ -36,24 +38,25 @@ public class User { private List foods = new ArrayList<>(); // 생성 메서드 - public static User createUser(String name, String keyCode, int tall, int weight, int age, BaseNutrition baseNutrition) { + public static User createUser(String name, String keyCode, int height, int weight, int gender, int age, BaseNutrition baseNutrition) { User user = new User(); user.name = name; user.keyCode = keyCode; - user.tall = tall; + user.height = height; user.weight = weight; + user.gender = gender; user.age = age; user.baseNutrition = baseNutrition; return user; } - // 회원정보 수정 및 수정에 따른 영양소 재계산 - public void updateUser(String name, int tall, int weight, int age, BaseNutrition baseNutrition) { + // 회원정보 수정 + public void updateUser(String name, int height, int weight, int gender, int age, BaseNutrition baseNutrition) { this.name = name; - this.tall = tall; + this.height = height; this.weight = weight; + this.gender = gender; this.age = age; - // 계산공식 추후 추가 this.baseNutrition = baseNutrition; } } From e74fc7c0cf78cfe16b39d4c6c934a156a2db8272 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 12:23:40 +0900 Subject: [PATCH 009/371] =?UTF-8?q?=E2=9C=A8Feat:=20User=20=EA=B0=9D?= =?UTF-8?q?=EC=B2=B4=20Dto=20=EA=B5=AC=ED=98=84=20(#5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/dto/ResponseUserDto.java | 26 +++++++++++++++++++ .../diareat/user/dto/UpdateUserDto.java | 23 ++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java create mode 100644 src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java new file mode 100644 index 0000000..c0b4c07 --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java @@ -0,0 +1,26 @@ +package com.diareat.diareat.user.dto; + +import com.diareat.diareat.user.domain.BaseNutrition; +import com.diareat.diareat.user.domain.User; +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class ResponseUserDto { + + private String name; + private int height; + private int weight; + private int gender; + private int age; + private BaseNutrition baseNutrition; + + public ResponseUserDto of(String userName, int userHeight, int userWeight, int userGender, int userAge, BaseNutrition userBaseNutrition) { + return new ResponseUserDto(userName, userHeight, userWeight, userGender, userAge, userBaseNutrition); + } + + public ResponseUserDto from(User user) { + return new ResponseUserDto(user.getName(), user.getHeight(), user.getWeight(), user.getGender(), user.getAge(), user.getBaseNutrition()); + } +} diff --git a/src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java b/src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java new file mode 100644 index 0000000..e16e46a --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java @@ -0,0 +1,23 @@ +package com.diareat.diareat.user.dto; + +import com.diareat.diareat.user.domain.BaseNutrition; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class UpdateUserDto { + + private Long id; + private String name; + private int height; + private int weight; + private int age; + private BaseNutrition baseNutrition; + + public UpdateUserDto of(Long userId, String userName, int userHeight, int userWeight, int userAge, BaseNutrition userBaseNutrition) { + return new UpdateUserDto(userId, userName, userHeight, userWeight, userAge, userBaseNutrition); + } +} From 85271cf0a49598e10502fe7177fbadd0afa0924b Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 12:52:33 +0900 Subject: [PATCH 010/371] =?UTF-8?q?=E2=9C=8F=EF=B8=8FChore:=20UserDto=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1=EB=A9=94=EC=84=9C=EB=93=9C=20static=20?= =?UTF-8?q?=EB=88=84=EB=9D=BD=20=EC=88=98=EC=A0=95=20(#5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/user/dto/ResponseUserDto.java | 4 ++-- src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java index c0b4c07..4f8b877 100644 --- a/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java @@ -16,11 +16,11 @@ public class ResponseUserDto { private int age; private BaseNutrition baseNutrition; - public ResponseUserDto of(String userName, int userHeight, int userWeight, int userGender, int userAge, BaseNutrition userBaseNutrition) { + public static ResponseUserDto of(String userName, int userHeight, int userWeight, int userGender, int userAge, BaseNutrition userBaseNutrition) { return new ResponseUserDto(userName, userHeight, userWeight, userGender, userAge, userBaseNutrition); } - public ResponseUserDto from(User user) { + public static ResponseUserDto from(User user) { return new ResponseUserDto(user.getName(), user.getHeight(), user.getWeight(), user.getGender(), user.getAge(), user.getBaseNutrition()); } } diff --git a/src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java b/src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java index e16e46a..a882577 100644 --- a/src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java @@ -10,14 +10,14 @@ @AllArgsConstructor public class UpdateUserDto { - private Long id; + private Long userId; private String name; private int height; private int weight; private int age; private BaseNutrition baseNutrition; - public UpdateUserDto of(Long userId, String userName, int userHeight, int userWeight, int userAge, BaseNutrition userBaseNutrition) { + public static UpdateUserDto of(Long userId, String userName, int userHeight, int userWeight, int userAge, BaseNutrition userBaseNutrition) { return new UpdateUserDto(userId, userName, userHeight, userWeight, userAge, userBaseNutrition); } } From 61aeb5406ae1fd4a0459b0d472c4a516e4f320d0 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 14:07:48 +0900 Subject: [PATCH 011/371] =?UTF-8?q?=E2=9C=8F=EF=B8=8FChore:=20Food?= =?UTF-8?q?=EC=99=80=20FavoriteFood=20=EA=B0=84=20=EC=97=B0=EA=B4=80?= =?UTF-8?q?=EA=B4=80=EA=B3=84=20=EC=A1=B0=EC=A0=95=20(#5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/domain/FavoriteFood.java | 33 +++++++++++++++---- .../com/diareat/diareat/food/domain/Food.java | 11 +++++-- 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java index 444ae2b..ca1f811 100644 --- a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java +++ b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java @@ -7,8 +7,6 @@ import lombok.NoArgsConstructor; import javax.persistence.*; -import java.time.LocalDate; -import java.time.LocalTime; @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @@ -21,7 +19,7 @@ public class FavoriteFood { private String name; - @OneToOne(fetch = FetchType.LAZY) + @OneToOne(fetch = FetchType.LAZY, orphanRemoval = false) // 즐찾음식이 삭제되어도 음식은 삭제되지 않음 @JoinColumn(name = "food_id") private Food food; @@ -29,11 +27,32 @@ public class FavoriteFood { @JoinColumn(name = "user_id") private User user; - - private LocalDate date; - - private LocalTime time; + private int count = 0; // 즐겨찾기에서 선택되어 바로 음식으로 추가된 횟수 private BaseNutrition baseNutrition; + public void addCount(){ + this.count++; + } + + // 생성 메서드 + public static FavoriteFood createFavoriteFood(String name, User user, BaseNutrition baseNutrition) { + FavoriteFood favoriteFood = new FavoriteFood(); + favoriteFood.name = name; + favoriteFood.user = user; + favoriteFood.baseNutrition = baseNutrition; + return favoriteFood; + } + + // 즐겨찾기 음식 정보 수정 + public void updateFavoriteFood(String name, BaseNutrition baseNutrition) { + this.name = name; + this.baseNutrition = baseNutrition; + } + + // 즐겨찾기 음식 정보로 새 음식 정보 생성 + public static Food createFoodFromFavoriteFood(FavoriteFood favoriteFood) { + favoriteFood.addCount(); + return Food.createFood(favoriteFood.getName(), favoriteFood.getUser(), favoriteFood.getBaseNutrition()); + } } 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 3d0ad0e..60414dd 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -5,6 +5,7 @@ import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; +import org.springframework.data.annotation.CreatedDate; import javax.persistence.*; import java.time.LocalDate; @@ -25,6 +26,11 @@ public class Food { @JoinColumn(name = "user_id") private User user; + @OneToOne(fetch = FetchType.LAZY, orphanRemoval = false) // 음식이 삭제되어도 즐찾음식은 삭제되지 않음 + @JoinColumn(name = "favorite_food_id") + private FavoriteFood favoriteFood; + + @CreatedDate private LocalDate date; private LocalTime time; @@ -32,12 +38,11 @@ public class Food { private BaseNutrition baseNutrition; // 생성 메서드 - public static Food createFood(String name, User user, LocalDate date, LocalTime time, BaseNutrition baseNutrition) { + public static Food createFood(String name, User user, BaseNutrition baseNutrition) { Food food = new Food(); food.name = name; food.user = user; - food.date = date; - food.time = time; + food.time = LocalTime.now(); food.baseNutrition = baseNutrition; return food; } From 93cdebf6764d2f1110571ed28cda96c33116cbab Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 14:08:23 +0900 Subject: [PATCH 012/371] =?UTF-8?q?=E2=9C=A8=EF=B8=8FFeat:=20FoodDto=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20(#5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/dto/CreateFoodDto.java | 20 +++++++++++++ .../diareat/food/dto/ResponseFoodDto.java | 29 +++++++++++++++++++ .../diareat/food/dto/UpdateFoodDto.java | 20 +++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java create mode 100644 src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java create mode 100644 src/main/java/com/diareat/diareat/food/dto/UpdateFoodDto.java diff --git a/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java new file mode 100644 index 0000000..1b4a7df --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java @@ -0,0 +1,20 @@ +package com.diareat.diareat.food.dto; + +import com.diareat.diareat.user.domain.BaseNutrition; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class CreateFoodDto { + + private Long userId; + private String name; + private BaseNutrition baseNutrition; + + public static CreateFoodDto of(Long userId, String name, BaseNutrition baseNutrition) { + return new CreateFoodDto(userId, name, baseNutrition); + } +} diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java new file mode 100644 index 0000000..097406e --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java @@ -0,0 +1,29 @@ +package com.diareat.diareat.food.dto; + +import com.diareat.diareat.food.domain.Food; +import com.diareat.diareat.user.domain.BaseNutrition; +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.time.LocalDate; +import java.time.LocalTime; + +@Getter +@AllArgsConstructor +public class ResponseFoodDto { + + private Long foodId; + private Long userId; + private String name; + private LocalDate date; + private LocalTime time; + private BaseNutrition baseNutrition; + + public static ResponseFoodDto of(Long foodId, Long userId, String name, LocalDate date, LocalTime time, BaseNutrition baseNutrition) { + return new ResponseFoodDto(foodId, userId, name, date, time, baseNutrition); + } + + public static ResponseFoodDto from(Food food) { + return new ResponseFoodDto(food.getId(), food.getUser().getId(), food.getName(), food.getDate(), food.getTime(), food.getBaseNutrition()); + } +} diff --git a/src/main/java/com/diareat/diareat/food/dto/UpdateFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/UpdateFoodDto.java new file mode 100644 index 0000000..7471e85 --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/dto/UpdateFoodDto.java @@ -0,0 +1,20 @@ +package com.diareat.diareat.food.dto; + +import com.diareat.diareat.user.domain.BaseNutrition; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class UpdateFoodDto { + + private Long foodId; + private String name; + private BaseNutrition baseNutrition; + + public static UpdateFoodDto of(Long foodId, String name, BaseNutrition baseNutrition) { + return new UpdateFoodDto(foodId, name, baseNutrition); + } +} From c6bb0befcd851f66130f1b5ae16dabcc1feff1d0 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 14:08:35 +0900 Subject: [PATCH 013/371] =?UTF-8?q?=E2=9C=A8=EF=B8=8FFeat:=20FavoriteFoodD?= =?UTF-8?q?to=20=EA=B5=AC=ED=98=84=20(#5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../food/dto/CreateFavoriteFoodDto.java | 21 ++++++++++++++ .../food/dto/ResponseFavoriteFoodDto.java | 28 +++++++++++++++++++ .../food/dto/UpdateFavoriteFoodDto.java | 20 +++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/food/dto/CreateFavoriteFoodDto.java create mode 100644 src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java create mode 100644 src/main/java/com/diareat/diareat/food/dto/UpdateFavoriteFoodDto.java diff --git a/src/main/java/com/diareat/diareat/food/dto/CreateFavoriteFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/CreateFavoriteFoodDto.java new file mode 100644 index 0000000..fce25be --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/dto/CreateFavoriteFoodDto.java @@ -0,0 +1,21 @@ +package com.diareat.diareat.food.dto; + +import com.diareat.diareat.user.domain.BaseNutrition; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class CreateFavoriteFoodDto { + + private Long foodId; + private Long userId; + private String name; + private BaseNutrition baseNutrition; + + public static CreateFavoriteFoodDto of(Long foodId, Long userId, String name, BaseNutrition baseNutrition) { + return new CreateFavoriteFoodDto(foodId, userId, name, baseNutrition); + } +} diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java new file mode 100644 index 0000000..78678bb --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java @@ -0,0 +1,28 @@ +package com.diareat.diareat.food.dto; + +import com.diareat.diareat.food.domain.FavoriteFood; +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class ResponseFavoriteFoodDto { + + private Long favoriteFoodId; + private String name; + private String baseNutrition; + private int count; + + public static ResponseFavoriteFoodDto of(Long favoriteFoodId, String name, String baseNutrition, int count) { + return new ResponseFavoriteFoodDto(favoriteFoodId, name, baseNutrition, count); + } + + public static ResponseFavoriteFoodDto from(FavoriteFood favoriteFood) { + return new ResponseFavoriteFoodDto( + favoriteFood.getId(), + favoriteFood.getName(), + favoriteFood.getBaseNutrition().toString(), + favoriteFood.getCount() + ); + } +} diff --git a/src/main/java/com/diareat/diareat/food/dto/UpdateFavoriteFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/UpdateFavoriteFoodDto.java new file mode 100644 index 0000000..705591e --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/dto/UpdateFavoriteFoodDto.java @@ -0,0 +1,20 @@ +package com.diareat.diareat.food.dto; + +import com.diareat.diareat.user.domain.BaseNutrition; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class UpdateFavoriteFoodDto { + + private Long favoriteFoodId; + private String name; + private BaseNutrition baseNutrition; + + public static UpdateFavoriteFoodDto of(Long favoriteFoodId, String name, BaseNutrition baseNutrition) { + return new UpdateFavoriteFoodDto(favoriteFoodId, name, baseNutrition); + } +} From ef2a95dc28f86ae0ebb98c7f14a8e38f9214a774 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Mon, 2 Oct 2023 14:54:07 +0900 Subject: [PATCH 014/371] =?UTF-8?q?:construction=5Fworker:=20feat:=20?= =?UTF-8?q?=EA=B8=B0=EB=B3=B8=20CI=20=ED=85=9C=ED=94=8C=EB=A6=BF=20?= =?UTF-8?q?=ED=8C=8C=EC=9D=BC=20=EC=83=9D=EC=84=B1=20(#10)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/diareat-CI.yml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .github/workflows/diareat-CI.yml diff --git a/.github/workflows/diareat-CI.yml b/.github/workflows/diareat-CI.yml new file mode 100644 index 0000000..a5b8110 --- /dev/null +++ b/.github/workflows/diareat-CI.yml @@ -0,0 +1,27 @@ +name: Java CI with Gradle + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master" ] + +permissions: + contents: read + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 11 + uses: actions/setup-java@v3 + with: + java-version: '11' + distribution: 'temurin' + - name: Build with Gradle + uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0 + with: + arguments: build From 3c9c3aa24cb07d41e93da4f86cf12fc9eeae05b2 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 15:53:57 +0900 Subject: [PATCH 015/371] =?UTF-8?q?=E2=9C=A8Feat:=20CreateUserDto=20?= =?UTF-8?q?=EB=88=84=EB=9D=BD=20=EB=B0=98=EC=98=81=20(#7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/dto/CreateUserDto.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/user/dto/CreateUserDto.java diff --git a/src/main/java/com/diareat/diareat/user/dto/CreateUserDto.java b/src/main/java/com/diareat/diareat/user/dto/CreateUserDto.java new file mode 100644 index 0000000..481bef4 --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/dto/CreateUserDto.java @@ -0,0 +1,22 @@ +package com.diareat.diareat.user.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class CreateUserDto { + + private String name; + private String keyCode; + private int gender; + private int height; + private int weight; + private int age; + + public static CreateUserDto of(String name, String keyCode, int gender, int height, int weight, int age){ + return new CreateUserDto(name, keyCode, gender, height, weight, age); + } +} From e9ae5249ba53460475f356bb40212a1d541881d0 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 15:54:50 +0900 Subject: [PATCH 016/371] =?UTF-8?q?=E2=9C=A8Feat:=20=EC=9C=A0=EC=A0=80=20E?= =?UTF-8?q?ntity=EC=99=80=20=EC=A6=90=EC=B0=BE=EC=9D=8C=EC=8B=9D,=20?= =?UTF-8?q?=ED=8C=94=EB=A1=9C=EC=9A=B0=EC=9C=A0=EC=A0=80=20=EC=97=B0?= =?UTF-8?q?=EA=B4=80=EA=B4=80=EA=B3=84=20=EC=84=A4=EC=A0=95=20(#7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/user/domain/User.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index 8f4a99e..6753004 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -1,5 +1,6 @@ package com.diareat.diareat.user.domain; +import com.diareat.diareat.food.domain.FavoriteFood; import com.diareat.diareat.food.domain.Food; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AccessLevel; @@ -37,6 +38,12 @@ public class User { @OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) // 유저가 탈퇴하면 촬영한 음식도 삭제 private List foods = new ArrayList<>(); + @OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) // 유저가 탈퇴하면 즐겨찾기 음식도 삭제 + private List favoriteFoods = new ArrayList<>(); + + @OneToMany(mappedBy = "user") // 유저의 팔로우 목록 + private List followings = new ArrayList<>(); + // 생성 메서드 public static User createUser(String name, String keyCode, int height, int weight, int gender, int age, BaseNutrition baseNutrition) { User user = new User(); From 98784dbe5f7ac55b97a8450cd5015b5a25bb34dd Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 15:56:26 +0900 Subject: [PATCH 017/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20Test:=20UserSe?= =?UTF-8?q?rviceTest=20=EC=BD=94=EB=93=9C=20=EC=84=A0=20=EC=9E=91=EC=84=B1?= =?UTF-8?q?=20(#7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/UserServiceTest.java | 125 ++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 src/test/java/com/diareat/diareat/service/UserServiceTest.java diff --git a/src/test/java/com/diareat/diareat/service/UserServiceTest.java b/src/test/java/com/diareat/diareat/service/UserServiceTest.java new file mode 100644 index 0000000..d6ab5e2 --- /dev/null +++ b/src/test/java/com/diareat/diareat/service/UserServiceTest.java @@ -0,0 +1,125 @@ +package com.diareat.diareat.service; + +import com.diareat.diareat.user.domain.User; +import com.diareat.diareat.user.dto.CreateUserDto; +import com.diareat.diareat.user.dto.ResponseUserDto; +import com.diareat.diareat.user.dto.UpdateUserDto; +import com.diareat.diareat.user.repository.UserRepository; +import com.diareat.diareat.user.service.UserService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + + +@SpringBootTest +class UserServiceTest { + + @Autowired + UserService userService; + + @Autowired + UserRepository userRepository; + + @BeforeEach + public void setUp() { + userRepository.deleteAll(); + } + + @Test + void testSaveAndGetUserInfo() { // 회원정보 저장 및 조회 + // given + Long userId = 1L; + + // when + userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); + ResponseUserDto responseUserDto = userService.getUserInfo(userId); + + // 검증: 올바른 결과를 반환하는지 확인 + assertNotNull(responseUserDto); + assertEquals("testUser", responseUserDto.getName()); + } + + @Test + void testUpdateUserInfo() { // 회원정보 수정 + + // given + Long userId = 1L; + userService.saveUser(CreateUserDto.of("1", "testPassword", 180, 75, 1, 25)); + + // when + UpdateUserDto updateUserDto = UpdateUserDto.of(1L, "2", 185, 70, 75, null); + userService.updateUserInfo(updateUserDto); + ResponseUserDto responseUserDto = userService.getUserInfo(userId); + + // then + assertNotNull(responseUserDto); + assertEquals("2", responseUserDto.getName()); + assertEquals(185, responseUserDto.getHeight()); + assertEquals(70, responseUserDto.getWeight()); + } + + @Test + void testDeleteUser() { // 회원 탈퇴 + // given + Long userId = 1L; + userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); + + // when + userService.deleteUser(userId); + + // then + assertEquals(Optional.empty(), userRepository.findById(userId)); + } + + @Test + void testSearchUserName() { + // given + userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); + userService.saveUser(CreateUserDto.of("hello", "testPassword", 180, 75, 1, 25)); + + // when + String name = "testUser"; + List users = userService.searchUser(name); + + // then + assertEquals(1, users.size()); + } + + @Test + void testFollowUser() { // 회원이 특정 회원 팔로우 + // given + Long userId = 1L; + Long followId = 2L; + userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); + userService.saveUser(CreateUserDto.of("followUser", "testPassword", 180, 75, 1, 25)); + + // when + userService.followUser(userId, followId); + + // then + assertEquals(1, userRepository.findById(userId).get().getFollowings().size()); + } + + @Test + void testUnfollowUser() { // 회원이 특정 회원 팔로우 취소 + // given + Long userId = 1L; + Long followId = 2L; + userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); + userService.saveUser(CreateUserDto.of("followUser", "testPassword", 180, 75, 1, 25)); + + // when + userService.followUser(userId, followId); + userService.unfollowUser(userId, followId); + + // then + assertEquals(0, userRepository.findById(userId).get().getFollowings().size()); + } +} From 75ea058535d3daac51c8604acf1014d0dcaf4c77 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Mon, 2 Oct 2023 16:10:14 +0900 Subject: [PATCH 018/371] =?UTF-8?q?:construction=5Fworker:=20feat:=20Diare?= =?UTF-8?q?at=20=EB=B9=8C=EB=93=9C=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1=20(PR=EC=A0=84=EC=9A=A9)=20(#10)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/{diareat-CI.yml => diareat-Build.yml} | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) rename .github/workflows/{diareat-CI.yml => diareat-Build.yml} (88%) diff --git a/.github/workflows/diareat-CI.yml b/.github/workflows/diareat-Build.yml similarity index 88% rename from .github/workflows/diareat-CI.yml rename to .github/workflows/diareat-Build.yml index a5b8110..656237f 100644 --- a/.github/workflows/diareat-CI.yml +++ b/.github/workflows/diareat-Build.yml @@ -1,8 +1,6 @@ -name: Java CI with Gradle +name: Diareat Build Test on: - push: - branches: [ "master" ] pull_request: branches: [ "master" ] @@ -25,3 +23,4 @@ jobs: uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0 with: arguments: build + From 31ed2dec18b2a912502585cbf86930a7f6978fda Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Mon, 2 Oct 2023 16:18:00 +0900 Subject: [PATCH 019/371] =?UTF-8?q?:construction=5Fworker:=20feat:=20Diare?= =?UTF-8?q?at=20CI/CD=20=EA=B5=AC=EC=B6=95=20(#10)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/Diareat-CICD.yml | 63 ++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 .github/workflows/Diareat-CICD.yml diff --git a/.github/workflows/Diareat-CICD.yml b/.github/workflows/Diareat-CICD.yml new file mode 100644 index 0000000..65910bc --- /dev/null +++ b/.github/workflows/Diareat-CICD.yml @@ -0,0 +1,63 @@ +name: Diareat CI/CD + +on: + push: + branches: [ "master" ] + +permissions: + contents: read + +jobs: + CI: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 11 + uses: actions/setup-java@v3 + with: + java-version: '11' + distribution: 'temurin' + + - name: Build with Gradle + uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0 + with: + arguments: build + + - name: Docker login + uses: docker/login-action@v3.0.0 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + logout: true + + - name: Build and push to DockerHub + run: | + docker build -t ${{ secrets.PROJECT_NAME }} . + docker tag ${{ secrets.PROJECT_NAME }}:latest ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest + docker push ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest + + CD: + needs: CI + runs-on: ubuntu-latest + + steps: + - name: Deploy to EC2 / Check Server status + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.EC2_HOST }} + username: ${{ secrets.EC2_USERNAME }} + key: ${{ secrets.EC2_KEY }} + + script: | + echo "${{ secrets.DOCKERHUB_TOKEN }}" | sudo docker login -u "${{ secrets.DOCKERHUB_USERNAME }}" --password-stdin + sudo docker rm $(sudo docker stop $(sudo docker ps -a -q --filter ancestor=${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest --format="{{.ID}}")) + sudo docker rmi ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest + sudo docker pull ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest + + echo "Some Environment Variable" > env.list + + sudo docker run -d --env-file env.list --name Diareat_Backend ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest + sleep 10s + sudo docker ps | grep ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest From e476c6bc67d37e6d6cd2bab9c535b3ce9781d20f Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 16:26:26 +0900 Subject: [PATCH 020/371] =?UTF-8?q?:necktie:=20Feat:=20Food=20Entity=20?= =?UTF-8?q?=EC=A6=90=EA=B2=A8=EC=B0=BE=EA=B8=B0=20=EB=93=B1=EB=A1=9D=20?= =?UTF-8?q?=EC=97=AC=EB=B6=80=20=ED=99=95=EC=9D=B8=20=EB=A9=94=EC=84=9C?= =?UTF-8?q?=EB=93=9C=20=EC=B6=94=EA=B0=80=20(#7)?= 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 | 4 ++++ .../java/com/diareat/diareat/food/dto/ResponseFoodDto.java | 7 ++++--- 2 files changed, 8 insertions(+), 3 deletions(-) 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 60414dd..7b98ef5 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -52,4 +52,8 @@ public void updateFood(String name, BaseNutrition baseNutrition) { this.name = name; this.baseNutrition = baseNutrition; } + + public boolean isFavorite() { + return this.favoriteFood != null; + } } diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java index 097406e..1430c32 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java @@ -18,12 +18,13 @@ public class ResponseFoodDto { private LocalDate date; private LocalTime time; private BaseNutrition baseNutrition; + private boolean isFavorite; - public static ResponseFoodDto of(Long foodId, Long userId, String name, LocalDate date, LocalTime time, BaseNutrition baseNutrition) { - return new ResponseFoodDto(foodId, userId, name, date, time, baseNutrition); + public static ResponseFoodDto of(Long foodId, Long userId, String name, LocalDate date, LocalTime time, BaseNutrition baseNutrition, boolean isFavorite) { + return new ResponseFoodDto(foodId, userId, name, date, time, baseNutrition, isFavorite); } public static ResponseFoodDto from(Food food) { - return new ResponseFoodDto(food.getId(), food.getUser().getId(), food.getName(), food.getDate(), food.getTime(), food.getBaseNutrition()); + return new ResponseFoodDto(food.getId(), food.getUser().getId(), food.getName(), food.getDate(), food.getTime(), food.getBaseNutrition(), food.isFavorite()); } } From fb1005e1bf89a503cd084326142d1f1d92584455 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 16:51:31 +0900 Subject: [PATCH 021/371] =?UTF-8?q?=E2=9C=A8Feat:=20=EA=B8=B0=EB=B3=B8?= =?UTF-8?q?=EC=A0=81=EC=9D=B8=20UserService=20=EB=A9=94=EC=84=9C=EB=93=9C?= =?UTF-8?q?=20=EA=B5=AC=EC=B6=95=20(#7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/repository/UserRepository.java | 3 + .../diareat/user/service/UserService.java | 91 +++++++++++++------ 2 files changed, 65 insertions(+), 29 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/repository/UserRepository.java b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java index 57b3beb..2c45f0a 100644 --- a/src/main/java/com/diareat/diareat/user/repository/UserRepository.java +++ b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java @@ -3,5 +3,8 @@ import com.diareat.diareat.user.domain.User; import org.springframework.data.jpa.repository.JpaRepository; +import java.util.List; + public interface UserRepository extends JpaRepository { + List findAllByNameContaining(String name); // 회원이 팔로우를 위해 검색한 유저 목록 조회 } diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index b86bd84..46b5a12 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -1,9 +1,14 @@ package com.diareat.diareat.user.service; -import com.diareat.diareat.food.domain.Food; import com.diareat.diareat.food.repository.FavoriteFoodRepository; import com.diareat.diareat.food.repository.FoodRepository; +import com.diareat.diareat.user.domain.User; +import com.diareat.diareat.user.dto.CreateUserDto; +import com.diareat.diareat.user.dto.ResponseUserDto; +import com.diareat.diareat.user.dto.UpdateUserDto; import com.diareat.diareat.user.repository.UserRepository; +import com.diareat.diareat.util.api.ResponseCode; +import com.diareat.diareat.util.exception.UserException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -18,15 +23,24 @@ public class UserService { private final FoodRepository foodRepository; private final FavoriteFoodRepository favoriteFoodRepository; + // 회원정보 저장 + @Transactional + public Long saveUser(CreateUserDto createUserDto) { + + return null; + } + // 회원정보 조회 @Transactional(readOnly = true) - public void getUserInfo(Long userId) { - + public ResponseUserDto getUserInfo(Long userId) { + return userRepository.findById(userId) + .map(ResponseUserDto::from) + .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); } // 회원정보 수정 @Transactional - public void updateUserInfo(Long userId) { + public void updateUserInfo(UpdateUserDto updateUserDto) { } @@ -36,48 +50,67 @@ public void deleteUser(Long userId) { } - // 유저가 특정 날짜에 섭취한 음식 조회 + // 회원이 팔로우를 위해 검색한 유저 목록 조회 @Transactional(readOnly = true) - public List getFoodByDate(Long userId, String date) { // 클라이언트가 넘길 날짜의 자료형 협의 필요 + public List searchUser(String name) { return null; } - // 유저가 특정 날짜에 섭취한 음식의 칼탄단지 총합 및 유저의 권장섭취량, 탄/단/지 구성 비율 조회 - @Transactional(readOnly = true) - public void getFoodNutrientByDate(Long userId, String date) { + // 회원이 특정 회원 팔로우 + @Transactional + public void followUser(Long userId, Long followId) { } - // 유저의 주간 영양소 섭취량 및 탄/단/지 구성 비율 조회 - @Transactional(readOnly = true) - public void getNutrientInfoByWeek(Long userId, String week) { + // 회원이 특정 회원 팔로우 취소 + @Transactional + public void unfollowUser(Long userId, Long unfollowId) { } - // 유저의 월간 영양소 섭취량 및 탄/단/지 구성 비율 조회 - @Transactional(readOnly = true) - public void getNutrientInfoByMonth(Long userId, String month) { + /* + 아래 메서드들은 원래 두 패키지 모두에 존재할 수 있는 혼합적인 의미를 가지고 있으며, 일단 FoodService에서 구현을 담당할 예정이다. + // 유저의 즐겨찾기 음식 목록 조회 + public void getFavoriteFoodList(Long userId) { - } + } - // 최근 7일간 Best 3 음식 조회 - @Transactional(readOnly = true) - public void getBestThreeFoodByDate(Long userId, String date) { + // 유저의 특정 날짜에 먹은 음식 목록 조회 + public void getFoodListByDate(Long userId, LocalDate date) { - } + } - // 최근 7일간 Worst 3 음식 조회 - @Transactional(readOnly = true) - public void getWorstThreeFoodByDate(Long userId, String date) { + // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) + public void getNutritionSumByDate(Long userId, LocalDate date) { - } + } + + // 유저의 최근 7일간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) + public void getNutritionSumByWeek(Long userId) { + + } + + // 유저의 최근 1개월간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) + public void getNutritionSumByMonth(Long userId) { + + } + + // 유저의 최근 7일간의 Best 3 음식 조회 (dto 구체적 협의 필요) + public void getBestFoodByWeek(Long userId) { + + } + + // 유저의 최근 7일간의 Worst 3 음식 조회 (dto 구체적 협의 필요) + public void getWorstFoodByWeek(Long userId) { + + } + */ /** - * 위 메서드 외 누락된 메서드가 존재할 수 있으며, 아래와 같은 추가적인 부가 기능을 구현할 가능성 있음 - * 1. 친구 추가 기능 - * 2. 친구 목록에 나를 포함하여 각 사람의 칼탄단지 섭취량 기준으로 정렬하는 랭킹 기능 - * 3. 주간 미션 기능 - * void라고 적혀있어도 실제 구현시 반환값이 필요하면 Dto를 생성해야 한다. + * 위 메서드 외 누락된 메서드가 존재할 수 있으며, UserService에는 아래와 같은 추가적인 부가 기능을 구현할 가능성이 있다. + * 1. 친구 추가 기능 (팔로우 기능 구현 중) + * 2. 친구 목록에 나를 포함하여 각 사람의 칼탄단지 섭취량 기준으로 섭취 현황을 채점(?)하여 정렬하는 랭킹 기능 + * 3. 주간 과제 기능? -> 2번과 연계 가능 */ } From 89ded607c63a0d4718fa013cf053228c78b3e72f Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 2 Oct 2023 17:51:24 +0900 Subject: [PATCH 022/371] =?UTF-8?q?:construction=5Fworker:=20feat:=20Docke?= =?UTF-8?q?rfile=20=EC=9E=91=EC=84=B1=20(#10)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Dockerfile | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Dockerfile diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..772a7c2 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM gradle:8.2.1-jdk11 AS build + +COPY --chown=gradle:gradle . /home/gradle/src +WORKDIR /home/gradle/src +RUN gradle build --no-daemon + +FROM openjdk:11-jre-slim + +EXPOSE 8080 +COPY --from=build /home/gradle/src/build/libs/*.jar /app/app.jar + +ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/app/app.jar"] From 1e369af8d7ff208513a284485b3df965710241e5 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 2 Oct 2023 17:52:45 +0900 Subject: [PATCH 023/371] :closed_lock_with_key: feat: add application-db.properties with ENV (#10) --- .gitignore | 4 +--- src/main/resources/application-db.properties | 11 +++++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 src/main/resources/application-db.properties diff --git a/.gitignore b/.gitignore index cf851a2..e48b6be 100644 --- a/.gitignore +++ b/.gitignore @@ -34,6 +34,4 @@ out/ /.nb-gradle/ ### VS Code ### -.vscode/ - -application-db.properties +.vscode/ \ No newline at end of file diff --git a/src/main/resources/application-db.properties b/src/main/resources/application-db.properties new file mode 100644 index 0000000..1a2cded --- /dev/null +++ b/src/main/resources/application-db.properties @@ -0,0 +1,11 @@ +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +spring.jpa.hibernate.ddl-auto=create + +# Remote DB +spring.datasource.url=${DB_ENDPOINT} +spring.datasource.username=${DB_USERNAME} +spring.datasource.password=${DB_PASSWORD} + +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +spring.jpa.properties.hibernate.format_sql=true From 990a7da83e292ae0445f3fabe7c3241d23e6a143 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 2 Oct 2023 17:56:41 +0900 Subject: [PATCH 024/371] :construction_worker: feat: ignore test temporarily (#10) --- .github/workflows/diareat-Build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/diareat-Build.yml b/.github/workflows/diareat-Build.yml index 656237f..88ff4d3 100644 --- a/.github/workflows/diareat-Build.yml +++ b/.github/workflows/diareat-Build.yml @@ -22,5 +22,5 @@ jobs: - name: Build with Gradle uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0 with: - arguments: build + arguments: build -x test From b00dbcd130e98a48eca4eff98e6f7f06d84ef2ed Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 2 Oct 2023 18:04:35 +0900 Subject: [PATCH 025/371] :construction_worker: feat: add env.list to CI/CD.yaml (#10) --- .github/workflows/Diareat-CICD.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/Diareat-CICD.yml b/.github/workflows/Diareat-CICD.yml index 65910bc..e90c875 100644 --- a/.github/workflows/Diareat-CICD.yml +++ b/.github/workflows/Diareat-CICD.yml @@ -56,7 +56,10 @@ jobs: sudo docker rmi ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest sudo docker pull ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest - echo "Some Environment Variable" > env.list + echo "DB_ENDPOINT=${{ secrets.DB_ENDPOINT }}" > env.list + echo "DB_USERNAME=${{ secrets.DB_USERNAME }}" >> env.list + echo "DB_PASSWORD=${{ secrets.DB_PASSWORD }}" >> env.list + sudo docker run -d --env-file env.list --name Diareat_Backend ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest sleep 10s From c8bd0969afa328fc6acce4b4a0b4dac6acfad9a3 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 2 Oct 2023 18:11:44 +0900 Subject: [PATCH 026/371] :construction_worker: feat: add unit test (#10) --- .github/workflows/diareat-Build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/diareat-Build.yml b/.github/workflows/diareat-Build.yml index 88ff4d3..656237f 100644 --- a/.github/workflows/diareat-Build.yml +++ b/.github/workflows/diareat-Build.yml @@ -22,5 +22,5 @@ jobs: - name: Build with Gradle uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0 with: - arguments: build -x test + arguments: build From 0a34877d950768303eac443489e2f99659527dfe Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 18:15:55 +0900 Subject: [PATCH 027/371] =?UTF-8?q?=E2=9C=A8Feat:=20User=20Entity=20?= =?UTF-8?q?=ED=8C=94=EB=A1=9C=EC=9A=B0=20=EA=B8=B0=EB=8A=A5=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20(#7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/user/domain/User.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index 6753004..9807cb9 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -58,12 +58,19 @@ public static User createUser(String name, String keyCode, int height, int weigh } // 회원정보 수정 - public void updateUser(String name, int height, int weight, int gender, int age, BaseNutrition baseNutrition) { + public void updateUser(String name, int height, int weight, int age, BaseNutrition baseNutrition) { this.name = name; this.height = height; this.weight = weight; - this.gender = gender; this.age = age; this.baseNutrition = baseNutrition; } + + public void followUser(User user) { + this.followings.add(user); + } + + public void unfollowUser(User user) { + this.followings.remove(user); + } } From 7ebd26759e0a60aea5cfd0e15c68d655ec3f1f98 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 18:24:06 +0900 Subject: [PATCH 028/371] =?UTF-8?q?=E2=9C=A8Feat:=20UserService=20?= =?UTF-8?q?=EC=A3=BC=EC=9A=94=20=EB=A9=94=EC=84=9C=EB=93=9C=201=EC=B0=A8?= =?UTF-8?q?=20=EA=B5=AC=ED=98=84=20(#7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/dto/ResponseResearchUserDto.java | 16 ++++++ .../diareat/user/service/UserService.java | 49 ++++++++++++------- 2 files changed, 46 insertions(+), 19 deletions(-) create mode 100644 src/main/java/com/diareat/diareat/user/dto/ResponseResearchUserDto.java diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseResearchUserDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseResearchUserDto.java new file mode 100644 index 0000000..24aac2f --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/dto/ResponseResearchUserDto.java @@ -0,0 +1,16 @@ +package com.diareat.diareat.user.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class ResponseResearchUserDto { + + private Long userId; + private String name; + + public static ResponseResearchUserDto of(Long userId, String name) { + return new ResponseResearchUserDto(userId, name); + } +} diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 46b5a12..f27f809 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -1,9 +1,9 @@ package com.diareat.diareat.user.service; -import com.diareat.diareat.food.repository.FavoriteFoodRepository; -import com.diareat.diareat.food.repository.FoodRepository; +import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; import com.diareat.diareat.user.dto.CreateUserDto; +import com.diareat.diareat.user.dto.ResponseResearchUserDto; import com.diareat.diareat.user.dto.ResponseUserDto; import com.diareat.diareat.user.dto.UpdateUserDto; import com.diareat.diareat.user.repository.UserRepository; @@ -14,63 +14,75 @@ import org.springframework.transaction.annotation.Transactional; import java.util.List; +import java.util.stream.Collectors; @RequiredArgsConstructor @Service public class UserService { private final UserRepository userRepository; - private final FoodRepository foodRepository; - private final FavoriteFoodRepository favoriteFoodRepository; // 회원정보 저장 @Transactional public Long saveUser(CreateUserDto createUserDto) { - - return null; + // 나이, 성별, 키, 몸무게로 기준 영양소 계산 (추후 로직 구성) + // BaseNutrition baseNutrition = BaseNutrition + return userRepository.save(User.createUser(createUserDto.getName(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getAge(), createUserDto.getGender(), null)).getId(); } // 회원정보 조회 @Transactional(readOnly = true) public ResponseUserDto getUserInfo(Long userId) { - return userRepository.findById(userId) - .map(ResponseUserDto::from) - .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); + return ResponseUserDto.from(getUserById(userId)); } // 회원정보 수정 @Transactional public void updateUserInfo(UpdateUserDto updateUserDto) { - + User user = getUserById(updateUserDto.getUserId()); + user.updateUser(updateUserDto.getName(), updateUserDto.getHeight(), updateUserDto.getWeight(), updateUserDto.getAge(), null); } // 회원 탈퇴 @Transactional public void deleteUser(Long userId) { - + User user = getUserById(userId); + userRepository.delete(user); } // 회원이 팔로우를 위해 검색한 유저 목록 조회 @Transactional(readOnly = true) - public List searchUser(String name) { - - return null; + public List searchUser(String name) { + List users = userRepository.findAllByNameContaining(name); + return users.stream() + .map(user -> ResponseResearchUserDto.of(user.getId(), user.getName())).collect(Collectors.toList()); } // 회원이 특정 회원 팔로우 @Transactional public void followUser(Long userId, Long followId) { - + User user = getUserById(userId); + User followUser = getUserById(followId); + user.followUser(followUser); } // 회원이 특정 회원 팔로우 취소 @Transactional public void unfollowUser(Long userId, Long unfollowId) { + User user = getUserById(userId); + User followUser = getUserById(unfollowId); + user.unfollowUser(followUser); + } + private User getUserById(Long userId) { + return userRepository.findById(userId) + .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); } /* 아래 메서드들은 원래 두 패키지 모두에 존재할 수 있는 혼합적인 의미를 가지고 있으며, 일단 FoodService에서 구현을 담당할 예정이다. + 현재 UserService가 음식 관련 Repository에 의존하지 않고 있기에, FoodService에서 구현하는 것이 더 적절하다고 판단했다. + // 유저의 즐겨찾기 음식 목록 조회 public void getFavoriteFoodList(Long userId) { @@ -107,10 +119,9 @@ public void getWorstFoodByWeek(Long userId) { } */ - /** + /* * 위 메서드 외 누락된 메서드가 존재할 수 있으며, UserService에는 아래와 같은 추가적인 부가 기능을 구현할 가능성이 있다. - * 1. 친구 추가 기능 (팔로우 기능 구현 중) - * 2. 친구 목록에 나를 포함하여 각 사람의 칼탄단지 섭취량 기준으로 섭취 현황을 채점(?)하여 정렬하는 랭킹 기능 - * 3. 주간 과제 기능? -> 2번과 연계 가능 + * 1. 팔로우 목록에 나를 포함하여 칼탄단지 섭취량 기준으로 건강한 섭취 현황을 분석(?)하여 점수별로 정렬하는 랭킹 기능 + * 2. 주간 과제 기능 (예: 주간에 목표한 섭취량을 달성하면 보상이 주어지는 등) */ } From 49f543f4f0b5fe7ba7cd97daa58589fed584bdd3 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 20:07:31 +0900 Subject: [PATCH 029/371] =?UTF-8?q?:goal=5Fnet:=20Fix:=20User=20=EC=9E=90?= =?UTF-8?q?=EA=B8=B0=20=EC=9E=90=EC=8B=A0=EC=9D=98=20=EC=9D=BC=EB=8C=80?= =?UTF-8?q?=EB=8B=A4=20=EA=B4=80=EA=B3=84=20=EB=A7=A4=ED=95=91=20=EC=98=A4?= =?UTF-8?q?=EB=A5=98=20=EC=88=98=EC=A0=95=20(#7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/user/domain/User.java | 11 +++++++++-- .../com/diareat/diareat/user/service/UserService.java | 10 ++++++---- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index 9807cb9..f28c005 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -9,7 +9,9 @@ import javax.persistence.*; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @@ -41,8 +43,13 @@ public class User { @OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) // 유저가 탈퇴하면 즐겨찾기 음식도 삭제 private List favoriteFoods = new ArrayList<>(); - @OneToMany(mappedBy = "user") // 유저의 팔로우 목록 - private List followings = new ArrayList<>(); + @ManyToMany // 팔로우 목록 + @JoinTable( + name = "user_follows", + joinColumns = @JoinColumn(name = "follower_id"), + inverseJoinColumns = @JoinColumn(name = "following_id") + ) + private Set followings = new HashSet<>(); // 생성 메서드 public static User createUser(String name, String keyCode, int height, int weight, int gender, int age, BaseNutrition baseNutrition) { diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index f27f809..1ebc485 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -25,9 +25,10 @@ public class UserService { // 회원정보 저장 @Transactional public Long saveUser(CreateUserDto createUserDto) { - // 나이, 성별, 키, 몸무게로 기준 영양소 계산 (추후 로직 구성) - // BaseNutrition baseNutrition = BaseNutrition - return userRepository.save(User.createUser(createUserDto.getName(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getAge(), createUserDto.getGender(), null)).getId(); + // 나이, 성별, 키, 몸무게로 기준 영양소 계산 (일단 임의의 값으로 설정했고 추후 로직 구성) + BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); + User user = User.createUser(createUserDto.getName(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getAge(), createUserDto.getGender(), baseNutrition); + return userRepository.save(user).getId(); } // 회원정보 조회 @@ -40,7 +41,8 @@ public ResponseUserDto getUserInfo(Long userId) { @Transactional public void updateUserInfo(UpdateUserDto updateUserDto) { User user = getUserById(updateUserDto.getUserId()); - user.updateUser(updateUserDto.getName(), updateUserDto.getHeight(), updateUserDto.getWeight(), updateUserDto.getAge(), null); + BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); + user.updateUser(updateUserDto.getName(), updateUserDto.getHeight(), updateUserDto.getWeight(), updateUserDto.getAge(), baseNutrition); } // 회원 탈퇴 From 6525f4cc0914fa52e0ce7963dd32b6ed167316f0 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 2 Oct 2023 20:08:38 +0900 Subject: [PATCH 030/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20Test:=20UserSe?= =?UTF-8?q?rvice=20=ED=85=8C=EC=8A=A4=ED=8A=B8=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1=20=EB=B0=8F=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C=20(#7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/UserServiceTest.java | 48 +++++++++---------- 1 file changed, 22 insertions(+), 26 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/UserServiceTest.java b/src/test/java/com/diareat/diareat/service/UserServiceTest.java index d6ab5e2..700c92b 100644 --- a/src/test/java/com/diareat/diareat/service/UserServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/UserServiceTest.java @@ -1,7 +1,8 @@ package com.diareat.diareat.service; -import com.diareat.diareat.user.domain.User; +import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.dto.CreateUserDto; +import com.diareat.diareat.user.dto.ResponseResearchUserDto; import com.diareat.diareat.user.dto.ResponseUserDto; import com.diareat.diareat.user.dto.UpdateUserDto; import com.diareat.diareat.user.repository.UserRepository; @@ -10,15 +11,15 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.transaction.annotation.Transactional; import java.util.List; -import java.util.Optional; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.*; @SpringBootTest +@Transactional class UserServiceTest { @Autowired @@ -50,13 +51,13 @@ void testSaveAndGetUserInfo() { // 회원정보 저장 및 조회 void testUpdateUserInfo() { // 회원정보 수정 // given - Long userId = 1L; - userService.saveUser(CreateUserDto.of("1", "testPassword", 180, 75, 1, 25)); + Long id = userService.saveUser(CreateUserDto.of("1", "testPassword", 180, 75, 1, 25)); + BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); // when - UpdateUserDto updateUserDto = UpdateUserDto.of(1L, "2", 185, 70, 75, null); + UpdateUserDto updateUserDto = UpdateUserDto.of(id, "2", 185, 70, 75, baseNutrition); userService.updateUserInfo(updateUserDto); - ResponseUserDto responseUserDto = userService.getUserInfo(userId); + ResponseUserDto responseUserDto = userService.getUserInfo(id); // then assertNotNull(responseUserDto); @@ -68,14 +69,13 @@ void testUpdateUserInfo() { // 회원정보 수정 @Test void testDeleteUser() { // 회원 탈퇴 // given - Long userId = 1L; - userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); + Long id = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); // when - userService.deleteUser(userId); + userService.deleteUser(id); // then - assertEquals(Optional.empty(), userRepository.findById(userId)); + assertNull(userRepository.findById(id).orElse(null)); } @Test @@ -86,7 +86,7 @@ void testSearchUserName() { // when String name = "testUser"; - List users = userService.searchUser(name); + List users = userService.searchUser(name); // then assertEquals(1, users.size()); @@ -95,31 +95,27 @@ void testSearchUserName() { @Test void testFollowUser() { // 회원이 특정 회원 팔로우 // given - Long userId = 1L; - Long followId = 2L; - userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); - userService.saveUser(CreateUserDto.of("followUser", "testPassword", 180, 75, 1, 25)); + Long id1 = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); + Long id2 = userService.saveUser(CreateUserDto.of("followUser", "testPassword", 180, 75, 1, 25)); // when - userService.followUser(userId, followId); + userService.followUser(id1, id2); // then - assertEquals(1, userRepository.findById(userId).get().getFollowings().size()); + assertEquals(1, userRepository.findById(id1).get().getFollowings().size()); } @Test void testUnfollowUser() { // 회원이 특정 회원 팔로우 취소 // given - Long userId = 1L; - Long followId = 2L; - userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); - userService.saveUser(CreateUserDto.of("followUser", "testPassword", 180, 75, 1, 25)); + Long id1 = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); + Long id2 = userService.saveUser(CreateUserDto.of("followUser", "testPassword", 180, 75, 1, 25)); // when - userService.followUser(userId, followId); - userService.unfollowUser(userId, followId); + userService.followUser(id1, id2); + userService.unfollowUser(id1, id2); // then - assertEquals(0, userRepository.findById(userId).get().getFollowings().size()); + assertEquals(0, userRepository.findById(id1).get().getFollowings().size()); } } From 7e7281eccdc31be6e8fa7850234a04db2ad6e211 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Tue, 3 Oct 2023 15:58:53 +0900 Subject: [PATCH 031/371] :construction_worker: feat: pass env to build step (#13) --- .github/workflows/diareat-Build.yml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/diareat-Build.yml b/.github/workflows/diareat-Build.yml index 656237f..be755a0 100644 --- a/.github/workflows/diareat-Build.yml +++ b/.github/workflows/diareat-Build.yml @@ -13,14 +13,21 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - name: Checkout + uses: actions/checkout@v3 + - name: Set up JDK 11 uses: actions/setup-java@v3 with: java-version: '11' distribution: 'temurin' + - name: Build with Gradle uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0 + env: + DB_ENDPOINT: ${{ secrets.DB_ENDPOINT } + DB_USERNAME: ${{ secrets.DB_USERNAME } + DB_PASSWORD: ${{ secrets.DB_PASSWORD } with: arguments: build From 88a69cb427b85189607061fc633f746ec440c8d4 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Tue, 3 Oct 2023 16:03:26 +0900 Subject: [PATCH 032/371] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20fix:=20fix=20typo?= =?UTF-8?q?=20(#13)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/diareat-Build.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/diareat-Build.yml b/.github/workflows/diareat-Build.yml index be755a0..8128bdb 100644 --- a/.github/workflows/diareat-Build.yml +++ b/.github/workflows/diareat-Build.yml @@ -25,9 +25,9 @@ jobs: - name: Build with Gradle uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0 env: - DB_ENDPOINT: ${{ secrets.DB_ENDPOINT } - DB_USERNAME: ${{ secrets.DB_USERNAME } - DB_PASSWORD: ${{ secrets.DB_PASSWORD } + DB_ENDPOINT: ${{ secrets.DB_ENDPOINT }} + DB_USERNAME: ${{ secrets.DB_USERNAME }} + DB_PASSWORD: ${{ secrets.DB_PASSWORD }} with: arguments: build From d955cd336494b7f42fa49206e157ee60ab53b7d4 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Tue, 3 Oct 2023 16:06:11 +0900 Subject: [PATCH 033/371] :construction_worker: feat: update Diareat-CICD.yml (#13) --- .github/workflows/Diareat-CICD.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/Diareat-CICD.yml b/.github/workflows/Diareat-CICD.yml index e90c875..4102a13 100644 --- a/.github/workflows/Diareat-CICD.yml +++ b/.github/workflows/Diareat-CICD.yml @@ -22,6 +22,10 @@ jobs: - name: Build with Gradle uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0 + env: + DB_ENDPOINT: ${{ secrets.DB_ENDPOINT }} + DB_USERNAME: ${{ secrets.DB_USERNAME }} + DB_PASSWORD: ${{ secrets.DB_PASSWORD }} with: arguments: build From ddcdb5eba00eff5769c5c9b452dedfd548fdcf7a Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Tue, 3 Oct 2023 16:07:48 +0900 Subject: [PATCH 034/371] :construction_worker: feat: skip test while building image (#13) --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 772a7c2..4173c9b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,7 +2,7 @@ FROM gradle:8.2.1-jdk11 AS build COPY --chown=gradle:gradle . /home/gradle/src WORKDIR /home/gradle/src -RUN gradle build --no-daemon +RUN gradle build --no-daemon -x test FROM openjdk:11-jre-slim From 1d895e94797ae47a498cf3a7d69bf4a0b297bbc1 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Tue, 3 Oct 2023 17:31:34 +0900 Subject: [PATCH 035/371] =?UTF-8?q?:see=5Fno=5Fevil:=20feat:=20gitignore?= =?UTF-8?q?=EC=97=90=20application-db.properties=20=EC=B6=94=EA=B0=80=20(#?= =?UTF-8?q?9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 ++- src/main/resources/application-db.properties | 11 ----------- 2 files changed, 2 insertions(+), 12 deletions(-) delete mode 100644 src/main/resources/application-db.properties diff --git a/.gitignore b/.gitignore index e48b6be..88dbad9 100644 --- a/.gitignore +++ b/.gitignore @@ -34,4 +34,5 @@ out/ /.nb-gradle/ ### VS Code ### -.vscode/ \ No newline at end of file +.vscode/ +application-db.properties \ No newline at end of file diff --git a/src/main/resources/application-db.properties b/src/main/resources/application-db.properties deleted file mode 100644 index 1a2cded..0000000 --- a/src/main/resources/application-db.properties +++ /dev/null @@ -1,11 +0,0 @@ -spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver -spring.jpa.hibernate.ddl-auto=create - -# Remote DB -spring.datasource.url=${DB_ENDPOINT} -spring.datasource.username=${DB_USERNAME} -spring.datasource.password=${DB_PASSWORD} - -spring.jpa.show-sql=true -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect -spring.jpa.properties.hibernate.format_sql=true From 8de56a812c3189d0ecc1061dd94fd17008b46908 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 4 Oct 2023 15:29:12 +0900 Subject: [PATCH 036/371] =?UTF-8?q?:sparkles:=20feat:=20ResponseUserDto?= =?UTF-8?q?=EC=97=90=20=EB=88=84=EB=9D=BD=EB=90=9C=20id=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/user/dto/ResponseUserDto.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java index 4f8b877..7d2e746 100644 --- a/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java @@ -9,6 +9,7 @@ @AllArgsConstructor public class ResponseUserDto { + private Long id; //누락된 id private String name; private int height; private int weight; @@ -16,11 +17,12 @@ public class ResponseUserDto { private int age; private BaseNutrition baseNutrition; - public static ResponseUserDto of(String userName, int userHeight, int userWeight, int userGender, int userAge, BaseNutrition userBaseNutrition) { - return new ResponseUserDto(userName, userHeight, userWeight, userGender, userAge, userBaseNutrition); + + public static ResponseUserDto of(Long id, String userName, int userHeight, int userWeight, int userGender, int userAge, BaseNutrition userBaseNutrition) { + return new ResponseUserDto(id, userName, userHeight, userWeight, userGender, userAge, userBaseNutrition); } public static ResponseUserDto from(User user) { - return new ResponseUserDto(user.getName(), user.getHeight(), user.getWeight(), user.getGender(), user.getAge(), user.getBaseNutrition()); + return new ResponseUserDto(user.getId(), user.getName(), user.getHeight(), user.getWeight(), user.getGender(), user.getAge(), user.getBaseNutrition()); } } From fffacf3a27715d1f5dc9ee17091cea31984e7f71 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 4 Oct 2023 20:23:00 +0900 Subject: [PATCH 037/371] =?UTF-8?q?:sparkles:=20feat:=20=EC=9D=8C=EC=8B=9D?= =?UTF-8?q?=20=EC=A0=80=EC=9E=A5=20=EB=B0=8F=20=EB=82=A0=EC=A7=9C=EB=B3=84?= =?UTF-8?q?=20=EC=9D=8C=EC=8B=9D=20=EB=A6=AC=EC=8A=A4=ED=8A=B8=20=EB=B0=98?= =?UTF-8?q?=ED=99=98=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../food/repository/FoodRepository.java | 4 +++ .../diareat/food/service/FoodService.java | 34 +++++++++++++++++-- 2 files changed, 36 insertions(+), 2 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 ee9d2b3..4c4ef98 100644 --- a/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java +++ b/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java @@ -3,5 +3,9 @@ import com.diareat.diareat.food.domain.Food; import org.springframework.data.jpa.repository.JpaRepository; +import java.time.LocalDate; +import java.util.List; + public interface FoodRepository extends JpaRepository { + List findAllByUserIdAndDate(Long userId, LocalDate date); //유저가 특정 날짜에 먹은 음식 반환 } 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 a0702b2..29fa112 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -1,10 +1,24 @@ package com.diareat.diareat.food.service; +import com.diareat.diareat.food.domain.Food; +import com.diareat.diareat.food.dto.CreateFoodDto; +import com.diareat.diareat.food.dto.ResponseFoodDto; import com.diareat.diareat.food.repository.FavoriteFoodRepository; import com.diareat.diareat.food.repository.FoodRepository; +import com.diareat.diareat.user.domain.User; +import com.diareat.diareat.user.dto.ResponseResearchUserDto; +import com.diareat.diareat.user.repository.UserRepository; +import com.diareat.diareat.util.api.ResponseCode; +import com.diareat.diareat.util.exception.FoodException; +import com.diareat.diareat.util.exception.UserException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; +import javax.transaction.Transactional; +import java.time.LocalDate; +import java.util.List; +import java.util.stream.Collectors; + @RequiredArgsConstructor @Service public class FoodService { @@ -12,11 +26,26 @@ public class FoodService { private final FoodRepository foodRepository; // 유저:음식은 1:다 private final FavoriteFoodRepository favoriteFoodRepository; // 유저:즐찾음식은 1:다 + private final UserRepository userRepository; + // 촬영 후, 음식 정보 저장 - public Long saveFood() { - return null; + @Transactional + public Long saveFood(CreateFoodDto createFoodDto) { + User user = userRepository.findById(createFoodDto.getUserId()) + .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); + Food food = Food.createFood(createFoodDto.getName(), user, createFoodDto.getBaseNutrition()); + return foodRepository.save(food).getId(); } + // 회원이 특정 날짜에 먹은 음식 반환 + @Transactional + public List getFoodListByDate(Long userId, LocalDate date){ + List foodList = foodRepository.findAllByUserIdAndDate(userId, date); + return foodList.stream() + .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getDate(), food.getTime(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); + } + + // 음식 정보 수정 public void updateFood() { @@ -42,6 +71,7 @@ public void deleteFavoriteFood() { } + /** * 메서드 구현 유의사항 * 1. 메서드명은 동사로 시작 From 061137a938cc073eb0b9a9f0ab9e8cb42b5f5a87 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 4 Oct 2023 20:23:34 +0900 Subject: [PATCH 038/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20feat:=20?= =?UTF-8?q?=EC=9D=8C=EC=8B=9D=20=EC=A0=80=EC=9E=A5=20=EB=B0=8F=20=EB=82=A0?= =?UTF-8?q?=EC=A7=9C=EB=B3=84=20=EC=9D=8C=EC=8B=9D=20=EB=B0=98=ED=99=98=20?= =?UTF-8?q?TestCode=20=EC=9E=91=EC=84=B1=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/FoodServiceTest.java | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 src/test/java/com/diareat/diareat/service/FoodServiceTest.java diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java new file mode 100644 index 0000000..2dc8ec6 --- /dev/null +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -0,0 +1,75 @@ +package com.diareat.diareat.service; + +import com.diareat.diareat.food.domain.Food; +import com.diareat.diareat.food.dto.CreateFoodDto; +import com.diareat.diareat.food.dto.ResponseFoodDto; +import com.diareat.diareat.food.repository.FavoriteFoodRepository; +import com.diareat.diareat.food.repository.FoodRepository; +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.CreateUserDto; +import com.diareat.diareat.user.dto.ResponseResearchUserDto; +import com.diareat.diareat.user.dto.ResponseUserDto; +import com.diareat.diareat.user.dto.UpdateUserDto; +import com.diareat.diareat.user.repository.UserRepository; +import com.diareat.diareat.user.service.UserService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.logging.log4j2.Log4J2LoggingSystem; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.transaction.annotation.Transactional; + +import javax.swing.text.html.Option; +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + + +@SpringBootTest +@Transactional +class FoodServiceTest { + + @Autowired + FoodService foodService; + + @Autowired + UserService userService; + + @Autowired + FoodRepository foodRepository; + + @Autowired + FavoriteFoodRepository favoriteFoodRepository; + + @Autowired + UserRepository userRepository; + + @BeforeEach + public void setUp() { + userRepository.deleteAll(); + foodRepository.deleteAll(); + favoriteFoodRepository.deleteAll(); + } + + @Test + void testSaveAndGetFood() { // 음식 정보 저장 및 업데이트 + // given + BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 1,180, 80,18)); + + //when + Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood",testBaseNutrition)); + Food testFood = foodRepository.getReferenceById(foodId); + + List responseFoodDto = foodService.getFoodListByDate(userId, testFood.getDate()); + + assertNotNull(responseFoodDto); + assertEquals("testFood",responseFoodDto.get(0).getName()); + } + + +} From 564a7e95c7a66eef119c4ee3a813f8dfac37db9d Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 4 Oct 2023 20:49:43 +0900 Subject: [PATCH 039/371] =?UTF-8?q?:sparkles:=20feat:=20=EC=9D=8C=EC=8B=9D?= =?UTF-8?q?=20Update=20=EA=B5=AC=ED=98=84=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/food/service/FoodService.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 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 29fa112..88562e0 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -3,6 +3,7 @@ import com.diareat.diareat.food.domain.Food; import com.diareat.diareat.food.dto.CreateFoodDto; import com.diareat.diareat.food.dto.ResponseFoodDto; +import com.diareat.diareat.food.dto.UpdateFoodDto; import com.diareat.diareat.food.repository.FavoriteFoodRepository; import com.diareat.diareat.food.repository.FoodRepository; import com.diareat.diareat.user.domain.User; @@ -47,8 +48,11 @@ public List getFoodListByDate(Long userId, LocalDate date){ // 음식 정보 수정 - public void updateFood() { - + @Transactional + public void updateFood(Long userId, UpdateFoodDto updateFoodDto) { + Food food = foodRepository.findById(updateFoodDto.getFoodId()) + .orElseThrow(() -> new FoodException(ResponseCode.FOOD_NOT_FOUND)); + food.updateFood(updateFoodDto.getName(), updateFoodDto.getBaseNutrition()); } // 음식 삭제 From a6117b6f2352dd2966b0a21a13e0b6217c36c533 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 4 Oct 2023 20:50:34 +0900 Subject: [PATCH 040/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20feat:=20update?= =?UTF-8?q?Food=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 2 +- .../diareat/service/FoodServiceTest.java | 23 ++++++++++++++++++- 2 files changed, 23 insertions(+), 2 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 88562e0..feb9444 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -49,7 +49,7 @@ public List getFoodListByDate(Long userId, LocalDate date){ // 음식 정보 수정 @Transactional - public void updateFood(Long userId, UpdateFoodDto updateFoodDto) { + public void updateFood(UpdateFoodDto updateFoodDto) { Food food = foodRepository.findById(updateFoodDto.getFoodId()) .orElseThrow(() -> new FoodException(ResponseCode.FOOD_NOT_FOUND)); food.updateFood(updateFoodDto.getName(), updateFoodDto.getBaseNutrition()); diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 2dc8ec6..381dee2 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -3,6 +3,7 @@ import com.diareat.diareat.food.domain.Food; import com.diareat.diareat.food.dto.CreateFoodDto; import com.diareat.diareat.food.dto.ResponseFoodDto; +import com.diareat.diareat.food.dto.UpdateFoodDto; import com.diareat.diareat.food.repository.FavoriteFoodRepository; import com.diareat.diareat.food.repository.FoodRepository; import com.diareat.diareat.food.service.FoodService; @@ -56,7 +57,7 @@ public void setUp() { } @Test - void testSaveAndGetFood() { // 음식 정보 저장 및 업데이트 + void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리스트 불러오기 // given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 1,180, 80,18)); @@ -71,5 +72,25 @@ void testSaveAndGetFood() { // 음식 정보 저장 및 업데이트 assertEquals("testFood",responseFoodDto.get(0).getName()); } + @Test + void testUpdateFood() { + //given + BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "tessPassword", 1, 180, 80, 18)); + Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); + + //when + BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); + foodService.updateFood(UpdateFoodDto.of(foodId, "testChangedFood", testChangedBaseNutrition)); + + Food changedFood = foodRepository.getReferenceById(foodId); + + assertNotNull(changedFood); + assertEquals("testChangedFood", changedFood.getName()); + assertEquals(2,changedFood.getBaseNutrition().getKcal()); + assertEquals(3,changedFood.getBaseNutrition().getCarbohydrate()); + assertEquals(4,changedFood.getBaseNutrition().getProtein()); + assertEquals(5,changedFood.getBaseNutrition().getFat()); + } } From bce3547309d4f43729d98d6df25bed800b3a12b4 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 4 Oct 2023 21:01:41 +0900 Subject: [PATCH 041/371] =?UTF-8?q?:sparkles:=20feat:=20deleteFood=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/service/FoodService.java | 5 +++-- 1 file changed, 3 insertions(+), 2 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 feb9444..0d6290d 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -56,8 +56,9 @@ public void updateFood(UpdateFoodDto updateFoodDto) { } // 음식 삭제 - public void deleteFood() { - + @Transactional + public void deleteFood(Long foodId) { + foodRepository.deleteById(foodId); } // 즐겨찾기에 음식 저장 From 4bdd15a6a5d19d9d887f82131ed62156b6846591 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 4 Oct 2023 21:02:05 +0900 Subject: [PATCH 042/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20feat:=20delete?= =?UTF-8?q?Food()=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/service/FoodServiceTest.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 381dee2..8231670 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -93,4 +93,16 @@ void testUpdateFood() { assertEquals(5,changedFood.getBaseNutrition().getFat()); } + @Test + void testDeleteFood() { + //given + BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "tessPassword", 1, 180, 80, 18)); + Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); + + //when + foodService.deleteFood(foodId); + + assertNull(foodRepository.findById(foodId).orElse(null)); + } } From e256d43abde1ef53dc04579cd113c14c1b5cf14f Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 4 Oct 2023 23:17:37 +0900 Subject: [PATCH 043/371] =?UTF-8?q?:recycle:=20refactor:=20ResponseFavorit?= =?UTF-8?q?eFoodDto=EC=97=90=EC=84=9C=20baseNutrition=20=EC=9E=90=EB=A3=8C?= =?UTF-8?q?=ED=98=95=20=EC=88=98=EC=A0=95=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/dto/ResponseFavoriteFoodDto.java | 7 ++++--- 1 file changed, 4 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 78678bb..3d33ca4 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java @@ -1,6 +1,7 @@ package com.diareat.diareat.food.dto; import com.diareat.diareat.food.domain.FavoriteFood; +import com.diareat.diareat.user.domain.BaseNutrition; import lombok.AllArgsConstructor; import lombok.Getter; @@ -10,10 +11,10 @@ public class ResponseFavoriteFoodDto { private Long favoriteFoodId; private String name; - private String baseNutrition; + private BaseNutrition baseNutrition; private int count; - public static ResponseFavoriteFoodDto of(Long favoriteFoodId, String name, String baseNutrition, int count) { + public static ResponseFavoriteFoodDto of(Long favoriteFoodId, String name, BaseNutrition baseNutrition, int count) { return new ResponseFavoriteFoodDto(favoriteFoodId, name, baseNutrition, count); } @@ -21,7 +22,7 @@ public static ResponseFavoriteFoodDto from(FavoriteFood favoriteFood) { return new ResponseFavoriteFoodDto( favoriteFood.getId(), favoriteFood.getName(), - favoriteFood.getBaseNutrition().toString(), + favoriteFood.getBaseNutrition(), favoriteFood.getCount() ); } From 89eaf285e90bc3daa1ebb5ef8f005bbb3ffe346c Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 4 Oct 2023 23:18:55 +0900 Subject: [PATCH 044/371] =?UTF-8?q?:sparkles:=20feat:=20=EC=A6=90=EA=B2=A8?= =?UTF-8?q?=EC=B0=BE=EA=B8=B0=20=EC=9D=8C=EC=8B=9D=20=EC=A0=80=EC=9E=A5=20?= =?UTF-8?q?=EB=B0=8F=20=EB=A6=AC=EC=8A=A4=ED=8A=B8=20=EB=B0=98=ED=99=98=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../repository/FavoriteFoodRepository.java | 3 +++ .../diareat/food/service/FoodService.java | 22 ++++++++++++++----- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java b/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java index d90278b..549a7cb 100644 --- a/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java +++ b/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java @@ -3,5 +3,8 @@ import com.diareat.diareat.food.domain.FavoriteFood; import org.springframework.data.jpa.repository.JpaRepository; +import java.util.List; + public interface FavoriteFoodRepository extends JpaRepository { + List findAllByUserId(Long userId); } 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 0d6290d..e0dc36e 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -1,9 +1,8 @@ package com.diareat.diareat.food.service; +import com.diareat.diareat.food.domain.FavoriteFood; import com.diareat.diareat.food.domain.Food; -import com.diareat.diareat.food.dto.CreateFoodDto; -import com.diareat.diareat.food.dto.ResponseFoodDto; -import com.diareat.diareat.food.dto.UpdateFoodDto; +import com.diareat.diareat.food.dto.*; import com.diareat.diareat.food.repository.FavoriteFoodRepository; import com.diareat.diareat.food.repository.FoodRepository; import com.diareat.diareat.user.domain.User; @@ -62,8 +61,21 @@ public void deleteFood(Long foodId) { } // 즐겨찾기에 음식 저장 - public Long saveFavoriteFood() { - return null; + public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { + User user = userRepository.findById(createFavoriteFoodDto.getUserId()) + .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); + + FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood(createFavoriteFoodDto.getName(), user, createFavoriteFoodDto.getBaseNutrition()); + return favoriteFoodRepository.save(favoriteFood).getId(); + } + + //즐겨찾기 음식 리스트 반환 + @Transactional + public List getFavoriteFoodByUserId(Long userId){ + List foodList = favoriteFoodRepository.findAllByUserId(userId); + return foodList.stream() + .map(favoriteFood -> ResponseFavoriteFoodDto.of(favoriteFood.getId(), favoriteFood.getName(), + favoriteFood.getBaseNutrition(), favoriteFood.getCount())).collect(Collectors.toList()); } // 즐겨찾기 음식 수정 From 52e2aa0b16c4d2a72d2c07cdc6b68630c30bbe30 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 4 Oct 2023 23:19:18 +0900 Subject: [PATCH 045/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20=EC=A6=90?= =?UTF-8?q?=EA=B2=A8=EC=B0=BE=EA=B8=B0=20=EC=9D=8C=EC=8B=9D=20=EC=A0=80?= =?UTF-8?q?=EC=9E=A5=20=EB=B0=8F=20=EB=A6=AC=EC=8A=A4=ED=8A=B8=20=EB=B0=98?= =?UTF-8?q?=ED=99=98=20=ED=85=8C=EC=8A=A4=ED=8A=B8=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 1 + .../diareat/service/FoodServiceTest.java | 27 ++++++++++++++----- 2 files changed, 22 insertions(+), 6 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 e0dc36e..6740136 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -61,6 +61,7 @@ public void deleteFood(Long foodId) { } // 즐겨찾기에 음식 저장 + @Transactional public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { User user = userRepository.findById(createFavoriteFoodDto.getUserId()) .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 8231670..48a5850 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -1,9 +1,8 @@ package com.diareat.diareat.service; +import com.diareat.diareat.food.domain.FavoriteFood; import com.diareat.diareat.food.domain.Food; -import com.diareat.diareat.food.dto.CreateFoodDto; -import com.diareat.diareat.food.dto.ResponseFoodDto; -import com.diareat.diareat.food.dto.UpdateFoodDto; +import com.diareat.diareat.food.dto.*; import com.diareat.diareat.food.repository.FavoriteFoodRepository; import com.diareat.diareat.food.repository.FoodRepository; import com.diareat.diareat.food.service.FoodService; @@ -66,10 +65,10 @@ void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리 Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood",testBaseNutrition)); Food testFood = foodRepository.getReferenceById(foodId); - List responseFoodDto = foodService.getFoodListByDate(userId, testFood.getDate()); + List responseFoodDtoList = foodService.getFoodListByDate(userId, testFood.getDate()); - assertNotNull(responseFoodDto); - assertEquals("testFood",responseFoodDto.get(0).getName()); + assertNotNull(responseFoodDtoList); + assertEquals("testFood",responseFoodDtoList.get(0).getName()); } @Test @@ -105,4 +104,20 @@ void testDeleteFood() { assertNull(foodRepository.findById(foodId).orElse(null)); } + + @Test + void testSaveAndGetFavoriteFood() { + //given + BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "tessPassword", 1, 180, 80, 18)); + Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); + + //when + Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); + + List responseFavoriteFoodDtoList = foodService.getFavoriteFoodByUserId(userId); + + assertNotNull(responseFavoriteFoodDtoList); + assertEquals("testFood",responseFavoriteFoodDtoList.get(0).getName()); + } } From 8d0abe6b1fa8db4b75e01ac42cad29f61cbe288e Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 4 Oct 2023 23:25:31 +0900 Subject: [PATCH 046/371] =?UTF-8?q?:sparkles:=20feat:=20update,=20deleteFa?= =?UTF-8?q?voriteFood()=20=EA=B5=AC=ED=98=84=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/service/FoodService.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 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 6740136..027600c 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -80,13 +80,17 @@ public List getFavoriteFoodByUserId(Long userId){ } // 즐겨찾기 음식 수정 - public void updateFavoriteFood() { - + @Transactional + public void updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto) { + FavoriteFood food = favoriteFoodRepository.findById(updateFavoriteFoodDto.getFavoriteFoodId()) + .orElseThrow(() -> new FoodException(ResponseCode.FOOD_NOT_FOUND)); + food.updateFavoriteFood(updateFavoriteFoodDto.getName(), updateFavoriteFoodDto.getBaseNutrition()); } // 즐겨찾기 해제 - public void deleteFavoriteFood() { - + @Transactional + public void deleteFavoriteFood(Long favoriteFoodId) { + favoriteFoodRepository.deleteById(favoriteFoodId); } From 60e1347236845bb17c121e3cfd19ba328f5463fd Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 4 Oct 2023 23:25:55 +0900 Subject: [PATCH 047/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20update,=20dele?= =?UTF-8?q?teFavoriteFood()=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94?= =?UTF-8?q?=EB=93=9C=20=EC=9E=91=EC=84=B1=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/FoodServiceTest.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 48a5850..624cc46 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -120,4 +120,41 @@ void testSaveAndGetFavoriteFood() { assertNotNull(responseFavoriteFoodDtoList); assertEquals("testFood",responseFavoriteFoodDtoList.get(0).getName()); } + + @Test + void testUpdateFavoriteFood() { + //given + BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "tessPassword", 1, 180, 80, 18)); + Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); + Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); + + + //when + BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); + foodService.updateFavoriteFood(UpdateFavoriteFoodDto.of(favoriteFoodId, "testChangedFood", testChangedBaseNutrition)); + + FavoriteFood changedFood = favoriteFoodRepository.getReferenceById(favoriteFoodId); + + assertNotNull(changedFood); + assertEquals("testChangedFood", changedFood.getName()); + assertEquals(2,changedFood.getBaseNutrition().getKcal()); + assertEquals(3,changedFood.getBaseNutrition().getCarbohydrate()); + assertEquals(4,changedFood.getBaseNutrition().getProtein()); + assertEquals(5,changedFood.getBaseNutrition().getFat()); + } + + @Test + void testDeleteFavoriteFood() { + //given + BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "tessPassword", 1, 180, 80, 18)); + Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); + Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); + + //when + foodService.deleteFavoriteFood(favoriteFoodId); + + assertNull(favoriteFoodRepository.findById(favoriteFoodId).orElse(null)); + } } From e6b33d81ea644e12d71bcd72f06a509e159d1b7d Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 4 Oct 2023 23:28:16 +0900 Subject: [PATCH 048/371] :recycle: refactor: rename getFavoriteFoodByUserId (#9) to getFavoriteFoodList --- src/main/java/com/diareat/diareat/food/service/FoodService.java | 2 +- 1 file changed, 1 insertion(+), 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 027600c..9b058b6 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -72,7 +72,7 @@ public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { //즐겨찾기 음식 리스트 반환 @Transactional - public List getFavoriteFoodByUserId(Long userId){ + public List getFavoriteFoodList(Long userId){ List foodList = favoriteFoodRepository.findAllByUserId(userId); return foodList.stream() .map(favoriteFood -> ResponseFavoriteFoodDto.of(favoriteFood.getId(), favoriteFood.getName(), From 75ce22b05541acfcaf7e04162ecc881ccf3c2451 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 5 Oct 2023 00:00:45 +0900 Subject: [PATCH 049/371] =?UTF-8?q?:sparkles:=20feat:=20=EC=9E=84=EC=8B=9C?= =?UTF-8?q?=20=EB=82=A0=EC=A7=9C=EB=B3=84=20=EC=98=81=EC=96=91=EC=86=8C=20?= =?UTF-8?q?=ED=95=A9=20dto=20=EA=B5=AC=ED=98=84=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dto/ResponseNutritionSumByDateDto.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java new file mode 100644 index 0000000..0229a24 --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java @@ -0,0 +1,22 @@ +package com.diareat.diareat.food.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class ResponseNutritionSumByDateDto { + int totalKcal; + int totalCarbohydrate; + int totalProtein; + int totalFat; + + double ratioKcal; + double ratioCarbohydrate; + double ratioProtein; + double ratioFat; + + public static ResponseNutritionSumByDateDto of (int totalKcal, int totalCarbohydrate, int totalProtein, int totalFat, double ratioKcal, double ratioCarbohydrate, double ratioProtein, double ratioFat){ + return new ResponseNutritionSumByDateDto(totalFat, totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); + } +} From db38b0398e541d84d9a71584ce0c71de903817fc Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 5 Oct 2023 00:01:11 +0900 Subject: [PATCH 050/371] =?UTF-8?q?:sparkles:=20=EB=82=A0=EC=A7=9C?= =?UTF-8?q?=EB=B3=84=20=EB=A8=B9=EC=9D=80=20=EC=9D=8C=EC=8B=9D=EB=93=A4?= =?UTF-8?q?=EC=9D=98=20=EC=98=81=EC=96=91=EC=84=B1=EB=B6=84=EB=B3=84=20?= =?UTF-8?q?=EC=B4=9D=ED=95=A9=20=EC=A1=B0=ED=9A=8C=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) 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 9b058b6..ee5a110 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -5,6 +5,7 @@ import com.diareat.diareat.food.dto.*; import com.diareat.diareat.food.repository.FavoriteFoodRepository; import com.diareat.diareat.food.repository.FoodRepository; +import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; import com.diareat.diareat.user.dto.ResponseResearchUserDto; import com.diareat.diareat.user.repository.UserRepository; @@ -17,6 +18,7 @@ import javax.transaction.Transactional; import java.time.LocalDate; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; @RequiredArgsConstructor @@ -93,6 +95,57 @@ public void deleteFavoriteFood(Long favoriteFoodId) { favoriteFoodRepository.deleteById(favoriteFoodId); } + @Transactional + // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) + public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { + List foodList = foodRepository.findAllByUserIdAndDate(userId, date); + User targetUser = userRepository.findById(userId) + .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); + int totalKcal = 0; + int totalCarbohydrate = 0; + int totalProtein = 0; + int totalFat = 0; + + for (Food food : foodList) { + BaseNutrition targetFoodNutrition = food.getBaseNutrition(); + totalKcal += targetFoodNutrition.getKcal(); + totalCarbohydrate += targetFoodNutrition.getCarbohydrate(); + totalProtein += targetFoodNutrition.getProtein(); + totalFat += targetFoodNutrition.getFat(); + } + + double ratioKcal = Math.round((totalKcal*1.0)/(targetUser.getBaseNutrition().getKcal()*1.0))*10.0; + double ratioCarbohydrate = Math.round((totalCarbohydrate*1.0)/(targetUser.getBaseNutrition().getCarbohydrate()*1.0))*10.0; + double ratioProtein = Math.round((totalProtein*1.0)/(targetUser.getBaseNutrition().getProtein()*1.0))*10.0; + double ratioFat = Math.round((totalFat*1.0)/(targetUser.getBaseNutrition().getFat()*1.0))*10.0; + + return ResponseNutritionSumByDateDto.of(totalKcal,totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); + } + + @Transactional + // 유저의 최근 7일간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) + public void getNutritionSumByWeek(Long userId) { + + } + + @Transactional + // 유저의 최근 1개월간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) + public void getNutritionSumByMonth(Long userId) { + + } + + @Transactional + // 유저의 최근 7일간의 Best 3 음식 조회 (dto 구체적 협의 필요) + public void getBestFoodByWeek(Long userId) { + + } + + @Transactional + // 유저의 최근 7일간의 Worst 3 음식 조회 (dto 구체적 협의 필요) + public void getWorstFoodByWeek(Long userId) { + + } + /** * 메서드 구현 유의사항 From 81c437aabca331e39206afea7bfbc654b4f6599f Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 5 Oct 2023 00:12:25 +0900 Subject: [PATCH 051/371] :pencil2: fix: totalFat -> totalKcal (#9) found on unit test --- .../diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java index 0229a24..5eb8e4c 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java @@ -17,6 +17,6 @@ public class ResponseNutritionSumByDateDto { double ratioFat; public static ResponseNutritionSumByDateDto of (int totalKcal, int totalCarbohydrate, int totalProtein, int totalFat, double ratioKcal, double ratioCarbohydrate, double ratioProtein, double ratioFat){ - return new ResponseNutritionSumByDateDto(totalFat, totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); + return new ResponseNutritionSumByDateDto(totalKcal, totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); } } From bd5c2b9998d22a24ab0fa9f5fa1ed155318399a8 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 5 Oct 2023 00:15:14 +0900 Subject: [PATCH 052/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20feat:=20?= =?UTF-8?q?=EB=82=A0=EC=A7=9C=EB=B3=84=20=EC=98=81=EC=96=91=EC=86=8C=20?= =?UTF-8?q?=ED=95=A9=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/FoodServiceTest.java | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 624cc46..4121d4a 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -115,7 +115,7 @@ void testSaveAndGetFavoriteFood() { //when Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); - List responseFavoriteFoodDtoList = foodService.getFavoriteFoodByUserId(userId); + List responseFavoriteFoodDtoList = foodService.getFavoriteFoodList(userId); assertNotNull(responseFavoriteFoodDtoList); assertEquals("testFood",responseFavoriteFoodDtoList.get(0).getName()); @@ -157,4 +157,28 @@ void testDeleteFavoriteFood() { assertNull(favoriteFoodRepository.findById(favoriteFoodId).orElse(null)); } + + @Test + void testNutritionSumByDate(){ + //given + BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(100,150,200,250); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword",1, 180, 80, 18)); + Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood", testFoodNutrition)); + Food food = foodRepository.getReferenceById(foodId); + + //when + ResponseNutritionSumByDateDto responseNutritionSumByDateDto = foodService.getNutritionSumByDate(userId,food.getDate()); + + assertNotNull(responseNutritionSumByDateDto); + assertEquals(100, responseNutritionSumByDateDto.getTotalKcal()); + assertEquals(150, responseNutritionSumByDateDto.getTotalCarbohydrate()); + assertEquals(200, responseNutritionSumByDateDto.getTotalProtein()); + assertEquals(250, responseNutritionSumByDateDto.getTotalFat()); + + assertEquals(Math.round((100*1.0)/(2000*1.0))*10.0, responseNutritionSumByDateDto.getRatioKcal()); + assertEquals(Math.round((150*1.0)/(300*1.0))*10.0, responseNutritionSumByDateDto.getRatioCarbohydrate()); + assertEquals(Math.round((200*1.0)/(80*1.0))*10.0, responseNutritionSumByDateDto.getRatioProtein()); + assertEquals(Math.round((250*1.0)/(80*1.0))*10.0, responseNutritionSumByDateDto.getRatioFat()); + + } } From 2d484559dce1fc561c2293e59a2351ddfbcdba35 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 5 Oct 2023 00:50:47 +0900 Subject: [PATCH 053/371] =?UTF-8?q?:green=5Fheart:=20fix:=20application-db?= =?UTF-8?q?.properties=20=EB=B3=B5=EA=B5=AC=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 +-- src/main/resources/application-db.properties | 11 +++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) create mode 100644 src/main/resources/application-db.properties diff --git a/.gitignore b/.gitignore index 88dbad9..e48b6be 100644 --- a/.gitignore +++ b/.gitignore @@ -34,5 +34,4 @@ out/ /.nb-gradle/ ### VS Code ### -.vscode/ -application-db.properties \ No newline at end of file +.vscode/ \ No newline at end of file diff --git a/src/main/resources/application-db.properties b/src/main/resources/application-db.properties new file mode 100644 index 0000000..ee08c3d --- /dev/null +++ b/src/main/resources/application-db.properties @@ -0,0 +1,11 @@ +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +spring.jpa.hibernate.ddl-auto=create + +# Remote DB +spring.datasource.url=${DB_ENDPOINT} +spring.datasource.username=${DB_USERNAME} +spring.datasource.password=${DB_PASSWORD} + +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +spring.jpa.properties.hibernate.format_sql=true \ No newline at end of file From b9c60acccdb249efc7a8801365cb0e15b7074a1d Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 5 Oct 2023 10:31:54 +0900 Subject: [PATCH 054/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20fix:=20UserSer?= =?UTF-8?q?viceTest=20=EB=B2=84=EA=B7=B8=20=EC=88=98=EC=A0=95=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/com/diareat/diareat/service/UserServiceTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/UserServiceTest.java b/src/test/java/com/diareat/diareat/service/UserServiceTest.java index 700c92b..6f5ba89 100644 --- a/src/test/java/com/diareat/diareat/service/UserServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/UserServiceTest.java @@ -36,10 +36,9 @@ public void setUp() { @Test void testSaveAndGetUserInfo() { // 회원정보 저장 및 조회 // given - Long userId = 1L; // when - userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); ResponseUserDto responseUserDto = userService.getUserInfo(userId); // 검증: 올바른 결과를 반환하는지 확인 From 6646330a31a90babbd0bf46104401a7944bc73ba Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 5 Oct 2023 10:47:20 +0900 Subject: [PATCH 055/371] =?UTF-8?q?:recycle:=20refactor:=20ResponseUserDto?= =?UTF-8?q?=EC=97=90=20id=20=EC=86=8D=EC=84=B1=20=EC=A0=9C=EA=B1=B0=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/user/dto/ResponseUserDto.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java index 7d2e746..ecdb851 100644 --- a/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java @@ -9,7 +9,6 @@ @AllArgsConstructor public class ResponseUserDto { - private Long id; //누락된 id private String name; private int height; private int weight; @@ -18,11 +17,11 @@ public class ResponseUserDto { private BaseNutrition baseNutrition; - public static ResponseUserDto of(Long id, String userName, int userHeight, int userWeight, int userGender, int userAge, BaseNutrition userBaseNutrition) { - return new ResponseUserDto(id, userName, userHeight, userWeight, userGender, userAge, userBaseNutrition); + public static ResponseUserDto of(String userName, int userHeight, int userWeight, int userGender, int userAge, BaseNutrition userBaseNutrition) { + return new ResponseUserDto(userName, userHeight, userWeight, userGender, userAge, userBaseNutrition); } public static ResponseUserDto from(User user) { - return new ResponseUserDto(user.getId(), user.getName(), user.getHeight(), user.getWeight(), user.getGender(), user.getAge(), user.getBaseNutrition()); + return new ResponseUserDto(user.getName(), user.getHeight(), user.getWeight(), user.getGender(), user.getAge(), user.getBaseNutrition()); } } From e48cf9683ef68de9d7ccb02dbf79343ffafd36d4 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 5 Oct 2023 18:39:00 +0900 Subject: [PATCH 056/371] =?UTF-8?q?:recycle:=20refactor:=20Transactional?= =?UTF-8?q?=20=EC=88=98=EC=A0=95=20=EB=B0=8F=20=EC=A4=91=EB=B3=B5=EB=90=9C?= =?UTF-8?q?=20=EB=A9=94=EC=84=9C=EB=93=9C=20=ED=95=A8=EC=88=98=ED=99=94=20?= =?UTF-8?q?(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 41 +++++++++++-------- .../diareat/service/FoodServiceTest.java | 8 ---- 2 files changed, 25 insertions(+), 24 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 ee5a110..f2db24e 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -7,18 +7,16 @@ import com.diareat.diareat.food.repository.FoodRepository; import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; -import com.diareat.diareat.user.dto.ResponseResearchUserDto; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.util.api.ResponseCode; import com.diareat.diareat.util.exception.FoodException; import com.diareat.diareat.util.exception.UserException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; -import javax.transaction.Transactional; import java.time.LocalDate; import java.util.List; -import java.util.Optional; import java.util.stream.Collectors; @RequiredArgsConstructor @@ -33,14 +31,13 @@ public class FoodService { // 촬영 후, 음식 정보 저장 @Transactional public Long saveFood(CreateFoodDto createFoodDto) { - User user = userRepository.findById(createFoodDto.getUserId()) - .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); + User user = getUserById(createFoodDto.getUserId()); Food food = Food.createFood(createFoodDto.getName(), user, createFoodDto.getBaseNutrition()); return foodRepository.save(food).getId(); } // 회원이 특정 날짜에 먹은 음식 반환 - @Transactional + @Transactional(readOnly = true) public List getFoodListByDate(Long userId, LocalDate date){ List foodList = foodRepository.findAllByUserIdAndDate(userId, date); return foodList.stream() @@ -51,8 +48,7 @@ public List getFoodListByDate(Long userId, LocalDate date){ // 음식 정보 수정 @Transactional public void updateFood(UpdateFoodDto updateFoodDto) { - Food food = foodRepository.findById(updateFoodDto.getFoodId()) - .orElseThrow(() -> new FoodException(ResponseCode.FOOD_NOT_FOUND)); + Food food = getFoodById(updateFoodDto.getFoodId()); food.updateFood(updateFoodDto.getName(), updateFoodDto.getBaseNutrition()); } @@ -65,15 +61,15 @@ public void deleteFood(Long foodId) { // 즐겨찾기에 음식 저장 @Transactional public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { - User user = userRepository.findById(createFavoriteFoodDto.getUserId()) - .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); + + User user = getUserById(createFavoriteFoodDto.getUserId()); FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood(createFavoriteFoodDto.getName(), user, createFavoriteFoodDto.getBaseNutrition()); return favoriteFoodRepository.save(favoriteFood).getId(); } //즐겨찾기 음식 리스트 반환 - @Transactional + @Transactional(readOnly = true) public List getFavoriteFoodList(Long userId){ List foodList = favoriteFoodRepository.findAllByUserId(userId); return foodList.stream() @@ -84,8 +80,7 @@ public List getFavoriteFoodList(Long userId){ // 즐겨찾기 음식 수정 @Transactional public void updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto) { - FavoriteFood food = favoriteFoodRepository.findById(updateFavoriteFoodDto.getFavoriteFoodId()) - .orElseThrow(() -> new FoodException(ResponseCode.FOOD_NOT_FOUND)); + FavoriteFood food = getFavoriteFoodById(updateFavoriteFoodDto.getFavoriteFoodId()); food.updateFavoriteFood(updateFavoriteFoodDto.getName(), updateFavoriteFoodDto.getBaseNutrition()); } @@ -95,12 +90,11 @@ public void deleteFavoriteFood(Long favoriteFoodId) { favoriteFoodRepository.deleteById(favoriteFoodId); } - @Transactional + @Transactional(readOnly = true) // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { List foodList = foodRepository.findAllByUserIdAndDate(userId, date); - User targetUser = userRepository.findById(userId) - .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); + User targetUser = getUserById(userId); int totalKcal = 0; int totalCarbohydrate = 0; int totalProtein = 0; @@ -146,6 +140,21 @@ public void getWorstFoodByWeek(Long userId) { } + private User getUserById(Long userId){ + return userRepository.findById(userId) + .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); + } + + private Food getFoodById(Long foodId){ + return foodRepository.findById(foodId) + .orElseThrow(() -> new FoodException(ResponseCode.FOOD_NOT_FOUND)); + } + + private FavoriteFood getFavoriteFoodById(Long foodId){ + return favoriteFoodRepository.findById(foodId) + .orElseThrow(() -> new FoodException(ResponseCode.FOOD_NOT_FOUND)); + } + /** * 메서드 구현 유의사항 diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 4121d4a..b633575 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -7,24 +7,16 @@ import com.diareat.diareat.food.repository.FoodRepository; 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.CreateUserDto; -import com.diareat.diareat.user.dto.ResponseResearchUserDto; -import com.diareat.diareat.user.dto.ResponseUserDto; -import com.diareat.diareat.user.dto.UpdateUserDto; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.user.service.UserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.logging.log4j2.Log4J2LoggingSystem; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; -import javax.swing.text.html.Option; -import java.time.LocalDate; import java.util.List; -import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; From 5e6a0591d5a16267d4fa85584a1c55acda39eb0d Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 5 Oct 2023 22:07:39 +0900 Subject: [PATCH 057/371] =?UTF-8?q?:sparkles:=20feat:=207=EC=9D=BC,=201?= =?UTF-8?q?=EA=B0=9C=EC=9B=94=20=EA=B0=84=20=EC=98=81=EC=96=91=EC=84=B1?= =?UTF-8?q?=EB=B6=84=20=EC=B4=9D=ED=95=A9=20=EC=A1=B0=ED=9A=8C=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../food/repository/FoodRepository.java | 1 + .../diareat/food/service/FoodService.java | 64 +++++++++++-------- 2 files changed, 39 insertions(+), 26 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 4c4ef98..5cd6d90 100644 --- a/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java +++ b/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java @@ -8,4 +8,5 @@ public interface FoodRepository extends JpaRepository { 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 f2db24e..b813e8b 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -94,47 +94,36 @@ public void deleteFavoriteFood(Long favoriteFoodId) { // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { List foodList = foodRepository.findAllByUserIdAndDate(userId, date); - User targetUser = getUserById(userId); - int totalKcal = 0; - int totalCarbohydrate = 0; - int totalProtein = 0; - int totalFat = 0; - - for (Food food : foodList) { - BaseNutrition targetFoodNutrition = food.getBaseNutrition(); - totalKcal += targetFoodNutrition.getKcal(); - totalCarbohydrate += targetFoodNutrition.getCarbohydrate(); - totalProtein += targetFoodNutrition.getProtein(); - totalFat += targetFoodNutrition.getFat(); - } - - double ratioKcal = Math.round((totalKcal*1.0)/(targetUser.getBaseNutrition().getKcal()*1.0))*10.0; - double ratioCarbohydrate = Math.round((totalCarbohydrate*1.0)/(targetUser.getBaseNutrition().getCarbohydrate()*1.0))*10.0; - double ratioProtein = Math.round((totalProtein*1.0)/(targetUser.getBaseNutrition().getProtein()*1.0))*10.0; - double ratioFat = Math.round((totalFat*1.0)/(targetUser.getBaseNutrition().getFat()*1.0))*10.0; - - return ResponseNutritionSumByDateDto.of(totalKcal,totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); + return calculateNutritionSumAndRatio(userId, foodList); } - @Transactional + @Transactional(readOnly = true) // 유저의 최근 7일간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) - public void getNutritionSumByWeek(Long userId) { + public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { + LocalDate endDate = LocalDate.now(); + LocalDate startDate = endDate.minusDays(6); + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, endDate); + return calculateNutritionSumAndRatio(userId, foodList); } - @Transactional + @Transactional(readOnly = true) // 유저의 최근 1개월간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) - public void getNutritionSumByMonth(Long userId) { + public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { + LocalDate endDate = LocalDate.now(); + LocalDate startDate = endDate.minusMonths(1); + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, endDate); + return calculateNutritionSumAndRatio(userId, foodList); } - @Transactional + @Transactional(readOnly = true) // 유저의 최근 7일간의 Best 3 음식 조회 (dto 구체적 협의 필요) public void getBestFoodByWeek(Long userId) { } - @Transactional + @Transactional(readOnly = true) // 유저의 최근 7일간의 Worst 3 음식 조회 (dto 구체적 협의 필요) public void getWorstFoodByWeek(Long userId) { @@ -155,6 +144,29 @@ private FavoriteFood getFavoriteFoodById(Long foodId){ .orElseThrow(() -> new FoodException(ResponseCode.FOOD_NOT_FOUND)); } + private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, List foodList){ + User targetUser = getUserById(userId); + int totalKcal = 0; + int totalCarbohydrate = 0; + int totalProtein = 0; + int totalFat = 0; + + for (Food food : foodList) { + BaseNutrition targetFoodNutrition = food.getBaseNutrition(); + totalKcal += targetFoodNutrition.getKcal(); + totalCarbohydrate += targetFoodNutrition.getCarbohydrate(); + totalProtein += targetFoodNutrition.getProtein(); + totalFat += targetFoodNutrition.getFat(); + } + + double ratioKcal = Math.round((totalKcal*1.0)/(targetUser.getBaseNutrition().getKcal()*1.0))*10.0; + double ratioCarbohydrate = Math.round((totalCarbohydrate*1.0)/(targetUser.getBaseNutrition().getCarbohydrate()*1.0))*10.0; + double ratioProtein = Math.round((totalProtein*1.0)/(targetUser.getBaseNutrition().getProtein()*1.0))*10.0; + double ratioFat = Math.round((totalFat*1.0)/(targetUser.getBaseNutrition().getFat()*1.0))*10.0; + + return ResponseNutritionSumByDateDto.of(totalKcal,totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); + } + /** * 메서드 구현 유의사항 From 5acb0d1879baee797324377fb8bf89105671c609 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 9 Oct 2023 19:38:46 +0900 Subject: [PATCH 058/371] =?UTF-8?q?=E2=9C=A8Feat:=20=ED=94=84=EB=A1=9C?= =?UTF-8?q?=ED=95=84=20=EA=B8=B0=EB=8A=A5=20=EA=B4=80=EB=A0=A8=20dto=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20(#19)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/dto/UpdateUserDto.java | 7 +++---- .../user/dto/UpdateUserNutritionDto.java | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/diareat/diareat/user/dto/UpdateUserNutritionDto.java diff --git a/src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java b/src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java index a882577..1a643d4 100644 --- a/src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java @@ -1,6 +1,5 @@ package com.diareat.diareat.user.dto; -import com.diareat.diareat.user.domain.BaseNutrition; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -15,9 +14,9 @@ public class UpdateUserDto { private int height; private int weight; private int age; - private BaseNutrition baseNutrition; + private boolean isAutoUpdateNutrition; // 개인정보를 활용한 기준 영양소 자동계산 여부 - public static UpdateUserDto of(Long userId, String userName, int userHeight, int userWeight, int userAge, BaseNutrition userBaseNutrition) { - return new UpdateUserDto(userId, userName, userHeight, userWeight, userAge, userBaseNutrition); + public static UpdateUserDto of(Long userId, String userName, int userHeight, int userWeight, int userAge, boolean isAutoUpdateNutrition) { + return new UpdateUserDto(userId, userName, userHeight, userWeight, userAge, isAutoUpdateNutrition); } } diff --git a/src/main/java/com/diareat/diareat/user/dto/UpdateUserNutritionDto.java b/src/main/java/com/diareat/diareat/user/dto/UpdateUserNutritionDto.java new file mode 100644 index 0000000..a5e6aee --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/dto/UpdateUserNutritionDto.java @@ -0,0 +1,21 @@ +package com.diareat.diareat.user.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class UpdateUserNutritionDto { + + private Long userId; + private int calorie; + private int carbohydrate; + private int protein; + private int fat; + + public static UpdateUserNutritionDto of(Long userId, int calorie, int carbohydrate, int protein, int fat) { + return new UpdateUserNutritionDto(userId, calorie, carbohydrate, protein, fat); + } +} From 5b5fffcf9423d6b6a38f217c1597f3f389663957 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 9 Oct 2023 19:56:07 +0900 Subject: [PATCH 059/371] =?UTF-8?q?=E2=9C=A8Feat:=20=EC=B9=9C=EA=B5=AC=20?= =?UTF-8?q?=EA=B4=80=EB=A6=AC=20=EA=B8=B0=EB=8A=A5=20=EA=B4=80=EB=A0=A8=20?= =?UTF-8?q?dto=20=EC=B6=94=EA=B0=80=20(#19)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/dto/FollowUserDto.java | 14 ++++++++++++++ .../user/dto/ResponseSearchUserDto.java | 17 +++++++++++++++++ .../diareat/user/dto/SearchUserDto.java | 18 ++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/user/dto/FollowUserDto.java create mode 100644 src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java create mode 100644 src/main/java/com/diareat/diareat/user/dto/SearchUserDto.java diff --git a/src/main/java/com/diareat/diareat/user/dto/FollowUserDto.java b/src/main/java/com/diareat/diareat/user/dto/FollowUserDto.java new file mode 100644 index 0000000..336a337 --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/dto/FollowUserDto.java @@ -0,0 +1,14 @@ +package com.diareat.diareat.user.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class FollowUserDto { + + private Long userId; + private Long followUserId; +} diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java new file mode 100644 index 0000000..bb2972c --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java @@ -0,0 +1,17 @@ +package com.diareat.diareat.user.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class ResponseSearchUserDto { + + private Long userId; + private String name; + private String image; + + public static ResponseSearchUserDto of(Long userId, String name, String image) { + return new ResponseSearchUserDto(userId, name, image); + } +} diff --git a/src/main/java/com/diareat/diareat/user/dto/SearchUserDto.java b/src/main/java/com/diareat/diareat/user/dto/SearchUserDto.java new file mode 100644 index 0000000..d6aa5db --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/dto/SearchUserDto.java @@ -0,0 +1,18 @@ +package com.diareat.diareat.user.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class SearchUserDto { + + private Long userId; + private String inputName; + + public static SearchUserDto of(Long userId, String inputName) { + return new SearchUserDto(userId, inputName); + } +} From 5c3c8eadcdb8b73e77b6fd1b4a8a83508c1011a4 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 9 Oct 2023 20:44:29 +0900 Subject: [PATCH 060/371] =?UTF-8?q?=E2=9C=A8Feat:=20=ED=8C=94=EB=A1=9C?= =?UTF-8?q?=EC=9A=B0=20=EA=B8=B0=EB=8A=A5=20User=EC=97=90=EC=84=9C=20?= =?UTF-8?q?=EB=B6=84=EB=A6=AC=ED=95=98=EC=97=AC=20=EA=B5=AC=ED=98=84=20(#1?= =?UTF-8?q?9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/user/domain/Follow.java | 37 +++++++++++++++++++ .../com/diareat/diareat/user/domain/User.java | 26 ++++--------- .../user/repository/FollowRepository.java | 14 +++++++ 3 files changed, 58 insertions(+), 19 deletions(-) create mode 100644 src/main/java/com/diareat/diareat/user/domain/Follow.java create mode 100644 src/main/java/com/diareat/diareat/user/repository/FollowRepository.java diff --git a/src/main/java/com/diareat/diareat/user/domain/Follow.java b/src/main/java/com/diareat/diareat/user/domain/Follow.java new file mode 100644 index 0000000..991834e --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/domain/Follow.java @@ -0,0 +1,37 @@ +package com.diareat.diareat.user.domain; + +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.io.Serializable; + +@NoArgsConstructor +@IdClass(Follow.PK.class) // 복합키를 위한 어노테이션 +@Getter +@Table(uniqueConstraints = { + @UniqueConstraint(columnNames = {"to_user", "from_user"}) +}) // 중복 팔로우 방지 +@Entity +public class Follow { + + @Id + @Column(name = "to_user", insertable = false, updatable = false) + private Long toUser; + + @Id + @Column(name = "from_user", insertable = false, updatable = false) + private Long fromUser; + + public static Follow makeFollow(Long toUser, Long fromUser) { + Follow follow = new Follow(); + follow.toUser = toUser; + follow.fromUser = fromUser; + return follow; + } + + public static class PK implements Serializable { // 복합키를 위한 클래스 + Long toUser; + Long fromUser; + } +} diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index f28c005..2f0d619 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -9,9 +9,7 @@ import javax.persistence.*; import java.util.ArrayList; -import java.util.HashSet; import java.util.List; -import java.util.Set; @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @@ -27,6 +25,8 @@ public class User { @JsonIgnore private String keyCode; // 로그인 식별키 + private String image; // 프로필 사진 경로 + private int height; // 키 private int weight; // 몸무게 @@ -35,7 +35,7 @@ public class User { private int age; // 나이 - private BaseNutrition baseNutrition; // 영양소 + private BaseNutrition baseNutrition; // 기준영양소 @OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) // 유저가 탈퇴하면 촬영한 음식도 삭제 private List foods = new ArrayList<>(); @@ -43,14 +43,6 @@ public class User { @OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) // 유저가 탈퇴하면 즐겨찾기 음식도 삭제 private List favoriteFoods = new ArrayList<>(); - @ManyToMany // 팔로우 목록 - @JoinTable( - name = "user_follows", - joinColumns = @JoinColumn(name = "follower_id"), - inverseJoinColumns = @JoinColumn(name = "following_id") - ) - private Set followings = new HashSet<>(); - // 생성 메서드 public static User createUser(String name, String keyCode, int height, int weight, int gender, int age, BaseNutrition baseNutrition) { User user = new User(); @@ -65,19 +57,15 @@ public static User createUser(String name, String keyCode, int height, int weigh } // 회원정보 수정 - public void updateUser(String name, int height, int weight, int age, BaseNutrition baseNutrition) { + public void updateUser(String name, int height, int weight, int age) { this.name = name; this.height = height; this.weight = weight; this.age = age; - this.baseNutrition = baseNutrition; } - public void followUser(User user) { - this.followings.add(user); - } - - public void unfollowUser(User user) { - this.followings.remove(user); + // 회원 기준영양소 직접 수정 + public void updateBaseNutrition(BaseNutrition baseNutrition) { + this.baseNutrition = baseNutrition; } } diff --git a/src/main/java/com/diareat/diareat/user/repository/FollowRepository.java b/src/main/java/com/diareat/diareat/user/repository/FollowRepository.java new file mode 100644 index 0000000..e5ff152 --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/repository/FollowRepository.java @@ -0,0 +1,14 @@ +package com.diareat.diareat.user.repository; + +import com.diareat.diareat.user.domain.Follow; +import com.diareat.diareat.user.domain.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; + +public interface FollowRepository extends JpaRepository { + @Query(value = "select u from Follow f INNER JOIN User u ON f.toUser = u.id where f.fromUser = :userId") // 팔로우 목록 조회 + List findAllByFromUser(@Param("userId") Long userId); +} From 6fe33cd95a4eba6b80d2b7f7958224b575fbd257 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 9 Oct 2023 20:51:40 +0900 Subject: [PATCH 061/371] =?UTF-8?q?=E2=99=BB=EF=B8=8FRefactor:=20=EA=B2=80?= =?UTF-8?q?=EC=83=89/=ED=94=84=EB=A1=9C=ED=95=84=20=EA=B8=B0=EB=8A=A5=20dt?= =?UTF-8?q?o=20=EC=88=98=EC=A0=95=20(#19)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/dto/ResponseRankUserDto.java | 22 ++++++++++++++++++ .../user/dto/ResponseResearchUserDto.java | 16 ------------- .../user/dto/ResponseSearchUserDto.java | 5 ++-- .../user/dto/ResponseSimpleUserDto.java | 17 ++++++++++++++ .../diareat/user/dto/ResponseUserDto.java | 12 ++++------ .../user/dto/ResponseUserNutritionDto.java | 23 +++++++++++++++++++ .../user/repository/FollowRepository.java | 2 ++ 7 files changed, 71 insertions(+), 26 deletions(-) create mode 100644 src/main/java/com/diareat/diareat/user/dto/ResponseRankUserDto.java delete mode 100644 src/main/java/com/diareat/diareat/user/dto/ResponseResearchUserDto.java create mode 100644 src/main/java/com/diareat/diareat/user/dto/ResponseSimpleUserDto.java create mode 100644 src/main/java/com/diareat/diareat/user/dto/ResponseUserNutritionDto.java diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseRankUserDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseRankUserDto.java new file mode 100644 index 0000000..c4c0700 --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/dto/ResponseRankUserDto.java @@ -0,0 +1,22 @@ +package com.diareat.diareat.user.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class ResponseRankUserDto { + + private Long userId; + private String name; + private String image; + private double calorieScore; + private double carbohydrateScore; + private double proteinScore; + private double fatScore; + private double totalScore; + + public static ResponseRankUserDto of(Long userId, String name, String image, double calorieScore, double carbohydrateScore, double proteinScore, double fatScore, double totalScore) { + return new ResponseRankUserDto(userId, name, image, calorieScore, carbohydrateScore, proteinScore, fatScore, totalScore); + } +} diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseResearchUserDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseResearchUserDto.java deleted file mode 100644 index 24aac2f..0000000 --- a/src/main/java/com/diareat/diareat/user/dto/ResponseResearchUserDto.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.diareat.diareat.user.dto; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -@Getter -@AllArgsConstructor -public class ResponseResearchUserDto { - - private Long userId; - private String name; - - public static ResponseResearchUserDto of(Long userId, String name) { - return new ResponseResearchUserDto(userId, name); - } -} diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java index bb2972c..ef4a23a 100644 --- a/src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java @@ -10,8 +10,9 @@ public class ResponseSearchUserDto { private Long userId; private String name; private String image; + private boolean isFollow; // 유저가 이미 팔로우한 유저인지 확인 - public static ResponseSearchUserDto of(Long userId, String name, String image) { - return new ResponseSearchUserDto(userId, name, image); + public static ResponseSearchUserDto of(Long userId, String name, String image, boolean isFollow) { + return new ResponseSearchUserDto(userId, name, image, isFollow); } } diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseSimpleUserDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseSimpleUserDto.java new file mode 100644 index 0000000..b56e7f6 --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/dto/ResponseSimpleUserDto.java @@ -0,0 +1,17 @@ +package com.diareat.diareat.user.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class ResponseSimpleUserDto { + + private String name; + private String image; + private double nutritionScore; + + public static ResponseSimpleUserDto of(String name, String image, double nutritionScore) { + return new ResponseSimpleUserDto(name, image, nutritionScore); + } +} diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java index ecdb851..dcda49f 100644 --- a/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java @@ -1,6 +1,5 @@ package com.diareat.diareat.user.dto; -import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; import lombok.AllArgsConstructor; import lombok.Getter; @@ -12,16 +11,13 @@ public class ResponseUserDto { private String name; private int height; private int weight; - private int gender; private int age; - private BaseNutrition baseNutrition; - - public static ResponseUserDto of(String userName, int userHeight, int userWeight, int userGender, int userAge, BaseNutrition userBaseNutrition) { - return new ResponseUserDto(userName, userHeight, userWeight, userGender, userAge, userBaseNutrition); + public static ResponseUserDto from(User user) { + return new ResponseUserDto(user.getName(), user.getHeight(), user.getWeight(), user.getAge()); } - public static ResponseUserDto from(User user) { - return new ResponseUserDto(user.getName(), user.getHeight(), user.getWeight(), user.getGender(), user.getAge(), user.getBaseNutrition()); + public static ResponseUserDto of(String name, int height, int weight, int age) { + return new ResponseUserDto(name, height, weight, age); } } diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseUserNutritionDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseUserNutritionDto.java new file mode 100644 index 0000000..a2db114 --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/dto/ResponseUserNutritionDto.java @@ -0,0 +1,23 @@ +package com.diareat.diareat.user.dto; + +import com.diareat.diareat.user.domain.User; +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class ResponseUserNutritionDto { + + private int calorie; + private int carbohydrate; + private int protein; + private int fat; + + public static ResponseUserNutritionDto of(int calorie, int carbohydrate, int protein, int fat) { + return new ResponseUserNutritionDto(calorie, carbohydrate, protein, fat); + } + + public static ResponseUserNutritionDto from(User user) { + return new ResponseUserNutritionDto(user.getBaseNutrition().getKcal(), user.getBaseNutrition().getCarbohydrate(), user.getBaseNutrition().getProtein(), user.getBaseNutrition().getFat()); + } +} diff --git a/src/main/java/com/diareat/diareat/user/repository/FollowRepository.java b/src/main/java/com/diareat/diareat/user/repository/FollowRepository.java index e5ff152..cfd4843 100644 --- a/src/main/java/com/diareat/diareat/user/repository/FollowRepository.java +++ b/src/main/java/com/diareat/diareat/user/repository/FollowRepository.java @@ -11,4 +11,6 @@ public interface FollowRepository extends JpaRepository { @Query(value = "select u from Follow f INNER JOIN User u ON f.toUser = u.id where f.fromUser = :userId") // 팔로우 목록 조회 List findAllByFromUser(@Param("userId") Long userId); + + boolean existsByFromUserAndToUser(Long fromUser, Long toUser); // 팔로우 여부 확인 } From 9908210f0f9a90ac233371a3d2190ccbcb452f4c Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 10 Oct 2023 11:48:11 +0900 Subject: [PATCH 062/371] =?UTF-8?q?=E2=9C=A8=EF=B8=8FFeat:=20BaseNutrition?= =?UTF-8?q?=20=EA=B8=B0=EC=A4=80=EC=98=81=EC=96=91=EC=86=8C=20=EA=B3=84?= =?UTF-8?q?=EC=82=B0=EB=A1=9C=EC=A7=81=20=EC=9E=84=EC=8B=9C=20=EB=8F=84?= =?UTF-8?q?=EC=9E=85=20(#19)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/domain/BaseNutrition.java | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/domain/BaseNutrition.java b/src/main/java/com/diareat/diareat/user/domain/BaseNutrition.java index ed23ef2..86719f9 100644 --- a/src/main/java/com/diareat/diareat/user/domain/BaseNutrition.java +++ b/src/main/java/com/diareat/diareat/user/domain/BaseNutrition.java @@ -26,11 +26,22 @@ public static BaseNutrition createNutrition(int kcal, int carbohydrate, int prot return baseNutrition; } - // 영양소 수정 - public void updateNutrition(int kcal, int carbohydrate, int protein, int fat) { - this.kcal = kcal; - this.carbohydrate = carbohydrate; - this.protein = protein; - this.fat = fat; + // 생성 메서드 by 개인정보 (성별, 나이, 키, 몸무게로 기준영양소 자동 계산 기능) + public static BaseNutrition calculateNutrition(int gender, int age, int height, int weight) { + BaseNutrition baseNutrition = new BaseNutrition(); + + // 임의의 식으로 기초대사량 계산하였으며, 추후 식약처 및 관련 기관에서 제공하는 공식으로 변경할 예정 + baseNutrition.kcal = (int) (66.47 + (13.75 * weight) + (5 * height) - (6.76 * age)); // 기초대사량 계산식 + baseNutrition.carbohydrate = (int) (baseNutrition.kcal * 0.65 / 4); // 탄수화물 65% + baseNutrition.protein = (int) (baseNutrition.kcal * 0.1 / 4); // 단백질 10% + baseNutrition.fat = (int) (baseNutrition.kcal * 0.25 / 9); + + if(gender == 1) { // 여성일 경우 + baseNutrition.kcal -= 161; + baseNutrition.carbohydrate -= 40; + baseNutrition.protein -= 5; + baseNutrition.fat -= 10; + } + return baseNutrition; } } From 352897dcaad2132532cd57f930a0c1da2291b3b1 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 10 Oct 2023 12:00:53 +0900 Subject: [PATCH 063/371] =?UTF-8?q?=E2=9C=A8=EF=B8=8FFeat:=20=ED=94=84?= =?UTF-8?q?=EB=A1=9C=ED=95=84/=EC=B9=9C=EA=B5=AC=EA=B4=80=EB=A6=AC=20?= =?UTF-8?q?=EA=B8=B0=EB=8A=A5=20=EA=B4=80=EB=A0=A8=20UserService=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20(#19)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/service/UserService.java | 115 ++++++++---------- 1 file changed, 49 insertions(+), 66 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 1ebc485..ed90037 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -1,11 +1,10 @@ package com.diareat.diareat.user.service; import com.diareat.diareat.user.domain.BaseNutrition; +import com.diareat.diareat.user.domain.Follow; import com.diareat.diareat.user.domain.User; -import com.diareat.diareat.user.dto.CreateUserDto; -import com.diareat.diareat.user.dto.ResponseResearchUserDto; -import com.diareat.diareat.user.dto.ResponseUserDto; -import com.diareat.diareat.user.dto.UpdateUserDto; +import com.diareat.diareat.user.dto.*; +import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.util.api.ResponseCode; import com.diareat.diareat.util.exception.UserException; @@ -21,109 +20,93 @@ public class UserService { private final UserRepository userRepository; + private final FollowRepository followRepository; // 회원정보 저장 @Transactional public Long saveUser(CreateUserDto createUserDto) { - // 나이, 성별, 키, 몸무게로 기준 영양소 계산 (일단 임의의 값으로 설정했고 추후 로직 구성) - BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); + BaseNutrition baseNutrition = BaseNutrition.createNutrition(0, 0, 0, 0); // 로직 확정 전에는 임시 코드로 대체 + // BaseNutrition baseNutrition = BaseNutrition.createNutrition(createUserDto.getGender(), createUserDto.getAge(), createUserDto.getHeight(), createUserDto.getWeight()); User user = User.createUser(createUserDto.getName(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getAge(), createUserDto.getGender(), baseNutrition); return userRepository.save(user).getId(); } + // 회원 기본정보 조회 + @Transactional(readOnly = true) + public ResponseSimpleUserDto getSimpleUserInfo(Long userId) { + User user = getUserById(userId); + double nutritionScore = 100; // 로직 확정 전에는 임시 값으로 대체 + return ResponseSimpleUserDto.of(user.getName(), user.getImage(), nutritionScore); + } + // 회원정보 조회 @Transactional(readOnly = true) public ResponseUserDto getUserInfo(Long userId) { - return ResponseUserDto.from(getUserById(userId)); + User user = getUserById(userId); + return ResponseUserDto.from(user); } // 회원정보 수정 @Transactional public void updateUserInfo(UpdateUserDto updateUserDto) { User user = getUserById(updateUserDto.getUserId()); - BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); - user.updateUser(updateUserDto.getName(), updateUserDto.getHeight(), updateUserDto.getWeight(), updateUserDto.getAge(), baseNutrition); + user.updateUser(updateUserDto.getName(), updateUserDto.getHeight(), updateUserDto.getWeight(), updateUserDto.getAge()); + } + + // 회원 기준영양소 조회 + @Transactional(readOnly = true) + public ResponseUserNutritionDto getUserNutrition(Long userId) { + User user = getUserById(userId); + return ResponseUserNutritionDto.from(user); + } + + // 회원 기준영양소 직접 수정 + @Transactional + public void updateBaseNutrition(UpdateUserNutritionDto updateUserNutritionDto) { + User user = getUserById(updateUserNutritionDto.getUserId()); + BaseNutrition baseNutrition = BaseNutrition.createNutrition(updateUserNutritionDto.getCalorie(), updateUserNutritionDto.getCarbohydrate(), updateUserNutritionDto.getProtein(), updateUserNutritionDto.getFat()); + user.updateBaseNutrition(baseNutrition); } // 회원 탈퇴 @Transactional public void deleteUser(Long userId) { - User user = getUserById(userId); - userRepository.delete(user); + validateUser(userId); + userRepository.deleteById(userId); } - // 회원이 팔로우를 위해 검색한 유저 목록 조회 + // 회원의 친구 검색 결과 조회 @Transactional(readOnly = true) - public List searchUser(String name) { + public List searchUser(Long hostId, String name) { + validateUser(hostId); List users = userRepository.findAllByNameContaining(name); return users.stream() - .map(user -> ResponseResearchUserDto.of(user.getId(), user.getName())).collect(Collectors.toList()); + .map(user -> ResponseSearchUserDto.of(user.getId(), user.getName(), user.getImage(), followRepository.existsByFromUserAndToUser(hostId, user.getId()))).collect(Collectors.toList()); } // 회원이 특정 회원 팔로우 @Transactional public void followUser(Long userId, Long followId) { - User user = getUserById(userId); - User followUser = getUserById(followId); - user.followUser(followUser); + validateUser(userId); + validateUser(followId); + followRepository.save(Follow.makeFollow(userId, followId)); } // 회원이 특정 회원 팔로우 취소 @Transactional public void unfollowUser(Long userId, Long unfollowId) { - User user = getUserById(userId); - User followUser = getUserById(unfollowId); - user.unfollowUser(followUser); + validateUser(userId); + validateUser(unfollowId); + followRepository.delete(Follow.makeFollow(userId, unfollowId)); + } + + private void validateUser(Long userId) { + if(!userRepository.existsById(userId)) + throw new UserException(ResponseCode.USER_NOT_FOUND); } private User getUserById(Long userId) { return userRepository.findById(userId) .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); } - - /* - 아래 메서드들은 원래 두 패키지 모두에 존재할 수 있는 혼합적인 의미를 가지고 있으며, 일단 FoodService에서 구현을 담당할 예정이다. - 현재 UserService가 음식 관련 Repository에 의존하지 않고 있기에, FoodService에서 구현하는 것이 더 적절하다고 판단했다. - - // 유저의 즐겨찾기 음식 목록 조회 - public void getFavoriteFoodList(Long userId) { - - } - - // 유저의 특정 날짜에 먹은 음식 목록 조회 - public void getFoodListByDate(Long userId, LocalDate date) { - - } - - // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) - public void getNutritionSumByDate(Long userId, LocalDate date) { - - } - - // 유저의 최근 7일간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) - public void getNutritionSumByWeek(Long userId) { - - } - - // 유저의 최근 1개월간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) - public void getNutritionSumByMonth(Long userId) { - - } - - // 유저의 최근 7일간의 Best 3 음식 조회 (dto 구체적 협의 필요) - public void getBestFoodByWeek(Long userId) { - - } - - // 유저의 최근 7일간의 Worst 3 음식 조회 (dto 구체적 협의 필요) - public void getWorstFoodByWeek(Long userId) { - - } - */ - - /* - * 위 메서드 외 누락된 메서드가 존재할 수 있으며, UserService에는 아래와 같은 추가적인 부가 기능을 구현할 가능성이 있다. - * 1. 팔로우 목록에 나를 포함하여 칼탄단지 섭취량 기준으로 건강한 섭취 현황을 분석(?)하여 점수별로 정렬하는 랭킹 기능 - * 2. 주간 과제 기능 (예: 주간에 목표한 섭취량을 달성하면 보상이 주어지는 등) - */ } From aef5da6ae66c0e28ae8e6a50c1cab84d323ee443 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 10 Oct 2023 23:04:21 +0900 Subject: [PATCH 064/371] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=EF=B8=8FChore:=20Use?= =?UTF-8?q?rService=20=EC=98=A4=ED=83=80=20=EC=88=98=EC=A0=95=20(#19)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/user/service/UserService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index ed90037..866aa3d 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -27,7 +27,7 @@ public class UserService { public Long saveUser(CreateUserDto createUserDto) { BaseNutrition baseNutrition = BaseNutrition.createNutrition(0, 0, 0, 0); // 로직 확정 전에는 임시 코드로 대체 // BaseNutrition baseNutrition = BaseNutrition.createNutrition(createUserDto.getGender(), createUserDto.getAge(), createUserDto.getHeight(), createUserDto.getWeight()); - User user = User.createUser(createUserDto.getName(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getAge(), createUserDto.getGender(), baseNutrition); + User user = User.createUser(createUserDto.getName(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); return userRepository.save(user).getId(); } From c30ae9a6a8f6c78350ac6531a08ae73c96ab4d29 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 10 Oct 2023 23:07:21 +0900 Subject: [PATCH 065/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20Test:=20UserSe?= =?UTF-8?q?rviceTest=20=EC=B6=94=EA=B0=80=20=EC=9E=91=EC=84=B1=20(#19)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/UserServiceTest.java | 129 ++++++++++++------ 1 file changed, 88 insertions(+), 41 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/UserServiceTest.java b/src/test/java/com/diareat/diareat/service/UserServiceTest.java index 6f5ba89..0fdce53 100644 --- a/src/test/java/com/diareat/diareat/service/UserServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/UserServiceTest.java @@ -1,23 +1,18 @@ package com.diareat.diareat.service; -import com.diareat.diareat.user.domain.BaseNutrition; -import com.diareat.diareat.user.dto.CreateUserDto; -import com.diareat.diareat.user.dto.ResponseResearchUserDto; -import com.diareat.diareat.user.dto.ResponseUserDto; -import com.diareat.diareat.user.dto.UpdateUserDto; +import com.diareat.diareat.user.dto.*; +import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.user.service.UserService; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; -import java.util.List; - import static org.junit.jupiter.api.Assertions.*; - @SpringBootTest @Transactional class UserServiceTest { @@ -28,93 +23,145 @@ class UserServiceTest { @Autowired UserRepository userRepository; + @Autowired + FollowRepository followRepository; + @BeforeEach - public void setUp() { + void setUp() { userRepository.deleteAll(); + followRepository.deleteAll(); + } + + @AfterEach + void tearDown() { + userRepository.deleteAll(); + followRepository.deleteAll(); } @Test - void testSaveAndGetUserInfo() { // 회원정보 저장 및 조회 + void saveUser() { // given + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 75, 1, 25)); // when - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); ResponseUserDto responseUserDto = userService.getUserInfo(userId); - // 검증: 올바른 결과를 반환하는지 확인 + // then assertNotNull(responseUserDto); assertEquals("testUser", responseUserDto.getName()); + assertEquals(25, responseUserDto.getAge()); } @Test - void testUpdateUserInfo() { // 회원정보 수정 + void getSimpleUserInfo() { + // given + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 75, 1, 25)); + + // when + ResponseSimpleUserDto responseSimpleUserDto = userService.getSimpleUserInfo(userId); + // then + assertEquals("testUser", responseSimpleUserDto.getName()); + } + + @Test + void getUserInfo() { // given - Long id = userService.saveUser(CreateUserDto.of("1", "testPassword", 180, 75, 1, 25)); - BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 75, 1, 25)); + + // when + ResponseUserDto responseUserDto = userService.getUserInfo(userId); + + // then + assertEquals("testUser", responseUserDto.getName()); + } + + @Test + void updateUserInfo() { + // given + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 160, 50, 25)); + UpdateUserDto updateUserDto = UpdateUserDto.of(userId, "updateUser", 180, 75, 25, false); // when - UpdateUserDto updateUserDto = UpdateUserDto.of(id, "2", 185, 70, 75, baseNutrition); userService.updateUserInfo(updateUserDto); - ResponseUserDto responseUserDto = userService.getUserInfo(id); // then - assertNotNull(responseUserDto); - assertEquals("2", responseUserDto.getName()); - assertEquals(185, responseUserDto.getHeight()); - assertEquals(70, responseUserDto.getWeight()); + assertEquals("updateUser", userService.getUserInfo(userId).getName()); + assertEquals(180, userService.getUserInfo(userId).getHeight()); } @Test - void testDeleteUser() { // 회원 탈퇴 + void getUserNutrition() { // 임시 코드 사용, 추후 로직 개편 시 테스트코드 수정 // given - Long id = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 160, 50, 25)); // when - userService.deleteUser(id); + ResponseUserNutritionDto responseUserNutritionDto = userService.getUserNutrition(userId); // then - assertNull(userRepository.findById(id).orElse(null)); + assertEquals(0, responseUserNutritionDto.getCalorie()); } @Test - void testSearchUserName() { + void updateBaseNutrition() { // given - userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); - userService.saveUser(CreateUserDto.of("hello", "testPassword", 180, 75, 1, 25)); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 160, 50, 25)); // when - String name = "testUser"; - List users = userService.searchUser(name); + UpdateUserNutritionDto updateUserNutritionDto = UpdateUserNutritionDto.of(userId, 2000, 300, 80, 80); + userService.updateBaseNutrition(updateUserNutritionDto); // then - assertEquals(1, users.size()); + assertEquals(2000, userService.getUserNutrition(userId).getCalorie()); } @Test - void testFollowUser() { // 회원이 특정 회원 팔로우 + void deleteUser() { // given - Long id1 = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); - Long id2 = userService.saveUser(CreateUserDto.of("followUser", "testPassword", 180, 75, 1, 25)); + Long id = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 75, 1, 25)); // when - userService.followUser(id1, id2); + userService.deleteUser(id); + + // then + assertFalse(userRepository.existsById(id)); + } + + @Test + void searchUser() { + // given + userService.saveUser(CreateUserDto.of("user1", "testPassword", 0, 175, 80, 25)); + Long id = userService.saveUser(CreateUserDto.of("user2", "testPassword", 0, 175, 80, 25)); + String name = "user"; + + // then + assertEquals(2, userService.searchUser(id, name).size()); + } + + @Test + void followUser() { + // given + Long id1 = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 75, 1, 25)); + Long id2 = userService.saveUser(CreateUserDto.of("followUser", "testPassword", 0, 75, 1, 25)); + + // when + userService.followUser(id2, id1); // then - assertEquals(1, userRepository.findById(id1).get().getFollowings().size()); + assertEquals(1, followRepository.findAllByFromUser(id1).size()); } @Test - void testUnfollowUser() { // 회원이 특정 회원 팔로우 취소 + void unfollowUser() { // given - Long id1 = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 180, 75, 1, 25)); - Long id2 = userService.saveUser(CreateUserDto.of("followUser", "testPassword", 180, 75, 1, 25)); + Long id1 = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 175, 1, 25)); + Long id2 = userService.saveUser(CreateUserDto.of("followUser", "testPassword", 0, 175, 1, 25)); // when userService.followUser(id1, id2); userService.unfollowUser(id1, id2); // then - assertEquals(0, userRepository.findById(id1).get().getFollowings().size()); + assertEquals(0, followRepository.findAllByFromUser(id1).size()); } -} +} \ No newline at end of file From 05399865eebf26de90942b9f0242de7a9cd399f7 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 10 Oct 2023 23:25:00 +0900 Subject: [PATCH 066/371] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=EF=B8=8FChore:=20Use?= =?UTF-8?q?rServiceTest=20=EC=98=A4=EB=A5=98=20=EC=88=98=EC=A0=95=20(#19)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/user/service/UserService.java | 2 +- src/test/java/com/diareat/diareat/service/UserServiceTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 866aa3d..2ce3bee 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -25,7 +25,7 @@ public class UserService { // 회원정보 저장 @Transactional public Long saveUser(CreateUserDto createUserDto) { - BaseNutrition baseNutrition = BaseNutrition.createNutrition(0, 0, 0, 0); // 로직 확정 전에는 임시 코드로 대체 + BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); // BaseNutrition baseNutrition = BaseNutrition.createNutrition(createUserDto.getGender(), createUserDto.getAge(), createUserDto.getHeight(), createUserDto.getWeight()); User user = User.createUser(createUserDto.getName(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); return userRepository.save(user).getId(); diff --git a/src/test/java/com/diareat/diareat/service/UserServiceTest.java b/src/test/java/com/diareat/diareat/service/UserServiceTest.java index 0fdce53..7d2ec45 100644 --- a/src/test/java/com/diareat/diareat/service/UserServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/UserServiceTest.java @@ -99,7 +99,7 @@ void getUserNutrition() { // 임시 코드 사용, 추후 로직 개편 시 테 ResponseUserNutritionDto responseUserNutritionDto = userService.getUserNutrition(userId); // then - assertEquals(0, responseUserNutritionDto.getCalorie()); + assertEquals(2000, responseUserNutritionDto.getCalorie()); } @Test From 73441ef4eabb49285e043aa0502ea361dd967d00 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 13:29:12 +0900 Subject: [PATCH 067/371] =?UTF-8?q?:bug:=20fix:=20=EC=9E=98=EB=AA=BB?= =?UTF-8?q?=EB=90=9C=20=EC=98=81=EC=96=91=EC=86=8C=20=EB=B9=84=EC=9C=A8=20?= =?UTF-8?q?=EA=B3=84=EC=82=B0=20=EB=A1=9C=EC=A7=81=20=EC=88=98=EC=A0=95=20?= =?UTF-8?q?(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 32 +++++++++++++++---- 1 file changed, 26 insertions(+), 6 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 b813e8b..b87a886 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -15,7 +15,9 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.rmi.registry.LocateRegistry; import java.time.LocalDate; +import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; @@ -119,14 +121,32 @@ public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { @Transactional(readOnly = true) // 유저의 최근 7일간의 Best 3 음식 조회 (dto 구체적 협의 필요) - public void getBestFoodByWeek(Long userId) { + public ResponseFoodRankDto getBestFoodByWeek(Long userId, LocalDate startDate) { + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, startDate.minusWeeks(1)); + List top3Foods = foodList.stream() + .sorted(Comparator.comparingDouble((Food food) -> + 0.7 * food.getBaseNutrition().getProtein()- 0.3 * food.getBaseNutrition().getProtein()).reversed()) + .limit(3) + .collect(Collectors.toList()); //고단백 저지방일수록 점수를 높게 측정되도록 기준을 잡은 후, 그 기준을 기반으로 정렬 + //사용한 기준은, 고단백과 저지방의 점수 반영 비율을 7:3으로 측정하고, 단백질량이 높을 수록, 지방량이 낮을 수록 점수가 높음. 이후, 내림차순 정렬 + + return ResponseFoodRankDto.of(userId, top3Foods, startDate, true); } @Transactional(readOnly = true) // 유저의 최근 7일간의 Worst 3 음식 조회 (dto 구체적 협의 필요) - public void getWorstFoodByWeek(Long userId) { + public ResponseFoodRankDto getWorstFoodByWeek(Long userId, LocalDate startDate) { + + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, startDate.minusWeeks(1)); + + List worst3Foods = foodList.stream() + .sorted(Comparator.comparingDouble((Food food) -> + 0.7 * food.getBaseNutrition().getProtein()- 0.3 * food.getBaseNutrition().getProtein())) + .limit(3) + .collect(Collectors.toList()); + return ResponseFoodRankDto.of(userId, worst3Foods, startDate, false); } private User getUserById(Long userId){ @@ -159,10 +179,10 @@ private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, totalFat += targetFoodNutrition.getFat(); } - double ratioKcal = Math.round((totalKcal*1.0)/(targetUser.getBaseNutrition().getKcal()*1.0))*10.0; - double ratioCarbohydrate = Math.round((totalCarbohydrate*1.0)/(targetUser.getBaseNutrition().getCarbohydrate()*1.0))*10.0; - double ratioProtein = Math.round((totalProtein*1.0)/(targetUser.getBaseNutrition().getProtein()*1.0))*10.0; - double ratioFat = Math.round((totalFat*1.0)/(targetUser.getBaseNutrition().getFat()*1.0))*10.0; + double ratioKcal = Math.round((((double) totalKcal /(double) targetUser.getBaseNutrition().getKcal())*100.0)*10.0)/10.0; + double ratioCarbohydrate = Math.round((((double) totalCarbohydrate /(double) targetUser.getBaseNutrition().getCarbohydrate())*100.0)*10.0)/10.0; + double ratioProtein = Math.round((((double) totalProtein /(double) targetUser.getBaseNutrition().getProtein())*100.0)*10.0)/10.0; + double ratioFat =Math.round((((double) totalFat /(double) targetUser.getBaseNutrition().getFat())*100.0)*10.0)/10.0; return ResponseNutritionSumByDateDto.of(totalKcal,totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); } From 13367fb8f2c1c355701241d83b65bdc233f6039e Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 13:30:56 +0900 Subject: [PATCH 068/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20?= =?UTF-8?q?=EC=98=81=EC=96=91=EC=86=8C=20=EB=B9=84=EC=9C=A8=20=EA=B3=84?= =?UTF-8?q?=EC=82=B0=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/FoodServiceTest.java | 49 ++++++++++++++++--- 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index b633575..e7dfba1 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -7,6 +7,7 @@ import com.diareat.diareat.food.repository.FoodRepository; 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.CreateUserDto; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.user.service.UserService; @@ -17,6 +18,7 @@ import org.springframework.transaction.annotation.Transactional; import java.util.List; +import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; @@ -153,24 +155,55 @@ void testDeleteFavoriteFood() { @Test void testNutritionSumByDate(){ //given - BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(100,150,200,250); + BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword",1, 180, 80, 18)); Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood", testFoodNutrition)); Food food = foodRepository.getReferenceById(foodId); //when ResponseNutritionSumByDateDto responseNutritionSumByDateDto = foodService.getNutritionSumByDate(userId,food.getDate()); - - assertNotNull(responseNutritionSumByDateDto); - assertEquals(100, responseNutritionSumByDateDto.getTotalKcal()); + assertEquals(1400, responseNutritionSumByDateDto.getTotalKcal()); assertEquals(150, responseNutritionSumByDateDto.getTotalCarbohydrate()); assertEquals(200, responseNutritionSumByDateDto.getTotalProtein()); assertEquals(250, responseNutritionSumByDateDto.getTotalFat()); - assertEquals(Math.round((100*1.0)/(2000*1.0))*10.0, responseNutritionSumByDateDto.getRatioKcal()); - assertEquals(Math.round((150*1.0)/(300*1.0))*10.0, responseNutritionSumByDateDto.getRatioCarbohydrate()); - assertEquals(Math.round((200*1.0)/(80*1.0))*10.0, responseNutritionSumByDateDto.getRatioProtein()); - assertEquals(Math.round((250*1.0)/(80*1.0))*10.0, responseNutritionSumByDateDto.getRatioFat()); + assertEquals(Math.round((((double)1400 / (double)2000) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioKcal()); + assertEquals(Math.round((((double)150 / (double)300) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioCarbohydrate()); + assertEquals(Math.round((((double)200 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioProtein()); + assertEquals(Math.round((((double)250 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioFat()); + } + @Test + void testNutritionSumByWeekAndMonth(){ + //given + BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(100,150,200,250); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword",1, 180, 80, 18)); + Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood", testFoodNutrition)); + + } + + @Test + void getTop3HighProteinLowFatFoodsTest() { + // given + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 1, 180, 80, 18)); + foodService.saveFood(CreateFoodDto.of(userId, "Food1", BaseNutrition.createNutrition(100, 100 ,10, 1))); + foodService.saveFood(CreateFoodDto.of(userId, "Food2", BaseNutrition.createNutrition(100, 100 ,8, 2))); + foodService.saveFood(CreateFoodDto.of(userId, "Food3", BaseNutrition.createNutrition(100, 100 ,6, 3))); + foodService.saveFood(CreateFoodDto.of(userId, "Food4", BaseNutrition.createNutrition(100, 100 ,4, 4))); + Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "Food5", BaseNutrition.createNutrition(100, 100 ,2, 5))); + + Food testFood = foodRepository.getReferenceById(foodId); +// +// // when +// ResponseNutritionSumByDateDto response = foodService.getNutritionSumByDate(userId, testFood.getDate()); +//// List top3Foods = response.getRankFoodList(); +//// +//// // then +//// assertEquals(3, top3Foods.size()); +//// assertEquals("Food1", top3Foods.get(0).getName()); +//// assertEquals("Food2", top3Foods.get(1).getName()); +//// assertEquals("Food3", top3Foods.get(2).getName()); +// assertNotNull(testFood.getName()); +// assertEquals("Food5", testFood.getDate()); } } From 2b25968aad6827fffd6b85ef8b69211856f21162 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 13:32:40 +0900 Subject: [PATCH 069/371] =?UTF-8?q?:sparkles:=20feat:=20=EC=9D=8C=EC=8B=9D?= =?UTF-8?q?=20=EC=83=9D=EC=84=B1=20=EB=82=A0=EC=A7=9C=20=ED=98=84=EC=9E=AC?= =?UTF-8?q?=20=EB=82=A0=EC=A7=9C=EB=A1=9C=20=EC=88=98=EC=A0=95=20(#18)?= 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 | 1 + 1 file changed, 1 insertion(+) 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 7b98ef5..490f4da 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -42,6 +42,7 @@ public static Food createFood(String name, User user, BaseNutrition baseNutritio Food food = new Food(); food.name = name; food.user = user; + food.date = LocalDate.now(); food.time = LocalTime.now(); food.baseNutrition = baseNutrition; return food; From 85edad8dd6c3b9af868f40ea058f6b7af3f7a283 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 13:42:14 +0900 Subject: [PATCH 070/371] =?UTF-8?q?:bug:=20fix:=20=EC=9E=98=EB=AA=BB?= =?UTF-8?q?=EB=90=9C=20=EB=82=A0=EC=A7=9C=20=EA=B8=B0=EA=B0=84=20=EC=84=A4?= =?UTF-8?q?=EC=A0=95=20=EC=88=98=EC=A0=95=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/service/FoodService.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 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 b87a886..a622fdc 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -121,8 +121,8 @@ public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { @Transactional(readOnly = true) // 유저의 최근 7일간의 Best 3 음식 조회 (dto 구체적 협의 필요) - public ResponseFoodRankDto getBestFoodByWeek(Long userId, LocalDate startDate) { - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, startDate.minusWeeks(1)); + public ResponseFoodRankDto getBestFoodByWeek(Long userId, LocalDate endDate) { + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); List top3Foods = foodList.stream() .sorted(Comparator.comparingDouble((Food food) -> @@ -131,14 +131,14 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId, LocalDate startDate) { .collect(Collectors.toList()); //고단백 저지방일수록 점수를 높게 측정되도록 기준을 잡은 후, 그 기준을 기반으로 정렬 //사용한 기준은, 고단백과 저지방의 점수 반영 비율을 7:3으로 측정하고, 단백질량이 높을 수록, 지방량이 낮을 수록 점수가 높음. 이후, 내림차순 정렬 - return ResponseFoodRankDto.of(userId, top3Foods, startDate, true); + return ResponseFoodRankDto.of(userId, top3Foods, endDate, true); } @Transactional(readOnly = true) // 유저의 최근 7일간의 Worst 3 음식 조회 (dto 구체적 협의 필요) - public ResponseFoodRankDto getWorstFoodByWeek(Long userId, LocalDate startDate) { + public ResponseFoodRankDto getWorstFoodByWeek(Long userId, LocalDate endDate) { - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, startDate.minusWeeks(1)); + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); List worst3Foods = foodList.stream() .sorted(Comparator.comparingDouble((Food food) -> @@ -146,7 +146,7 @@ public ResponseFoodRankDto getWorstFoodByWeek(Long userId, LocalDate startDate) .limit(3) .collect(Collectors.toList()); - return ResponseFoodRankDto.of(userId, worst3Foods, startDate, false); + return ResponseFoodRankDto.of(userId, worst3Foods, endDate, false); } private User getUserById(Long userId){ From 05d85dd9f62b00a68c0117bd2a2079838eb02059 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 13:45:40 +0900 Subject: [PATCH 071/371] =?UTF-8?q?:sparkles:=20feat:=20Worst=203=20?= =?UTF-8?q?=EC=9D=8C=EC=8B=9D=20=EC=A1=B0=ED=9A=8C=20=EB=A1=9C=EC=A7=81=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 고지방, 고탄수 --- .../java/com/diareat/diareat/food/service/FoodService.java | 3 ++- 1 file changed, 2 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 a622fdc..1a6b40f 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -142,9 +142,10 @@ public ResponseFoodRankDto getWorstFoodByWeek(Long userId, LocalDate endDate) { List worst3Foods = foodList.stream() .sorted(Comparator.comparingDouble((Food food) -> - 0.7 * food.getBaseNutrition().getProtein()- 0.3 * food.getBaseNutrition().getProtein())) + 0.7 * food.getBaseNutrition().getFat() + 0.3 * food.getBaseNutrition().getCarbohydrate()).reversed()) .limit(3) .collect(Collectors.toList()); + //반대로 고지방 고탄수의 경우를 7:3으로 측정하고, 지방이 높을 수록 점수가 급격히 높아짐. 이 경우는 점수가 높은 것이 안좋음. return ResponseFoodRankDto.of(userId, worst3Foods, endDate, false); } From 14c8223af7ab1dbb0efda18a310f77f67c9e768e Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 13:46:02 +0900 Subject: [PATCH 072/371] =?UTF-8?q?:sparkles:=20feat:=20Best,=20Worst=20?= =?UTF-8?q?=EC=9D=8C=EC=8B=9D=20=EC=84=A0=EC=A0=95=20=EC=9C=84=ED=95=9C=20?= =?UTF-8?q?=EC=9E=84=EC=8B=9C=20Dto=20=EA=B5=AC=ED=98=84=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/dto/ResponseFoodRankDto.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java new file mode 100644 index 0000000..6f32f5f --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java @@ -0,0 +1,24 @@ +package com.diareat.diareat.food.dto; + +import com.diareat.diareat.food.domain.Food; +import com.diareat.diareat.user.domain.BaseNutrition; +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.List; + +@Getter +@AllArgsConstructor +public class ResponseFoodRankDto { + + private Long userId; + 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) { + return new ResponseFoodRankDto(userId, rankFoodList, startDate, isBest); + } +} From fe650909adff575b348583b60301439847dbdfda Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 13:58:16 +0900 Subject: [PATCH 073/371] =?UTF-8?q?:bulb:=20chore:=20Best3,=20Worst3=20?= =?UTF-8?q?=EC=84=A0=EC=A0=95=20=EA=B8=B0=EC=A4=80=20=EB=85=BC=EC=9D=98=20?= =?UTF-8?q?=EC=A3=BC=EC=84=9D=20=EC=B6=94=EA=B0=80=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/service/FoodService.java | 4 ++++ 1 file changed, 4 insertions(+) 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 1a6b40f..3222f7a 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -130,6 +130,7 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId, LocalDate endDate) { .limit(3) .collect(Collectors.toList()); //고단백 저지방일수록 점수를 높게 측정되도록 기준을 잡은 후, 그 기준을 기반으로 정렬 //사용한 기준은, 고단백과 저지방의 점수 반영 비율을 7:3으로 측정하고, 단백질량이 높을 수록, 지방량이 낮을 수록 점수가 높음. 이후, 내림차순 정렬 + // ** Best 3 기준 논의 필요 ** return ResponseFoodRankDto.of(userId, top3Foods, endDate, true); } @@ -146,6 +147,9 @@ public ResponseFoodRankDto getWorstFoodByWeek(Long userId, LocalDate endDate) { .limit(3) .collect(Collectors.toList()); //반대로 고지방 고탄수의 경우를 7:3으로 측정하고, 지방이 높을 수록 점수가 급격히 높아짐. 이 경우는 점수가 높은 것이 안좋음. + //(수정) https://blog.nongshim.com/1961, 탄수화물이 더 영향을 미친다고 하는데...흠... + // ** 이점은 논의가 필요할 듯? ** + // 우선 임시로 지방 비율을 높게 설정 return ResponseFoodRankDto.of(userId, worst3Foods, endDate, false); } From dfb25036f819134000c023abb1108d9f2d990924 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 13:58:39 +0900 Subject: [PATCH 074/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20Worst3?= =?UTF-8?q?=20=EC=84=A0=EC=A0=95=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94?= =?UTF-8?q?=EB=93=9C=20=EA=B5=AC=ED=98=84=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/FoodServiceTest.java | 47 ++++++++++++++----- 1 file changed, 34 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 e7dfba1..242d875 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -183,7 +183,7 @@ void testNutritionSumByWeekAndMonth(){ } @Test - void getTop3HighProteinLowFatFoodsTest() { + void getBest3FoodTest() { // given Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 1, 180, 80, 18)); foodService.saveFood(CreateFoodDto.of(userId, "Food1", BaseNutrition.createNutrition(100, 100 ,10, 1))); @@ -193,17 +193,38 @@ void getTop3HighProteinLowFatFoodsTest() { Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "Food5", BaseNutrition.createNutrition(100, 100 ,2, 5))); Food testFood = foodRepository.getReferenceById(foodId); -// -// // when -// ResponseNutritionSumByDateDto response = foodService.getNutritionSumByDate(userId, testFood.getDate()); -//// List top3Foods = response.getRankFoodList(); -//// -//// // then -//// assertEquals(3, top3Foods.size()); -//// assertEquals("Food1", top3Foods.get(0).getName()); -//// assertEquals("Food2", top3Foods.get(1).getName()); -//// assertEquals("Food3", top3Foods.get(2).getName()); -// assertNotNull(testFood.getName()); -// assertEquals("Food5", testFood.getDate()); + + // when + ResponseFoodRankDto response = foodService.getBestFoodByWeek(userId, testFood.getDate()); + List top3Foods = response.getRankFoodList(); + + // then + assertEquals(3, top3Foods.size()); + assertEquals("Food1", top3Foods.get(0).getName()); + assertEquals("Food2", top3Foods.get(1).getName()); + assertEquals("Food3", top3Foods.get(2).getName()); + } + + @Test + void getWorst3FoodsTest() { + // given + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 1, 180, 80, 18)); + foodService.saveFood(CreateFoodDto.of(userId, "Food1", BaseNutrition.createNutrition(100, 50 ,10, 1))); + foodService.saveFood(CreateFoodDto.of(userId, "Food2", BaseNutrition.createNutrition(100, 100 ,8, 20))); + foodService.saveFood(CreateFoodDto.of(userId, "Food3", BaseNutrition.createNutrition(100, 80 ,6, 7))); + foodService.saveFood(CreateFoodDto.of(userId, "Food4", BaseNutrition.createNutrition(100, 100 ,4, 5))); + Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "Food5", BaseNutrition.createNutrition(100, 90 ,2, 6))); + + Food testFood = foodRepository.getReferenceById(foodId); + + // when + ResponseFoodRankDto response = foodService.getWorstFoodByWeek(userId, testFood.getDate()); + List top3Foods = response.getRankFoodList(); + + // then + assertEquals(3, top3Foods.size()); + assertEquals("Food2", top3Foods.get(0).getName()); + assertEquals("Food4", top3Foods.get(1).getName()); + assertEquals("Food5", top3Foods.get(2).getName()); } } From f2ecba087ea37ca2d021882b7e260c3a218bf283 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 14:07:16 +0900 Subject: [PATCH 075/371] =?UTF-8?q?:pencil2:=20fix:=20Best3=20=EC=84=A0?= =?UTF-8?q?=EC=A0=95=20=EA=B8=B0=EC=A4=80=EC=97=90=EC=84=9C=20getProtein()?= =?UTF-8?q?=20->=20getFat()=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/food/service/FoodService.java | 2 +- 1 file changed, 1 insertion(+), 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 3222f7a..d8aca7f 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -126,7 +126,7 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId, LocalDate endDate) { List top3Foods = foodList.stream() .sorted(Comparator.comparingDouble((Food food) -> - 0.7 * food.getBaseNutrition().getProtein()- 0.3 * food.getBaseNutrition().getProtein()).reversed()) + 0.7 * food.getBaseNutrition().getProtein()- 0.3 * food.getBaseNutrition().getFat()).reversed()) .limit(3) .collect(Collectors.toList()); //고단백 저지방일수록 점수를 높게 측정되도록 기준을 잡은 후, 그 기준을 기반으로 정렬 //사용한 기준은, 고단백과 저지방의 점수 반영 비율을 7:3으로 측정하고, 단백질량이 높을 수록, 지방량이 낮을 수록 점수가 높음. 이후, 내림차순 정렬 From ea0adcb1f4e632e3bbff253419108230db3e49f8 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 14:19:11 +0900 Subject: [PATCH 076/371] =?UTF-8?q?:recycle:=20refactor:=20=EC=98=81?= =?UTF-8?q?=EC=96=91=EC=84=B1=EB=B6=84=20=EC=B4=9D=ED=95=A9=20Dto=20?= =?UTF-8?q?=EC=A4=91=20=EB=88=84=EB=9D=BD=EB=90=9C=20=EC=86=8D=EC=84=B1=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../food/dto/ResponseNutritionSumByDateDto.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java index 5eb8e4c..1520eb4 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java @@ -3,9 +3,16 @@ import lombok.AllArgsConstructor; import lombok.Getter; +import java.time.LocalDate; + @Getter @AllArgsConstructor public class ResponseNutritionSumByDateDto { + + Long userId; + LocalDate checkDate; //조회한 날짜 + int nutritionSumType; //조회할 기간을 나타내는 코드. {1: 특정 날짜, 7: 최근 7일간, 30: 최근 한달간} + int totalKcal; int totalCarbohydrate; int totalProtein; @@ -16,7 +23,7 @@ public class ResponseNutritionSumByDateDto { double ratioProtein; double ratioFat; - public static ResponseNutritionSumByDateDto of (int totalKcal, int totalCarbohydrate, int totalProtein, int totalFat, double ratioKcal, double ratioCarbohydrate, double ratioProtein, double ratioFat){ - return new ResponseNutritionSumByDateDto(totalKcal, totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); + public static ResponseNutritionSumByDateDto of (Long userId, LocalDate checkDate, int nutritionSumType, int totalKcal, int totalCarbohydrate, int totalProtein, int totalFat, double ratioKcal, double ratioCarbohydrate, double ratioProtein, double ratioFat){ + return new ResponseNutritionSumByDateDto(userId, checkDate, nutritionSumType, totalKcal, totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); } } From ce61bdd0dc12479c7fdaef137bd7c0755218a2df Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 14:23:19 +0900 Subject: [PATCH 077/371] =?UTF-8?q?:recycle:=20refactor:=20Dto=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=EC=97=90=20=EB=94=B0=EB=A5=B8=20=EC=98=81=EC=96=91?= =?UTF-8?q?=EC=84=B1=EB=B6=84=20=ED=95=A9=20=EC=A1=B0=ED=9A=8C=20=EC=BD=94?= =?UTF-8?q?=EB=93=9C=20=EC=88=98=EC=A0=95=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 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 d8aca7f..f7d5494 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -96,27 +96,25 @@ public void deleteFavoriteFood(Long favoriteFoodId) { // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { List foodList = foodRepository.findAllByUserIdAndDate(userId, date); - return calculateNutritionSumAndRatio(userId, foodList); + return calculateNutritionSumAndRatio(userId, foodList, date, 1); } @Transactional(readOnly = true) // 유저의 최근 7일간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { LocalDate endDate = LocalDate.now(); - LocalDate startDate = endDate.minusDays(6); - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, endDate); + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); - return calculateNutritionSumAndRatio(userId, foodList); + return calculateNutritionSumAndRatio(userId, foodList, endDate, 7); } @Transactional(readOnly = true) // 유저의 최근 1개월간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { LocalDate endDate = LocalDate.now(); - LocalDate startDate = endDate.minusMonths(1); - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, endDate); + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); - return calculateNutritionSumAndRatio(userId, foodList); + return calculateNutritionSumAndRatio(userId, foodList, endDate, 30); } @Transactional(readOnly = true) @@ -169,7 +167,7 @@ private FavoriteFood getFavoriteFoodById(Long foodId){ .orElseThrow(() -> new FoodException(ResponseCode.FOOD_NOT_FOUND)); } - private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, List foodList){ + private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, List foodList, LocalDate checkDate, int nutritionSumType){ User targetUser = getUserById(userId); int totalKcal = 0; int totalCarbohydrate = 0; @@ -189,7 +187,7 @@ private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, double ratioProtein = Math.round((((double) totalProtein /(double) targetUser.getBaseNutrition().getProtein())*100.0)*10.0)/10.0; double ratioFat =Math.round((((double) totalFat /(double) targetUser.getBaseNutrition().getFat())*100.0)*10.0)/10.0; - return ResponseNutritionSumByDateDto.of(totalKcal,totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); + return ResponseNutritionSumByDateDto.of(userId, checkDate, nutritionSumType, totalKcal,totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); } From dc44397477734c59e04fe44c36b84142b1f9fe6e Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 15:30:05 +0900 Subject: [PATCH 078/371] =?UTF-8?q?:recycle:=20refactor:=20ResponseFoodRan?= =?UTF-8?q?kDto=EC=97=90=EC=84=9C=20Food=20Domain=20->=20Dto=EB=A1=9C=20?= =?UTF-8?q?=EB=B3=80=EA=B2=BD=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/dto/ResponseFoodRankDto.java | 4 ++-- .../com/diareat/diareat/food/service/FoodService.java | 11 +++++++++-- 2 files changed, 11 insertions(+), 4 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 6f32f5f..03d74b8 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 f7d5494..2d7c637 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -130,7 +130,10 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId, LocalDate endDate) { //사용한 기준은, 고단백과 저지방의 점수 반영 비율을 7:3으로 측정하고, 단백질량이 높을 수록, 지방량이 낮을 수록 점수가 높음. 이후, 내림차순 정렬 // ** Best 3 기준 논의 필요 ** - return ResponseFoodRankDto.of(userId, top3Foods, endDate, true); + 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()); + + return ResponseFoodRankDto.of(userId, top3FoodsDtoList, endDate, true); } @Transactional(readOnly = true) @@ -149,7 +152,11 @@ public ResponseFoodRankDto getWorstFoodByWeek(Long userId, LocalDate endDate) { // ** 이점은 논의가 필요할 듯? ** // 우선 임시로 지방 비율을 높게 설정 - return ResponseFoodRankDto.of(userId, worst3Foods, endDate, false); + 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()); + + + return ResponseFoodRankDto.of(userId, worst3FoodDtoList, endDate, false); } private User getUserById(Long userId){ From d19b639765b89fe797d8b041640ce718470052be Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 15:31:29 +0900 Subject: [PATCH 079/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20Dto?= =?UTF-8?q?=EB=A1=9C=20=EC=88=98=EC=A0=95=EC=97=90=20=EB=94=B0=EB=A5=B8=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/service/FoodServiceTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 242d875..904899c 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -196,7 +196,7 @@ void getBest3FoodTest() { // when ResponseFoodRankDto response = foodService.getBestFoodByWeek(userId, testFood.getDate()); - List top3Foods = response.getRankFoodList(); + List top3Foods = response.getRankFoodList(); // then assertEquals(3, top3Foods.size()); @@ -219,7 +219,7 @@ void getWorst3FoodsTest() { // when ResponseFoodRankDto response = foodService.getWorstFoodByWeek(userId, testFood.getDate()); - List top3Foods = response.getRankFoodList(); + List top3Foods = response.getRankFoodList(); // then assertEquals(3, top3Foods.size()); From 9faba4c9f5b5dc45a2f77f67ced2b7a5a2f31c85 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 11 Oct 2023 15:33:07 +0900 Subject: [PATCH 080/371] =?UTF-8?q?:recycle:=20refactor:=20CreatedDate=20?= =?UTF-8?q?=EC=96=B4=EB=85=B8=ED=85=8C=EC=9D=B4=EC=85=98=20=EC=A0=9C?= =?UTF-8?q?=EA=B1=B0=20(#18)?= 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 | 1 - 1 file changed, 1 deletion(-) 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 490f4da..851c5e5 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -30,7 +30,6 @@ public class Food { @JoinColumn(name = "favorite_food_id") private FavoriteFood favoriteFood; - @CreatedDate private LocalDate date; private LocalTime time; From 925c4dc8cf21ccf2d8fed201c22a9536d9e8b318 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 13 Oct 2023 11:45:09 +0900 Subject: [PATCH 081/371] =?UTF-8?q?:safety=5Fvest:=20Feat:=20UserService?= =?UTF-8?q?=20=EC=9D=BC=EB=B6=80=20=EC=98=88=EC=99=B8=EC=B2=98=EB=A6=AC=20?= =?UTF-8?q?=EB=A1=9C=EC=A7=81=20=EC=B6=94=EA=B0=80=20(#22)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/repository/UserRepository.java | 1 + .../com/diareat/diareat/user/service/UserService.java | 10 +++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/user/repository/UserRepository.java b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java index 2c45f0a..743ec3a 100644 --- a/src/main/java/com/diareat/diareat/user/repository/UserRepository.java +++ b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java @@ -7,4 +7,5 @@ public interface UserRepository extends JpaRepository { List findAllByNameContaining(String name); // 회원이 팔로우를 위해 검색한 유저 목록 조회 + boolean existsByName(String name); // 회원가입 시 닉네임 중복 확인 } diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 2ce3bee..7d688bd 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -27,6 +27,8 @@ public class UserService { public Long saveUser(CreateUserDto createUserDto) { BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); // BaseNutrition baseNutrition = BaseNutrition.createNutrition(createUserDto.getGender(), createUserDto.getAge(), createUserDto.getHeight(), createUserDto.getWeight()); + if (userRepository.existsByName(createUserDto.getName())) + throw new UserException(ResponseCode.USER_ALREADY_EXIST); User user = User.createUser(createUserDto.getName(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); return userRepository.save(user).getId(); } @@ -89,6 +91,9 @@ public List searchUser(Long hostId, String name) { public void followUser(Long userId, Long followId) { validateUser(userId); validateUser(followId); + // 이미 팔로우 중인 경우 + if (followRepository.existsByFromUserAndToUser(userId, followId)) + throw new UserException(ResponseCode.FOLLOWED_ALREADY); followRepository.save(Follow.makeFollow(userId, followId)); } @@ -97,11 +102,14 @@ public void followUser(Long userId, Long followId) { public void unfollowUser(Long userId, Long unfollowId) { validateUser(userId); validateUser(unfollowId); + // 이미 팔로우 취소한 경우 + if (followRepository.existsByFromUserAndToUser(userId, unfollowId)) + throw new UserException(ResponseCode.UNFOLLOWED_ALREADY); followRepository.delete(Follow.makeFollow(userId, unfollowId)); } private void validateUser(Long userId) { - if(!userRepository.existsById(userId)) + if (!userRepository.existsById(userId)) throw new UserException(ResponseCode.USER_NOT_FOUND); } From ca23cafa4c80ca42f8993c71ff82e8f0c3422de8 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 13 Oct 2023 11:45:56 +0900 Subject: [PATCH 082/371] =?UTF-8?q?:heavy=5Fplus=5Fsign:=20Chore:=20Swagge?= =?UTF-8?q?r=20API=20=EC=9D=98=EC=A1=B4=EC=84=B1=20=EC=B6=94=EA=B0=80=20(#?= =?UTF-8?q?22)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 4 ++++ src/main/resources/application.properties | 3 +++ 2 files changed, 7 insertions(+) diff --git a/build.gradle b/build.gradle index c7c7a25..a33ed66 100644 --- a/build.gradle +++ b/build.gradle @@ -35,6 +35,10 @@ dependencies { annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.security:spring-security-test' + + // Swagger dependency + implementation 'io.springfox:springfox-boot-starter:3.0.0' + implementation 'io.springfox:springfox-swagger-ui:3.0.0' } tasks.named('test') { diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 3e18c96..61a7a3e 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,2 +1,5 @@ # db spring.profiles.include = db + +# swagger +spring.mvc.pathmatch.matching-strategy=ant_path_matcher \ No newline at end of file From 3591486d37ce96b004d5f7184d3296000b1c1a07 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 13 Oct 2023 11:53:41 +0900 Subject: [PATCH 083/371] =?UTF-8?q?:sparkles:=20Feat:=20UserController=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20=EB=B0=8F=20ResponseCode=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20(#22)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/controller/UserController.java | 84 ++++++++++++++++++- .../diareat/util/api/ResponseCode.java | 39 +++++++-- 2 files changed, 116 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/controller/UserController.java b/src/main/java/com/diareat/diareat/user/controller/UserController.java index d7be5f3..ce6c3f5 100644 --- a/src/main/java/com/diareat/diareat/user/controller/UserController.java +++ b/src/main/java/com/diareat/diareat/user/controller/UserController.java @@ -1,9 +1,91 @@ package com.diareat.diareat.user.controller; +import com.diareat.diareat.user.dto.*; +import com.diareat.diareat.user.service.UserService; +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.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.RestController; +import net.bytebuddy.implementation.bind.annotation.Empty; +import org.springframework.web.bind.annotation.*; +import java.util.List; + +@Api(tags = "1. User") @RequiredArgsConstructor @RestController +@RequestMapping("/api/user") public class UserController { + + private final UserService userService; + + // 회원정보 저장 + @Operation(summary = "[회원가입] 회원정보 저장", description = "신규 회원정보를 저장합니다.") + @PostMapping("/save") + public ApiResponse saveUser(CreateUserDto createUserDto) { + return ApiResponse.success(userService.saveUser(createUserDto), ResponseCode.USER_CREATE_SUCCESS.getMessage()); + } + + // 회원 기본정보 조회 + @Operation(summary = "[프로필] 회원 기본정보 조회", description = "회원 기본정보를 조회합니다.") + @GetMapping("{userId}/info/simple/") + public ApiResponse getSimpleUserInfo(@PathVariable Long userId) { + return ApiResponse.success(userService.getSimpleUserInfo(userId), ResponseCode.USER_CREATE_SUCCESS.getMessage()); + } + + // 회원정보 조회 + @Operation(summary = "[프로필] 회원 정보 조회", description = "회원 정보를 조회합니다.") + @GetMapping("{userId}/info") + public ApiResponse getUserInfo(@PathVariable Long userId) { + return ApiResponse.success(userService.getUserInfo(userId), ResponseCode.USER_CREATE_SUCCESS.getMessage()); + } + + // 회원정보 수정 + @Operation(summary = "[프로필] 회원 정보 수정", description = "회원 정보를 수정합니다.") + @PutMapping("/update") + public ApiResponse updateUserInfo(UpdateUserDto updateUserDto) { + userService.updateUserInfo(updateUserDto); + return ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); + } + + // 회원 기준섭취량 조회 + @Operation(summary = "[프로필] 회원 기준섭취량 조회", description = "회원 기준섭취량을 조회합니다.") + @GetMapping("{userId}/nutrition") + public ApiResponse getUserNutrition(@PathVariable Long userId) { + return ApiResponse.success(userService.getUserNutrition(userId), ResponseCode.USER_READ_SUCCESS.getMessage()); + } + + // 회원 기준섭취량 직접 수정 + @Operation(summary = "[프로필] 회원 기준섭취량 직접 수정", description = "회원 기준섭취량을 직접 수정합니다.") + @PutMapping("{userId}/nutrition") + public ApiResponse updateUserNutrition(UpdateUserNutritionDto updateUserNutritionDto) { + userService.updateBaseNutrition(updateUserNutritionDto); + return ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); + } + + // 회원의 친구 검색 결과 조회 + @Operation(summary = "[주간 랭킹] 회원의 친구 검색 결과 조회", description = "회원의 친구 검색 결과를 조회합니다.") + @GetMapping("{userId}/search/{name}") + public ApiResponse> searchUser(@PathVariable Long userId, @RequestParam String name) { + return ApiResponse.success(userService.searchUser(userId, name), ResponseCode.USER_SEARCH_SUCCESS.getMessage()); + } + + // 실제 팔로잉 유저들의 점수 계산하여 랭킹 형태로 반환하는 API: FoodService에서 계산할지 UserService에서 FoodRepository를 콜해서 처리할지 협의 필요 + + // 회원이 특정 회원 팔로우 + @Operation(summary = "[주간 랭킹] 회원이 특정 회원 팔로우", description = "회원이 특정 회원을 팔로우합니다.") + @PostMapping("{userId}/follow/{followId}") + public ApiResponse followUser(@PathVariable Long userId, @PathVariable Long followId) { + userService.followUser(userId, followId); + return ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); + } + + // 회원이 특정 회원 팔로우 취소 + @Operation(summary = "[주간 랭킹] 회원이 특정 회원 팔로우 취소", description = "회원이 특정 회원을 팔로우 취소합니다.") + @DeleteMapping("{userId}/follow/{followId}") + public ApiResponse unfollowUser(@PathVariable Long userId, @PathVariable Long followId) { + userService.unfollowUser(userId, followId); + return ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); + } } 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 450a24a..0f1574b 100644 --- a/src/main/java/com/diareat/diareat/util/api/ResponseCode.java +++ b/src/main/java/com/diareat/diareat/util/api/ResponseCode.java @@ -16,15 +16,42 @@ public enum ResponseCode { FORBIDDEN(HttpStatus.FORBIDDEN, false, "권한이 없습니다."), // 404 Not Found - USER_NOT_FOUND(HttpStatus.NOT_FOUND, false,"사용자를 찾을 수 없습니다."), - FOOD_NOT_FOUND(HttpStatus.NOT_FOUND, false,"음식을 찾을 수 없습니다."), - FAVORITE_NOT_FOUND(HttpStatus.NOT_FOUND, false,"즐겨찾기를 찾을 수 없습니다."), + USER_NOT_FOUND(HttpStatus.NOT_FOUND, false, "사용자를 찾을 수 없습니다."), + FOOD_NOT_FOUND(HttpStatus.NOT_FOUND, false, "음식을 찾을 수 없습니다."), + FAVORITE_NOT_FOUND(HttpStatus.NOT_FOUND, false, "즐겨찾기를 찾을 수 없습니다."), // 405 Method Not Allowed - METHOD_NOT_ALLOWED(HttpStatus.METHOD_NOT_ALLOWED, false,"허용되지 않은 메소드입니다."), + METHOD_NOT_ALLOWED(HttpStatus.METHOD_NOT_ALLOWED, false, "허용되지 않은 메소드입니다."), + + // 409 Conflict + USER_ALREADY_EXIST(HttpStatus.CONFLICT, false, "이미 존재하는 닉네임입니다."), + FOLLOWED_ALREADY(HttpStatus.CONFLICT, false, "이미 팔로우한 사용자입니다."), + UNFOLLOWED_ALREADY(HttpStatus.CONFLICT, false, "이미 언팔로우한 사용자입니다."), + FOOD_ALREADY_EXIST(HttpStatus.CONFLICT, false, "이미 즐겨찾기에 존재하는 음식입니다."), // 500 Internal Server Error - INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, false,"서버에 오류가 발생하였습니다."); + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, false, "서버에 오류가 발생하였습니다."), + + // 200 OK + USER_READ_SUCCESS(HttpStatus.CREATED, true, "사용자 정보 조회 성공"), + USER_UPDATE_SUCCESS(HttpStatus.OK, true, "사용자 정보 수정 성공"), + USER_SEARCH_SUCCESS(HttpStatus.OK, true, "사용자 검색 성공"), + USER_FOLLOW_SUCCESS(HttpStatus.OK, true, "사용자 팔로우 성공"), + USER_UNFOLLOW_SUCCESS(HttpStatus.OK, true, "사용자 언팔로우 성공"), + + FOOD_READ_SUCCESS(HttpStatus.OK, true, "음식 정보 조회 성공"), + FOOD_UPDATE_SUCCESS(HttpStatus.OK, true, "음식 정보 수정 성공"), + FOOD_DELETE_SUCCESS(HttpStatus.OK, true, "음식 정보 삭제 성공"), + FOOD_FAVORITE_READ_SUCCESS(HttpStatus.OK, true, "즐겨찾기 음식 조회 성공"), + FOOD_FAVORITE_UPDATE_SUCCESS(HttpStatus.OK, true, "즐겨찾기 음식 수정 성공"), + FOOD_FAVORITE_DELETE_SUCCESS(HttpStatus.OK, true, "즐겨찾기 음식 삭제 성공"), + + + // 201 Created + USER_CREATE_SUCCESS(HttpStatus.CREATED, true, "사용자 생성 성공"), + FOOD_CREATE_SUCCESS(HttpStatus.CREATED, true, "음식 생성 성공"), + FOOD_FAVORITE_CREATE_SUCCESS(HttpStatus.OK, true, "즐겨찾기 음식 생성 성공"); + private final HttpStatus httpStatus; private final Boolean success; @@ -33,4 +60,4 @@ public enum ResponseCode { public int getHttpStatusCode() { return httpStatus.value(); } - } +} From 6109866d1d8f30aa23bbef054ca2be9651665330 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 13 Oct 2023 12:00:45 +0900 Subject: [PATCH 084/371] =?UTF-8?q?:sparkles:=20Feat:=20UserService=20?= =?UTF-8?q?=ED=8C=94=EB=A1=9C=EC=9A=B0=EB=AA=A9=EB=A1=9D=20=EC=A1=B0?= =?UTF-8?q?=ED=9A=8C=20=EA=B8=B0=EB=8A=A5=20=EC=B6=94=EA=B0=80=20(#22)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/user/service/UserService.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 7d688bd..fe49358 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -108,6 +108,15 @@ public void unfollowUser(Long userId, Long unfollowId) { followRepository.delete(Follow.makeFollow(userId, unfollowId)); } + // 회원의 팔로우 목록 조회 (현재 외부 Dto 변환은 Food에서 위임받아 진행할지 협의하지 않았기에 일단 User 리스트로 반환) + @Transactional(readOnly = true) + public List getFollowList(Long userId) { + validateUser(userId); + List users = followRepository.findAllByFromUser(userId); + users.add(getUserById(userId)); // 자기 자신도 랭킹에 포함 + return users; + } + private void validateUser(Long userId) { if (!userRepository.existsById(userId)) throw new UserException(ResponseCode.USER_NOT_FOUND); From 8df6c4368fb2aa812542ae0dfe58596c5381e36a Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Fri, 13 Oct 2023 15:12:16 +0900 Subject: [PATCH 085/371] =?UTF-8?q?:sparkles:=20feat:=20FoodController=20?= =?UTF-8?q?=ED=95=A8=EC=88=98=20=ED=94=84=EB=A1=9C=ED=86=A0=ED=83=80?= =?UTF-8?q?=EC=9E=85=20=EC=A0=95=EC=9D=98=20(#24)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../food/controller/FoodController.java | 84 ++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) 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 06feadc..bb54ce5 100644 --- a/src/main/java/com/diareat/diareat/food/controller/FoodController.java +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -1,9 +1,91 @@ package com.diareat.diareat.food.controller; +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.service.UserService; +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.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.RestController; +import net.bytebuddy.asm.Advice; +import org.springframework.security.core.parameters.P; +import org.springframework.web.bind.annotation.*; +import java.time.LocalDate; +import java.util.List; + +@Api(tags = "2. food") @RequiredArgsConstructor @RestController +@RequestMapping("api/food") public class FoodController { + + private final FoodService foodService; + + //음식 정보 저장 + @Operation(summary = "[음식] 음식 정보 저장", description = "촬영한 음식 정보를 저장합니다.") + @PostMapping("/save") + public ApiResponse saveFood(CreateFoodDto createFoodDto){} + + //특정 날짜에 먹은 음식 반환 + @Operation(summary = "[음식] 특정 날짜에 먹은 음식 목록 조회",description = "유저의 특정 날짜에 먹은 음식 목록을 조회합니다.") + @GetMapping("{userId}/{date}") + public ApiResponse> getFoodListByDate(@PathVariable Long userId, @RequestParam LocalDate date){} + + //음식 정보 수정 + @Operation(summary = "[음식] 음식 정보 수정",description = "음식에 대한 정보를 수정합니다.") + @PostMapping("/update") + public ApiResponse updateFood(UpdateFoodDto updateFoodDto){} + //음식 삭제 + @Operation(summary = "[음식] 음식 정보 삭제",description = "음식에 대한 정보를 삭제합니다.") + @DeleteMapping("{foodId}/delete") + public ApiResponse deleteFood(Long foodId){} + + //즐겨찾기에 음식 저장 + @Operation(summary = "[즐겨찾기] 즐겨찾기에 저장",description = "유저의 즐겨찾기에 음식을 저장합니다.") + @PostMapping("/favorite") + public ApiResponse saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto){} + + //즐겨찾기 음식 리스트 반환 + @Operation(summary = "[즐겨찾기] 즐겨찾기 목록 조회",description = "유저의 즐겨찾기에 등록된 음식 목록을 조회합니다.") + @GetMapping("/favorite/{userId}") + public ApiResponse> getFavoriteFoodList(@PathVariable Long userId){} + + //즐겨찾기 음식 수정 + @Operation(summary = "[즐겨찾기] 즐겨찾기 수정",description = "유저의 즐겨찾기에 등록된 음식의 정보를 수정합니다.") + @PostMapping("/favorite/update") + public ApiResponse updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto){} + + //즐겨찾기 음식 해제 + @Operation(summary = "[즐겨찾기] 즐겨찾기 해제",description = "유저의 즐겨찾기에 등록된 음식을 해제합니다.") + @DeleteMapping("/favorite/{favoriteFoodId}") + public ApiResponse deleteFavoriteFood(@PathVariable Long favoriteFoodId){} + + //특정 날짜에 먹은 음식들의 영양성분별 총합 조회 + @Operation(summary = "[음식] 특정 날짜에 먹은 음식들의 영양성분 총합 조회",description = "특정 날짜에 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") + @GetMapping("{userId}/nutrition/{date}") + public ApiResponse getNutritionSumByDate(@PathVariable Long userId, @RequestParam LocalDate date){} + + //"" 7일간 총합 조회 + @Operation(summary = "[음식] 최근 7일간 먹은 음식들의 영양성분 총합 조회",description = "최근 7일 간 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") + @GetMapping("{userId}/nutrition/recentWeek") + public ApiResponse getNutritionSumByWeek(@PathVariable Long userId){} + + //"" 30일간 (1달간) 총합 조회 + @Operation(summary = "[음식] 최근 한달 간 먹은 음식들의 영양성분 총합 조회",description = "최근 한달 간 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") + @GetMapping("{userId}/nutrition/recentMonth") + public ApiResponse getNutritionSumByMonth(@PathVariable Long userId){} + + //7일간의 Best 3 조회 + @Operation(summary = "[음식] 최근 7일 간 먹은 Top3 음식 조회",description = "최근 7일 간 유저가 먹은 음식들 중에서 Top3에 해당한 음식들을 조회합니다.") + @GetMapping("{userId}/best") + public ApiResponse getBestFoodByWeek(@PathVariable Long userId){} + + //7일간의 Worst 3 조회 + @Operation(summary = "[음식] 최근 7일 간 먹은 Worst3 음식 조회",description = "최근 7일 간 유저가 먹은 음식들 중에서 Worst3에 해당한 음식들을 조회합니다.") + @GetMapping("{userId}/worst") + public ApiResponse getWorstFoodByWeek(@PathVariable Long userId){} + } From de98e552a9dddd6ddddbe18d7e879a8312d072f4 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Fri, 13 Oct 2023 15:29:28 +0900 Subject: [PATCH 086/371] =?UTF-8?q?:sparkles:=20feat:=20FoodController=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20(#24)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../food/controller/FoodController.java | 74 ++++++++++++++----- .../diareat/food/service/FoodService.java | 7 +- .../diareat/service/FoodServiceTest.java | 10 +-- 3 files changed, 63 insertions(+), 28 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 bb54ce5..ebb0435 100644 --- a/src/main/java/com/diareat/diareat/food/controller/FoodController.java +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -1,16 +1,12 @@ package com.diareat.diareat.food.controller; -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.service.UserService; 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.RequiredArgsConstructor; -import net.bytebuddy.asm.Advice; -import org.springframework.security.core.parameters.P; import org.springframework.web.bind.annotation.*; import java.time.LocalDate; @@ -27,65 +23,105 @@ public class FoodController { //음식 정보 저장 @Operation(summary = "[음식] 음식 정보 저장", description = "촬영한 음식 정보를 저장합니다.") @PostMapping("/save") - public ApiResponse saveFood(CreateFoodDto createFoodDto){} + public ApiResponse saveFood(CreateFoodDto createFoodDto){ + return ApiResponse.success(foodService.saveFood(createFoodDto),ResponseCode.FOOD_CREATE_SUCCESS.getMessage()); + } //특정 날짜에 먹은 음식 반환 @Operation(summary = "[음식] 특정 날짜에 먹은 음식 목록 조회",description = "유저의 특정 날짜에 먹은 음식 목록을 조회합니다.") - @GetMapping("{userId}/{date}") - public ApiResponse> getFoodListByDate(@PathVariable Long userId, @RequestParam LocalDate date){} + @GetMapping("{userId}") + public ApiResponse> getFoodListByDate(@PathVariable Long userId, + @RequestParam int yy, + @RequestParam int mm, + @RequestParam int dd) + { + LocalDate date = LocalDate.of(yy,mm,dd); + return ApiResponse.success(foodService.getFoodListByDate(userId,date),ResponseCode.FOOD_READ_SUCCESS.getMessage()); + } //음식 정보 수정 @Operation(summary = "[음식] 음식 정보 수정",description = "음식에 대한 정보를 수정합니다.") @PostMapping("/update") - public ApiResponse updateFood(UpdateFoodDto updateFoodDto){} + public ApiResponse updateFood(UpdateFoodDto updateFoodDto){ + foodService.updateFood(updateFoodDto); + return ApiResponse.success(null,ResponseCode.FOOD_UPDATE_SUCCESS.getMessage()); + } //음식 삭제 @Operation(summary = "[음식] 음식 정보 삭제",description = "음식에 대한 정보를 삭제합니다.") @DeleteMapping("{foodId}/delete") - public ApiResponse deleteFood(Long foodId){} + public ApiResponse deleteFood(@PathVariable Long foodId){ + foodService.deleteFood(foodId); + return ApiResponse.success(null, ResponseCode.FOOD_DELETE_SUCCESS.getMessage()); + } //즐겨찾기에 음식 저장 @Operation(summary = "[즐겨찾기] 즐겨찾기에 저장",description = "유저의 즐겨찾기에 음식을 저장합니다.") @PostMapping("/favorite") - public ApiResponse saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto){} + public ApiResponse saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto){ + return ApiResponse.success(foodService.saveFavoriteFood(createFavoriteFoodDto),ResponseCode.FOOD_FAVORITE_CREATE_SUCCESS.getMessage()); + } //즐겨찾기 음식 리스트 반환 @Operation(summary = "[즐겨찾기] 즐겨찾기 목록 조회",description = "유저의 즐겨찾기에 등록된 음식 목록을 조회합니다.") @GetMapping("/favorite/{userId}") - public ApiResponse> getFavoriteFoodList(@PathVariable Long userId){} + public ApiResponse> getFavoriteFoodList(@PathVariable Long userId){ + return ApiResponse.success(foodService.getFavoriteFoodList(userId), ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); + } //즐겨찾기 음식 수정 @Operation(summary = "[즐겨찾기] 즐겨찾기 수정",description = "유저의 즐겨찾기에 등록된 음식의 정보를 수정합니다.") @PostMapping("/favorite/update") - public ApiResponse updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto){} + public ApiResponse updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto){ + foodService.updateFavoriteFood(updateFavoriteFoodDto); + return ApiResponse.success(null, ResponseCode.FOOD_FAVORITE_UPDATE_SUCCESS.getMessage()); + } //즐겨찾기 음식 해제 @Operation(summary = "[즐겨찾기] 즐겨찾기 해제",description = "유저의 즐겨찾기에 등록된 음식을 해제합니다.") @DeleteMapping("/favorite/{favoriteFoodId}") - public ApiResponse deleteFavoriteFood(@PathVariable Long favoriteFoodId){} + public ApiResponse deleteFavoriteFood(@PathVariable Long favoriteFoodId){ + foodService.deleteFavoriteFood(favoriteFoodId); + return ApiResponse.success(null, ResponseCode.FOOD_FAVORITE_DELETE_SUCCESS.getMessage()); + } //특정 날짜에 먹은 음식들의 영양성분별 총합 조회 @Operation(summary = "[음식] 특정 날짜에 먹은 음식들의 영양성분 총합 조회",description = "특정 날짜에 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") - @GetMapping("{userId}/nutrition/{date}") - public ApiResponse getNutritionSumByDate(@PathVariable Long userId, @RequestParam LocalDate date){} + @GetMapping("{userId}/nutrition") + public ApiResponse getNutritionSumByDate(@PathVariable Long userId, + @RequestParam int yy, + @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()); + } //"" 7일간 총합 조회 @Operation(summary = "[음식] 최근 7일간 먹은 음식들의 영양성분 총합 조회",description = "최근 7일 간 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") @GetMapping("{userId}/nutrition/recentWeek") - public ApiResponse getNutritionSumByWeek(@PathVariable Long userId){} + public ApiResponse getNutritionSumByWeek(@PathVariable Long userId){ + return ApiResponse.success(foodService.getNutritionSumByWeek(userId),ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); + } //"" 30일간 (1달간) 총합 조회 @Operation(summary = "[음식] 최근 한달 간 먹은 음식들의 영양성분 총합 조회",description = "최근 한달 간 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") @GetMapping("{userId}/nutrition/recentMonth") - public ApiResponse getNutritionSumByMonth(@PathVariable Long userId){} + public ApiResponse getNutritionSumByMonth(@PathVariable Long userId){ + return ApiResponse.success(foodService.getNutritionSumByMonth(userId),ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); + + } //7일간의 Best 3 조회 @Operation(summary = "[음식] 최근 7일 간 먹은 Top3 음식 조회",description = "최근 7일 간 유저가 먹은 음식들 중에서 Top3에 해당한 음식들을 조회합니다.") @GetMapping("{userId}/best") - public ApiResponse getBestFoodByWeek(@PathVariable Long userId){} + 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){} + public ApiResponse getWorstFoodByWeek(@PathVariable Long userId){ + return ApiResponse.success(foodService.getWorstFoodByWeek(userId),ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); + } } 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 2d7c637..f339d56 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -119,7 +119,8 @@ public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { @Transactional(readOnly = true) // 유저의 최근 7일간의 Best 3 음식 조회 (dto 구체적 협의 필요) - public ResponseFoodRankDto getBestFoodByWeek(Long userId, LocalDate endDate) { + public ResponseFoodRankDto getBestFoodByWeek(Long userId) { + LocalDate endDate = LocalDate.now(); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); List top3Foods = foodList.stream() @@ -138,8 +139,8 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId, LocalDate endDate) { @Transactional(readOnly = true) // 유저의 최근 7일간의 Worst 3 음식 조회 (dto 구체적 협의 필요) - public ResponseFoodRankDto getWorstFoodByWeek(Long userId, LocalDate endDate) { - + public ResponseFoodRankDto getWorstFoodByWeek(Long userId) { + LocalDate endDate = LocalDate.now(); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); List worst3Foods = foodList.stream() diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 904899c..c598aab 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -190,12 +190,11 @@ void getBest3FoodTest() { foodService.saveFood(CreateFoodDto.of(userId, "Food2", BaseNutrition.createNutrition(100, 100 ,8, 2))); foodService.saveFood(CreateFoodDto.of(userId, "Food3", BaseNutrition.createNutrition(100, 100 ,6, 3))); foodService.saveFood(CreateFoodDto.of(userId, "Food4", BaseNutrition.createNutrition(100, 100 ,4, 4))); - Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "Food5", BaseNutrition.createNutrition(100, 100 ,2, 5))); + foodService.saveFood(CreateFoodDto.of(userId, "Food5", BaseNutrition.createNutrition(100, 100 ,2, 5))); - Food testFood = foodRepository.getReferenceById(foodId); // when - ResponseFoodRankDto response = foodService.getBestFoodByWeek(userId, testFood.getDate()); + ResponseFoodRankDto response = foodService.getBestFoodByWeek(userId); List top3Foods = response.getRankFoodList(); // then @@ -213,12 +212,11 @@ void getWorst3FoodsTest() { foodService.saveFood(CreateFoodDto.of(userId, "Food2", BaseNutrition.createNutrition(100, 100 ,8, 20))); foodService.saveFood(CreateFoodDto.of(userId, "Food3", BaseNutrition.createNutrition(100, 80 ,6, 7))); foodService.saveFood(CreateFoodDto.of(userId, "Food4", BaseNutrition.createNutrition(100, 100 ,4, 5))); - Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "Food5", BaseNutrition.createNutrition(100, 90 ,2, 6))); + foodService.saveFood(CreateFoodDto.of(userId, "Food5", BaseNutrition.createNutrition(100, 90 ,2, 6))); - Food testFood = foodRepository.getReferenceById(foodId); // when - ResponseFoodRankDto response = foodService.getWorstFoodByWeek(userId, testFood.getDate()); + ResponseFoodRankDto response = foodService.getWorstFoodByWeek(userId); List top3Foods = response.getRankFoodList(); // then From 1a9786bae70213740c81794356d2ef63973f5621 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Fri, 13 Oct 2023 15:34:56 +0900 Subject: [PATCH 087/371] =?UTF-8?q?:pencil2:=20fix:=20=EC=98=A4=ED=83=88?= =?UTF-8?q?=EC=9E=90=20=EC=88=98=EC=A0=95=20(#24)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/controller/FoodController.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 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 ebb0435..293eb3e 100644 --- a/src/main/java/com/diareat/diareat/food/controller/FoodController.java +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -29,7 +29,7 @@ public ApiResponse saveFood(CreateFoodDto createFoodDto){ //특정 날짜에 먹은 음식 반환 @Operation(summary = "[음식] 특정 날짜에 먹은 음식 목록 조회",description = "유저의 특정 날짜에 먹은 음식 목록을 조회합니다.") - @GetMapping("{userId}") + @GetMapping("/{userId}") public ApiResponse> getFoodListByDate(@PathVariable Long userId, @RequestParam int yy, @RequestParam int mm, @@ -48,7 +48,7 @@ public ApiResponse updateFood(UpdateFoodDto updateFoodDto){ } //음식 삭제 @Operation(summary = "[음식] 음식 정보 삭제",description = "음식에 대한 정보를 삭제합니다.") - @DeleteMapping("{foodId}/delete") + @DeleteMapping("/{foodId}/delete") public ApiResponse deleteFood(@PathVariable Long foodId){ foodService.deleteFood(foodId); return ApiResponse.success(null, ResponseCode.FOOD_DELETE_SUCCESS.getMessage()); @@ -86,7 +86,7 @@ public ApiResponse deleteFavoriteFood(@PathVariable Long favoriteFoodId){ //특정 날짜에 먹은 음식들의 영양성분별 총합 조회 @Operation(summary = "[음식] 특정 날짜에 먹은 음식들의 영양성분 총합 조회",description = "특정 날짜에 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") - @GetMapping("{userId}/nutrition") + @GetMapping("/{userId}/nutrition") public ApiResponse getNutritionSumByDate(@PathVariable Long userId, @RequestParam int yy, @RequestParam int mm, @@ -97,14 +97,14 @@ public ApiResponse getNutritionSumByDate(@PathVar //"" 7일간 총합 조회 @Operation(summary = "[음식] 최근 7일간 먹은 음식들의 영양성분 총합 조회",description = "최근 7일 간 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") - @GetMapping("{userId}/nutrition/recentWeek") + @GetMapping("/{userId}/nutrition/recentWeek") public ApiResponse getNutritionSumByWeek(@PathVariable Long userId){ return ApiResponse.success(foodService.getNutritionSumByWeek(userId),ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); } //"" 30일간 (1달간) 총합 조회 @Operation(summary = "[음식] 최근 한달 간 먹은 음식들의 영양성분 총합 조회",description = "최근 한달 간 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") - @GetMapping("{userId}/nutrition/recentMonth") + @GetMapping("/{userId}/nutrition/recentMonth") public ApiResponse getNutritionSumByMonth(@PathVariable Long userId){ return ApiResponse.success(foodService.getNutritionSumByMonth(userId),ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); @@ -112,14 +112,14 @@ public ApiResponse getNutritionSumByMonth(@PathVa //7일간의 Best 3 조회 @Operation(summary = "[음식] 최근 7일 간 먹은 Top3 음식 조회",description = "최근 7일 간 유저가 먹은 음식들 중에서 Top3에 해당한 음식들을 조회합니다.") - @GetMapping("{userId}/best") + @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") + @GetMapping("/{userId}/worst") public ApiResponse getWorstFoodByWeek(@PathVariable Long userId){ return ApiResponse.success(foodService.getWorstFoodByWeek(userId),ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); } From 7595a46f734b0af3cac9fc33e15dc45ef7e6045c Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 13 Oct 2023 15:46:59 +0900 Subject: [PATCH 088/371] =?UTF-8?q?:green=5Fheart:=20fix:=20=EC=BB=A8?= =?UTF-8?q?=ED=85=8C=EC=9D=B4=EB=84=88=20=ED=8F=AC=ED=8A=B8=20=ED=8F=AC?= =?UTF-8?q?=EC=9B=8C=EB=94=A9=20=EC=84=A4=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/Diareat-CICD.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Diareat-CICD.yml b/.github/workflows/Diareat-CICD.yml index 4102a13..fb1be37 100644 --- a/.github/workflows/Diareat-CICD.yml +++ b/.github/workflows/Diareat-CICD.yml @@ -65,6 +65,6 @@ jobs: echo "DB_PASSWORD=${{ secrets.DB_PASSWORD }}" >> env.list - sudo docker run -d --env-file env.list --name Diareat_Backend ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest + sudo docker run -d -p 22:22/tcp --env-file env.list --name Diareat_Backend ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest sleep 10s sudo docker ps | grep ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest From 96318df1f0af72575171273731fdf28dccb3ded2 Mon Sep 17 00:00:00 2001 From: CHAE Date: Sat, 14 Oct 2023 11:33:43 +0900 Subject: [PATCH 089/371] =?UTF-8?q?:bug:=20Fix:=20User=20image=20=EC=86=8D?= =?UTF-8?q?=EC=84=B1=20=EB=88=84=EB=9D=BD=20=EC=88=98=EC=A0=95=20(#26)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/user/domain/User.java | 3 ++- .../diareat/user/dto/CreateUserDto.java | 5 +++-- .../diareat/user/service/UserService.java | 5 +++-- .../diareat/service/FoodServiceTest.java | 20 +++++++++---------- 4 files changed, 18 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index 2f0d619..47d470e 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -44,9 +44,10 @@ public class User { private List favoriteFoods = new ArrayList<>(); // 생성 메서드 - public static User createUser(String name, String keyCode, int height, int weight, int gender, int age, BaseNutrition baseNutrition) { + public static User createUser(String name, String image, String keyCode, int height, int weight, int gender, int age, BaseNutrition baseNutrition) { User user = new User(); user.name = name; + user.image = image; user.keyCode = keyCode; user.height = height; user.weight = weight; diff --git a/src/main/java/com/diareat/diareat/user/dto/CreateUserDto.java b/src/main/java/com/diareat/diareat/user/dto/CreateUserDto.java index 481bef4..5c463ef 100644 --- a/src/main/java/com/diareat/diareat/user/dto/CreateUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/CreateUserDto.java @@ -10,13 +10,14 @@ public class CreateUserDto { private String name; + private String image; private String keyCode; private int gender; private int height; private int weight; private int age; - public static CreateUserDto of(String name, String keyCode, int gender, int height, int weight, int age){ - return new CreateUserDto(name, keyCode, gender, height, weight, age); + public static CreateUserDto of(String name, String image, String keyCode, int gender, int height, int weight, int age){ + return new CreateUserDto(name, image, keyCode, gender, height, weight, age); } } diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index fe49358..caf312a 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -29,7 +29,7 @@ public Long saveUser(CreateUserDto createUserDto) { // BaseNutrition baseNutrition = BaseNutrition.createNutrition(createUserDto.getGender(), createUserDto.getAge(), createUserDto.getHeight(), createUserDto.getWeight()); if (userRepository.existsByName(createUserDto.getName())) throw new UserException(ResponseCode.USER_ALREADY_EXIST); - User user = User.createUser(createUserDto.getName(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); + User user = User.createUser(createUserDto.getName(), createUserDto.getImage(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); return userRepository.save(user).getId(); } @@ -68,6 +68,7 @@ public void updateBaseNutrition(UpdateUserNutritionDto updateUserNutritionDto) { User user = getUserById(updateUserNutritionDto.getUserId()); BaseNutrition baseNutrition = BaseNutrition.createNutrition(updateUserNutritionDto.getCalorie(), updateUserNutritionDto.getCarbohydrate(), updateUserNutritionDto.getProtein(), updateUserNutritionDto.getFat()); user.updateBaseNutrition(baseNutrition); + userRepository.save(user); } // 회원 탈퇴 @@ -103,7 +104,7 @@ public void unfollowUser(Long userId, Long unfollowId) { validateUser(userId); validateUser(unfollowId); // 이미 팔로우 취소한 경우 - if (followRepository.existsByFromUserAndToUser(userId, unfollowId)) + if (!followRepository.existsByFromUserAndToUser(userId, unfollowId)) throw new UserException(ResponseCode.UNFOLLOWED_ALREADY); followRepository.delete(Follow.makeFollow(userId, unfollowId)); } diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 904899c..759ecbb 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -53,7 +53,7 @@ public void setUp() { void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리스트 불러오기 // given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 1,180, 80,18)); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword", 1,180, 80,18)); //when Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood",testBaseNutrition)); @@ -69,7 +69,7 @@ void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리 void testUpdateFood() { //given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "tessPassword", 1, 180, 80, 18)); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); //when @@ -90,7 +90,7 @@ void testUpdateFood() { void testDeleteFood() { //given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "tessPassword", 1, 180, 80, 18)); + Long userId = userService.saveUser(CreateUserDto.of("testUser","testImage", "tessPassword", 1, 180, 80, 18)); Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); //when @@ -103,7 +103,7 @@ void testDeleteFood() { void testSaveAndGetFavoriteFood() { //given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "tessPassword", 1, 180, 80, 18)); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); //when @@ -119,7 +119,7 @@ void testSaveAndGetFavoriteFood() { void testUpdateFavoriteFood() { //given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "tessPassword", 1, 180, 80, 18)); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); @@ -142,7 +142,7 @@ void testUpdateFavoriteFood() { void testDeleteFavoriteFood() { //given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "tessPassword", 1, 180, 80, 18)); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); @@ -156,7 +156,7 @@ void testDeleteFavoriteFood() { void testNutritionSumByDate(){ //given BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword",1, 180, 80, 18)); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword",1, 180, 80, 18)); Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood", testFoodNutrition)); Food food = foodRepository.getReferenceById(foodId); @@ -177,7 +177,7 @@ void testNutritionSumByDate(){ void testNutritionSumByWeekAndMonth(){ //given BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(100,150,200,250); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword",1, 180, 80, 18)); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword",1, 180, 80, 18)); Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood", testFoodNutrition)); } @@ -185,7 +185,7 @@ void testNutritionSumByWeekAndMonth(){ @Test void getBest3FoodTest() { // given - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 1, 180, 80, 18)); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword", 1, 180, 80, 18)); foodService.saveFood(CreateFoodDto.of(userId, "Food1", BaseNutrition.createNutrition(100, 100 ,10, 1))); foodService.saveFood(CreateFoodDto.of(userId, "Food2", BaseNutrition.createNutrition(100, 100 ,8, 2))); foodService.saveFood(CreateFoodDto.of(userId, "Food3", BaseNutrition.createNutrition(100, 100 ,6, 3))); @@ -208,7 +208,7 @@ void getBest3FoodTest() { @Test void getWorst3FoodsTest() { // given - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 1, 180, 80, 18)); + Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword", 1, 180, 80, 18)); foodService.saveFood(CreateFoodDto.of(userId, "Food1", BaseNutrition.createNutrition(100, 50 ,10, 1))); foodService.saveFood(CreateFoodDto.of(userId, "Food2", BaseNutrition.createNutrition(100, 100 ,8, 20))); foodService.saveFood(CreateFoodDto.of(userId, "Food3", BaseNutrition.createNutrition(100, 80 ,6, 7))); From 0773ebf759dafa2f5e3952d662cb105f173b6877 Mon Sep 17 00:00:00 2001 From: CHAE Date: Sat, 14 Oct 2023 11:34:47 +0900 Subject: [PATCH 090/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20Refactor:=20Us?= =?UTF-8?q?erServiceTest=20Mock=EC=9C=BC=EB=A1=9C=20=EB=A6=AC=ED=8C=A9?= =?UTF-8?q?=ED=86=A0=EB=A7=81=20(=EA=B2=80=EC=83=89=20=EC=A0=9C=EC=99=B8)?= =?UTF-8?q?=20(#26)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/UserServiceTest.java | 211 ++++++++++-------- 1 file changed, 118 insertions(+), 93 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/UserServiceTest.java b/src/test/java/com/diareat/diareat/service/UserServiceTest.java index 7d2ec45..329e8be 100644 --- a/src/test/java/com/diareat/diareat/service/UserServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/UserServiceTest.java @@ -1,167 +1,192 @@ package com.diareat.diareat.service; +import com.diareat.diareat.user.domain.BaseNutrition; +import com.diareat.diareat.user.domain.Follow; +import com.diareat.diareat.user.domain.User; import com.diareat.diareat.user.dto.*; import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.user.service.UserService; -import org.junit.jupiter.api.AfterEach; -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.context.SpringBootTest; -import org.springframework.transaction.annotation.Transactional; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.*; -@SpringBootTest -@Transactional +@ExtendWith(MockitoExtension.class) class UserServiceTest { - @Autowired - UserService userService; - - @Autowired - UserRepository userRepository; + @InjectMocks + private UserService userService; - @Autowired - FollowRepository followRepository; - - @BeforeEach - void setUp() { - userRepository.deleteAll(); - followRepository.deleteAll(); - } + @Mock + private UserRepository userRepository; - @AfterEach - void tearDown() { - userRepository.deleteAll(); - followRepository.deleteAll(); - } + @Mock + private FollowRepository followRepository; + @DisplayName("회원정보 저장") @Test void saveUser() { - // given - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 75, 1, 25)); + // Given + CreateUserDto createUserDto = CreateUserDto.of("test", "profile.jpg", "testPassword", 0, 75, 1, 25); + BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); + User user = User.createUser(createUserDto.getName(), createUserDto.getImage(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); - // when - ResponseUserDto responseUserDto = userService.getUserInfo(userId); + given(userRepository.existsByName("test")).willReturn(false); // 유저가 존재하지 않음 + given(userRepository.save(any(User.class))).willReturn(user); + + // When + Long id = userService.saveUser(createUserDto); - // then - assertNotNull(responseUserDto); - assertEquals("testUser", responseUserDto.getName()); - assertEquals(25, responseUserDto.getAge()); + // Then + assertEquals(user.getId(), id); // 저장된 사용자의 ID와 반환된 ID를 비교 + verify(userRepository, times(1)).save(any(User.class)); // userRepository의 save 메서드가 1번 호출되었는지 확인 } @Test void getSimpleUserInfo() { - // given - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 75, 1, 25)); + // Given + Long userId = 1L; + User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + given(userRepository.findById(userId)).willReturn(Optional.of(user)); - // when - ResponseSimpleUserDto responseSimpleUserDto = userService.getSimpleUserInfo(userId); + // When + ResponseSimpleUserDto result = userService.getSimpleUserInfo(userId); - // then - assertEquals("testUser", responseSimpleUserDto.getName()); + // Then + assertEquals("test", result.getName()); + assertEquals("profile.jpg", result.getImage()); } @Test void getUserInfo() { - // given - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 75, 1, 25)); + // Given + Long userId = 1L; + User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + given(userRepository.findById(userId)).willReturn(Optional.of(user)); - // when - ResponseUserDto responseUserDto = userService.getUserInfo(userId); + // When + ResponseUserDto result = userService.getUserInfo(userId); - // then - assertEquals("testUser", responseUserDto.getName()); + // Then + assertEquals("test", result.getName()); + assertEquals(30, result.getAge()); } @Test void updateUserInfo() { // given - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 160, 50, 25)); - UpdateUserDto updateUserDto = UpdateUserDto.of(userId, "updateUser", 180, 75, 25, false); + UpdateUserDto updateUserDto = UpdateUserDto.of(1L, "update", 180, 75, 25, false); + User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + given(userRepository.findById(updateUserDto.getUserId())).willReturn(Optional.of(user)); // when userService.updateUserInfo(updateUserDto); - // then - assertEquals("updateUser", userService.getUserInfo(userId).getName()); - assertEquals(180, userService.getUserInfo(userId).getHeight()); + + // Then + assertEquals("update", user.getName()); + assertEquals(180, user.getHeight()); + assertEquals(75, user.getWeight()); + assertEquals(25, user.getAge()); } @Test void getUserNutrition() { // 임시 코드 사용, 추후 로직 개편 시 테스트코드 수정 - // given - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 160, 50, 25)); - - // when - ResponseUserNutritionDto responseUserNutritionDto = userService.getUserNutrition(userId); - - // then - assertEquals(2000, responseUserNutritionDto.getCalorie()); + // Given + Long userId = 1L; + User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + given(userRepository.findById(userId)).willReturn(Optional.of(user)); + + // When + ResponseUserNutritionDto result = userService.getUserNutrition(userId); + + // Then + assertEquals(2000, result.getCalorie()); + assertEquals(300, result.getCarbohydrate()); + assertEquals(80, result.getProtein()); + assertEquals(80, result.getFat()); } @Test void updateBaseNutrition() { - // given - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 160, 50, 25)); + // Given + UpdateUserNutritionDto updateUserNutritionDto = UpdateUserNutritionDto.of(1L, 2000, 300, 80, 80); + // 필드 초기화 + User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(1000, 100, 40, 40)); + given(userRepository.findById(updateUserNutritionDto.getUserId())).willReturn(Optional.of(user)); - // when - UpdateUserNutritionDto updateUserNutritionDto = UpdateUserNutritionDto.of(userId, 2000, 300, 80, 80); + // When userService.updateBaseNutrition(updateUserNutritionDto); - // then - assertEquals(2000, userService.getUserNutrition(userId).getCalorie()); + // Then + assertEquals(2000, user.getBaseNutrition().getKcal()); + assertEquals(300, user.getBaseNutrition().getCarbohydrate()); + assertEquals(80, user.getBaseNutrition().getProtein()); + assertEquals(80, user.getBaseNutrition().getFat()); } @Test void deleteUser() { - // given - Long id = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 75, 1, 25)); + // Given + Long userId = 1L; + given(userRepository.existsById(userId)).willReturn(true); - // when - userService.deleteUser(id); + // When + userService.deleteUser(userId); - // then - assertFalse(userRepository.existsById(id)); + // Then + verify(userRepository, times(1)).deleteById(userId); } @Test void searchUser() { - // given - userService.saveUser(CreateUserDto.of("user1", "testPassword", 0, 175, 80, 25)); - Long id = userService.saveUser(CreateUserDto.of("user2", "testPassword", 0, 175, 80, 25)); - String name = "user"; - // then - assertEquals(2, userService.searchUser(id, name).size()); } @Test void followUser() { - // given - Long id1 = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 75, 1, 25)); - Long id2 = userService.saveUser(CreateUserDto.of("followUser", "testPassword", 0, 75, 1, 25)); - - // when - userService.followUser(id2, id1); - - // then - assertEquals(1, followRepository.findAllByFromUser(id1).size()); + // Given + Long userId = 1L; // 팔로우 요청을 보낸 사용자의 ID + Long followId = 2L; // 팔로우할 사용자의 ID + + given(userRepository.existsById(userId)).willReturn(true); // userId에 해당하는 사용자가 존재함 + given(userRepository.existsById(followId)).willReturn(true); // followId에 해당하는 사용자가 존재함 + given(followRepository.existsByFromUserAndToUser(userId, followId)).willReturn(false); // 아직 팔로우 중이 아님 + + // When + userService.followUser(userId, followId); + + // Then + verify(userRepository, times(1)).existsById(userId); // 사용자 존재 여부 확인 + verify(userRepository, times(1)).existsById(followId); // 팔로우할 사용자 존재 여부 확인 + verify(followRepository, times(1)).existsByFromUserAndToUser(userId, followId); // 이미 팔로우 중인지 확인 + verify(followRepository, times(1)).save(any(Follow.class)); } @Test void unfollowUser() { - // given - Long id1 = userService.saveUser(CreateUserDto.of("testUser", "testPassword", 0, 175, 1, 25)); - Long id2 = userService.saveUser(CreateUserDto.of("followUser", "testPassword", 0, 175, 1, 25)); + // Given + Long userId = 1L; // 팔로우 취소를 요청한 사용자의 ID + Long unfollowId = 2L; // 팔로우를 취소할 사용자의 ID - // when - userService.followUser(id1, id2); - userService.unfollowUser(id1, id2); + given(userRepository.existsById(userId)).willReturn(true); // userId에 해당하는 사용자가 존재함 + given(userRepository.existsById(unfollowId)).willReturn(true); // unfollowId에 해당하는 사용자가 존재함 + given(followRepository.existsByFromUserAndToUser(userId, unfollowId)).willReturn(true); + + // When + userService.unfollowUser(userId, unfollowId); - // then - assertEquals(0, followRepository.findAllByFromUser(id1).size()); + // Then + verify(followRepository, times(1)).delete(any(Follow.class)); } } \ No newline at end of file From edb2303f71713160c07b61ca460ca399dd387eba Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 15 Oct 2023 01:15:49 +0900 Subject: [PATCH 091/371] =?UTF-8?q?:bug:=20Fix:=20UserController=20import?= =?UTF-8?q?=20=EC=A0=95=EB=A6=AC=20=EB=B0=8F=20UserService=20=EA=B2=80?= =?UTF-8?q?=EC=83=89=EA=B8=B0=EB=8A=A5=20=EB=B2=84=EA=B7=B8=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=20(#26)"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/controller/UserController.java | 1 - .../com/diareat/diareat/user/domain/User.java | 8 +-- .../diareat/user/service/UserService.java | 4 +- .../diareat/service/UserServiceTest.java | 60 ++++++++++++++----- 4 files changed, 52 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/controller/UserController.java b/src/main/java/com/diareat/diareat/user/controller/UserController.java index ce6c3f5..5024b92 100644 --- a/src/main/java/com/diareat/diareat/user/controller/UserController.java +++ b/src/main/java/com/diareat/diareat/user/controller/UserController.java @@ -7,7 +7,6 @@ import io.swagger.annotations.Api; import io.swagger.v3.oas.annotations.Operation; import lombok.RequiredArgsConstructor; -import net.bytebuddy.implementation.bind.annotation.Empty; import org.springframework.web.bind.annotation.*; import java.util.List; diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index 47d470e..178cb50 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -14,11 +14,11 @@ @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @Entity -public class User { +public class TestUser { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_id") - private Long id; + protected Long id; private String name; // 닉네임 @@ -44,8 +44,8 @@ public class User { private List favoriteFoods = new ArrayList<>(); // 생성 메서드 - public static User createUser(String name, String image, String keyCode, int height, int weight, int gender, int age, BaseNutrition baseNutrition) { - User user = new User(); + public static TestUser createUser(String name, String image, String keyCode, int height, int weight, int gender, int age, BaseNutrition baseNutrition) { + TestUser user = new TestUser(); user.name = name; user.image = image; user.keyCode = keyCode; diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index caf312a..80db78a 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -12,6 +12,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -82,7 +83,8 @@ public void deleteUser(Long userId) { @Transactional(readOnly = true) public List searchUser(Long hostId, String name) { validateUser(hostId); - List users = userRepository.findAllByNameContaining(name); + List users = new ArrayList<>(userRepository.findAllByNameContaining(name)); + users.removeIf(user -> user.getId().equals(hostId)); // 검색 결과에서 자기 자신은 제외 (removeIf 메서드는 ArrayList에만 존재) return users.stream() .map(user -> ResponseSearchUserDto.of(user.getId(), user.getName(), user.getImage(), followRepository.existsByFromUserAndToUser(hostId, user.getId()))).collect(Collectors.toList()); } diff --git a/src/test/java/com/diareat/diareat/service/UserServiceTest.java b/src/test/java/com/diareat/diareat/service/UserServiceTest.java index 329e8be..fc2c222 100644 --- a/src/test/java/com/diareat/diareat/service/UserServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/UserServiceTest.java @@ -2,7 +2,7 @@ import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.Follow; -import com.diareat.diareat.user.domain.User; +import com.diareat.diareat.user.domain.TestUser; import com.diareat.diareat.user.dto.*; import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; @@ -14,6 +14,7 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; @@ -22,7 +23,7 @@ import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) -class UserServiceTest { +class TestUserServiceTest { @InjectMocks private UserService userService; @@ -35,28 +36,29 @@ class UserServiceTest { @DisplayName("회원정보 저장") @Test - void saveUser() { + void saveUser() { // setId() 메서드 임시 삽입하여 테스트 진행함 // Given CreateUserDto createUserDto = CreateUserDto.of("test", "profile.jpg", "testPassword", 0, 75, 1, 25); BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); - User user = User.createUser(createUserDto.getName(), createUserDto.getImage(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); + TestUser user = TestUser.createUser(createUserDto.getName(), createUserDto.getImage(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); + user.setId(1L); // 테스트 커밋 중 User에 setId() 메서드 임시적으로 삽입하여 테스트 진행함 - given(userRepository.existsByName("test")).willReturn(false); // 유저가 존재하지 않음 - given(userRepository.save(any(User.class))).willReturn(user); + given(userRepository.existsByName("test")).willReturn(false); + given(userRepository.save(any(TestUser.class))).willReturn(user); // When - Long id = userService.saveUser(createUserDto); + Long id = userService.saveUser(createUserDto); // id null로 반환됨 (Mock은 실제 DB에 객체를 생성하지 않기 때문) // Then - assertEquals(user.getId(), id); // 저장된 사용자의 ID와 반환된 ID를 비교 - verify(userRepository, times(1)).save(any(User.class)); // userRepository의 save 메서드가 1번 호출되었는지 확인 + assertEquals(1L, id); + verify(userRepository, times(1)).save(any(TestUser.class)); } @Test void getSimpleUserInfo() { // Given Long userId = 1L; - User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + TestUser user = TestUser.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); given(userRepository.findById(userId)).willReturn(Optional.of(user)); // When @@ -71,7 +73,7 @@ void getSimpleUserInfo() { void getUserInfo() { // Given Long userId = 1L; - User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + TestUser user = TestUser.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); given(userRepository.findById(userId)).willReturn(Optional.of(user)); // When @@ -86,7 +88,7 @@ void getUserInfo() { void updateUserInfo() { // given UpdateUserDto updateUserDto = UpdateUserDto.of(1L, "update", 180, 75, 25, false); - User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + TestUser user = TestUser.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); given(userRepository.findById(updateUserDto.getUserId())).willReturn(Optional.of(user)); // when @@ -104,7 +106,7 @@ void updateUserInfo() { void getUserNutrition() { // 임시 코드 사용, 추후 로직 개편 시 테스트코드 수정 // Given Long userId = 1L; - User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + TestUser user = TestUser.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); given(userRepository.findById(userId)).willReturn(Optional.of(user)); // When @@ -122,7 +124,7 @@ void updateBaseNutrition() { // Given UpdateUserNutritionDto updateUserNutritionDto = UpdateUserNutritionDto.of(1L, 2000, 300, 80, 80); // 필드 초기화 - User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(1000, 100, 40, 40)); + TestUser user = TestUser.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(1000, 100, 40, 40)); given(userRepository.findById(updateUserNutritionDto.getUserId())).willReturn(Optional.of(user)); // When @@ -149,8 +151,36 @@ void deleteUser() { } @Test - void searchUser() { + void searchUser() { // setId() 메서드 임시 삽입하여 테스트 진행함 + // Given + Long userId1 = 1L; + Long userId2 = 2L; + Long userId3 = 3L; + String name = "John"; + + // 사용자 목록 생성 + TestUser user1 = TestUser.createUser("John", "profile1.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + TestUser user2 = TestUser.createUser("John Doe", "profile2.jpg", "keycode456", 170, 65, 1, 35, BaseNutrition.createNutrition(2000, 300, 80, 80)); + TestUser user3 = TestUser.createUser("John Doo", "profile3.jpg", "keycode789", 160, 55, 1, 25, BaseNutrition.createNutrition(2000, 300, 80, 80)); + user1.setId(userId1); + user2.setId(userId2); + user3.setId(userId3); + + given(userRepository.existsById(userId1)).willReturn(true); + given(userRepository.findAllByNameContaining(name)).willReturn(List.of(user1, user2, user3)); + given(followRepository.existsByFromUserAndToUser(userId1, userId2)).willReturn(true); + given(followRepository.existsByFromUserAndToUser(userId1, userId3)).willReturn(false); + + // When + List result = userService.searchUser(userId1, name); + // Then + assertEquals(2, result.size()); + assertEquals("John Doe", result.get(0).getName()); + assertTrue(result.get(0).isFollow()); + assertEquals("John Doo", result.get(1).getName()); + assertFalse(result.get(1).isFollow()); + verify(userRepository, times(1)).findAllByNameContaining(name); } @Test From 2e8afd8a0dffca9a875603e8b1935766c96a8b43 Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 15 Oct 2023 01:18:02 +0900 Subject: [PATCH 092/371] =?UTF-8?q?:recycle:=20Refactor:=20UserServiceTest?= =?UTF-8?q?=20=EA=B2=80=EC=83=89=EA=B8=B0=EB=8A=A5=20Mock=20=EC=A0=81?= =?UTF-8?q?=EC=9A=A9=20=EB=B0=8F=20User=EC=97=90=20SetId()=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20(#26)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/user/domain/User.java | 12 +++++--- .../diareat/service/UserServiceTest.java | 30 +++++++++---------- 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index 178cb50..6852f48 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -14,11 +14,11 @@ @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @Entity -public class TestUser { +public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_id") - protected Long id; + private Long id; private String name; // 닉네임 @@ -44,8 +44,8 @@ public class TestUser { private List favoriteFoods = new ArrayList<>(); // 생성 메서드 - public static TestUser createUser(String name, String image, String keyCode, int height, int weight, int gender, int age, BaseNutrition baseNutrition) { - TestUser user = new TestUser(); + public static User createUser(String name, String image, String keyCode, int height, int weight, int gender, int age, BaseNutrition baseNutrition) { + User user = new User(); user.name = name; user.image = image; user.keyCode = keyCode; @@ -69,4 +69,8 @@ public void updateUser(String name, int height, int weight, int age) { public void updateBaseNutrition(BaseNutrition baseNutrition) { this.baseNutrition = baseNutrition; } + + public void setId(Long id) { // 테스트코드용 메서드 + this.id = id; + } } diff --git a/src/test/java/com/diareat/diareat/service/UserServiceTest.java b/src/test/java/com/diareat/diareat/service/UserServiceTest.java index fc2c222..0d062e9 100644 --- a/src/test/java/com/diareat/diareat/service/UserServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/UserServiceTest.java @@ -2,7 +2,7 @@ import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.Follow; -import com.diareat.diareat.user.domain.TestUser; +import com.diareat.diareat.user.domain.User; import com.diareat.diareat.user.dto.*; import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; @@ -23,7 +23,7 @@ import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) -class TestUserServiceTest { +class UserServiceTest { @InjectMocks private UserService userService; @@ -36,29 +36,29 @@ class TestUserServiceTest { @DisplayName("회원정보 저장") @Test - void saveUser() { // setId() 메서드 임시 삽입하여 테스트 진행함 + void saveUser() { // setId() 메서드로 테스트 진행함 // Given CreateUserDto createUserDto = CreateUserDto.of("test", "profile.jpg", "testPassword", 0, 75, 1, 25); BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); - TestUser user = TestUser.createUser(createUserDto.getName(), createUserDto.getImage(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); + User user = User.createUser(createUserDto.getName(), createUserDto.getImage(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); user.setId(1L); // 테스트 커밋 중 User에 setId() 메서드 임시적으로 삽입하여 테스트 진행함 given(userRepository.existsByName("test")).willReturn(false); - given(userRepository.save(any(TestUser.class))).willReturn(user); + given(userRepository.save(any(User.class))).willReturn(user); // When Long id = userService.saveUser(createUserDto); // id null로 반환됨 (Mock은 실제 DB에 객체를 생성하지 않기 때문) // Then assertEquals(1L, id); - verify(userRepository, times(1)).save(any(TestUser.class)); + verify(userRepository, times(1)).save(any(User.class)); } @Test void getSimpleUserInfo() { // Given Long userId = 1L; - TestUser user = TestUser.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); given(userRepository.findById(userId)).willReturn(Optional.of(user)); // When @@ -73,7 +73,7 @@ void getSimpleUserInfo() { void getUserInfo() { // Given Long userId = 1L; - TestUser user = TestUser.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); given(userRepository.findById(userId)).willReturn(Optional.of(user)); // When @@ -88,7 +88,7 @@ void getUserInfo() { void updateUserInfo() { // given UpdateUserDto updateUserDto = UpdateUserDto.of(1L, "update", 180, 75, 25, false); - TestUser user = TestUser.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); given(userRepository.findById(updateUserDto.getUserId())).willReturn(Optional.of(user)); // when @@ -106,7 +106,7 @@ void updateUserInfo() { void getUserNutrition() { // 임시 코드 사용, 추후 로직 개편 시 테스트코드 수정 // Given Long userId = 1L; - TestUser user = TestUser.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); given(userRepository.findById(userId)).willReturn(Optional.of(user)); // When @@ -124,7 +124,7 @@ void updateBaseNutrition() { // Given UpdateUserNutritionDto updateUserNutritionDto = UpdateUserNutritionDto.of(1L, 2000, 300, 80, 80); // 필드 초기화 - TestUser user = TestUser.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(1000, 100, 40, 40)); + User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(1000, 100, 40, 40)); given(userRepository.findById(updateUserNutritionDto.getUserId())).willReturn(Optional.of(user)); // When @@ -151,7 +151,7 @@ void deleteUser() { } @Test - void searchUser() { // setId() 메서드 임시 삽입하여 테스트 진행함 + void searchUser() { // setId() 메서드로 테스트 진행함 // Given Long userId1 = 1L; Long userId2 = 2L; @@ -159,9 +159,9 @@ void searchUser() { // setId() 메서드 임시 삽입하여 테스트 진행함 String name = "John"; // 사용자 목록 생성 - TestUser user1 = TestUser.createUser("John", "profile1.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); - TestUser user2 = TestUser.createUser("John Doe", "profile2.jpg", "keycode456", 170, 65, 1, 35, BaseNutrition.createNutrition(2000, 300, 80, 80)); - TestUser user3 = TestUser.createUser("John Doo", "profile3.jpg", "keycode789", 160, 55, 1, 25, BaseNutrition.createNutrition(2000, 300, 80, 80)); + User user1 = User.createUser("John", "profile1.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); + User user2 = User.createUser("John Doe", "profile2.jpg", "keycode456", 170, 65, 1, 35, BaseNutrition.createNutrition(2000, 300, 80, 80)); + User user3 = User.createUser("John Doo", "profile3.jpg", "keycode789", 160, 55, 1, 25, BaseNutrition.createNutrition(2000, 300, 80, 80)); user1.setId(userId1); user2.setId(userId2); user3.setId(userId3); From 4a889e33f5f26b68862fe99e01743c780505d453 Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 15 Oct 2023 20:41:44 +0900 Subject: [PATCH 093/371] =?UTF-8?q?:recycle:=20Refactor:=20Api=20=EC=9D=91?= =?UTF-8?q?=EB=8B=B5=20=EA=B0=9D=EC=B2=B4=20=EB=A6=AC=ED=8C=A9=ED=86=A0?= =?UTF-8?q?=EB=A7=81=20(#28)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/util/api/ApiBody.java | 16 ---------------- .../com/diareat/diareat/util/api/ApiHeader.java | 13 +++++-------- .../diareat/diareat/util/api/ApiResponse.java | 16 +++++++--------- 3 files changed, 12 insertions(+), 33 deletions(-) delete mode 100644 src/main/java/com/diareat/diareat/util/api/ApiBody.java diff --git a/src/main/java/com/diareat/diareat/util/api/ApiBody.java b/src/main/java/com/diareat/diareat/util/api/ApiBody.java deleted file mode 100644 index d4fca17..0000000 --- a/src/main/java/com/diareat/diareat/util/api/ApiBody.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.diareat.diareat.util.api; - -public class ApiBody { - - private final T data; - private final T msg; - - public ApiBody(T data, T msg) { - this.data = data; - this.msg = msg; - } - - public T getData() { - return data; - } -} diff --git a/src/main/java/com/diareat/diareat/util/api/ApiHeader.java b/src/main/java/com/diareat/diareat/util/api/ApiHeader.java index f6c4fb9..7788e9a 100644 --- a/src/main/java/com/diareat/diareat/util/api/ApiHeader.java +++ b/src/main/java/com/diareat/diareat/util/api/ApiHeader.java @@ -1,18 +1,15 @@ package com.diareat.diareat.util.api; +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor public class ApiHeader { private int code; private String message; - public ApiHeader(int code, String message) { - this.code = code; - this.message = message; - } - - public ApiHeader() { - } - public int getCode() { return code; } diff --git a/src/main/java/com/diareat/diareat/util/api/ApiResponse.java b/src/main/java/com/diareat/diareat/util/api/ApiResponse.java index 4fe2374..ba96c5e 100644 --- a/src/main/java/com/diareat/diareat/util/api/ApiResponse.java +++ b/src/main/java/com/diareat/diareat/util/api/ApiResponse.java @@ -8,24 +8,22 @@ public class ApiResponse { private ApiHeader header; - private ApiBody body; + private T data; + private String msg; private static final int SUCCESS = 200; - public ApiResponse(ApiHeader header, ApiBody body) { - this.header = header; - this.body = body; - } - - public ApiResponse(ApiHeader header) { + private ApiResponse(ApiHeader header, T data, String msg) { this.header = header; + this.data = data; + this.msg = msg; } public static ApiResponse success(T data, String message) { - return new ApiResponse(new ApiHeader(SUCCESS, "SUCCESS"), new ApiBody(data, message)); + return new ApiResponse(new ApiHeader(SUCCESS, "SUCCESS"), data, message); } public static ApiResponse fail(ResponseCode responseCode) { - return new ApiResponse(new ApiHeader(responseCode.getHttpStatusCode(), responseCode.getMessage()), new ApiBody(null, responseCode.getMessage())); + return new ApiResponse(new ApiHeader(responseCode.getHttpStatusCode(), responseCode.getMessage()), null, responseCode.getMessage()); } } \ No newline at end of file From 16f635864696a08867ffc4c313c4d77fa326d0be Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 15 Oct 2023 20:46:15 +0900 Subject: [PATCH 094/371] =?UTF-8?q?:recycle:=20Fix:=20=EC=9D=BC=EB=B6=80?= =?UTF-8?q?=20=EB=B3=80=EC=88=98=EB=AA=85=20=EB=B0=8F=20=EC=A3=BC=EC=84=9D?= =?UTF-8?q?=20=EC=88=98=EC=A0=95(#28)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/user/controller/UserController.java | 2 +- .../com/diareat/diareat/user/dto/ResponseSearchUserDto.java | 2 +- .../java/com/diareat/diareat/user/service/UserService.java | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/controller/UserController.java b/src/main/java/com/diareat/diareat/user/controller/UserController.java index 5024b92..66693b6 100644 --- a/src/main/java/com/diareat/diareat/user/controller/UserController.java +++ b/src/main/java/com/diareat/diareat/user/controller/UserController.java @@ -28,7 +28,7 @@ public ApiResponse saveUser(CreateUserDto createUserDto) { // 회원 기본정보 조회 @Operation(summary = "[프로필] 회원 기본정보 조회", description = "회원 기본정보를 조회합니다.") - @GetMapping("{userId}/info/simple/") + @GetMapping("{userId}/info/simple") public ApiResponse getSimpleUserInfo(@PathVariable Long userId) { return ApiResponse.success(userService.getSimpleUserInfo(userId), ResponseCode.USER_CREATE_SUCCESS.getMessage()); } diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java index ef4a23a..811fa92 100644 --- a/src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java @@ -10,7 +10,7 @@ public class ResponseSearchUserDto { private Long userId; private String name; private String image; - private boolean isFollow; // 유저가 이미 팔로우한 유저인지 확인 + private boolean follow; // 유저가 이미 팔로우한 유저인지 확인 public static ResponseSearchUserDto of(Long userId, String name, String image, boolean isFollow) { return new ResponseSearchUserDto(userId, name, image, isFollow); diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 80db78a..22e85ef 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -56,14 +56,14 @@ public void updateUserInfo(UpdateUserDto updateUserDto) { user.updateUser(updateUserDto.getName(), updateUserDto.getHeight(), updateUserDto.getWeight(), updateUserDto.getAge()); } - // 회원 기준영양소 조회 + // 회원 기준섭취량 조회 @Transactional(readOnly = true) public ResponseUserNutritionDto getUserNutrition(Long userId) { User user = getUserById(userId); return ResponseUserNutritionDto.from(user); } - // 회원 기준영양소 직접 수정 + // 회원 기준섭취량 직접 수정 @Transactional public void updateBaseNutrition(UpdateUserNutritionDto updateUserNutritionDto) { User user = getUserById(updateUserNutritionDto.getUserId()); From 09932ef26b178dcc7f3ef83184577df3a359a77e Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 15 Oct 2023 20:47:09 +0900 Subject: [PATCH 095/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20Test:=20UserSe?= =?UTF-8?q?rviceTest=20@DisplayName=20=EC=B6=94=EA=B0=80=20=EB=B0=8F=20?= =?UTF-8?q?=EC=98=88=EC=99=B8=EC=B2=98=EB=A6=AC=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=EC=BD=94=EB=93=9C=20=EC=B6=94=EA=B0=80=20=EC=9E=91?= =?UTF-8?q?=EC=84=B1=20(#28)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/UserServiceTest.java | 57 ++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/diareat/diareat/service/UserServiceTest.java b/src/test/java/com/diareat/diareat/service/UserServiceTest.java index 0d062e9..98641d4 100644 --- a/src/test/java/com/diareat/diareat/service/UserServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/UserServiceTest.java @@ -7,6 +7,7 @@ import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.user.service.UserService; +import com.diareat.diareat.util.exception.UserException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -54,6 +55,22 @@ void saveUser() { // setId() 메서드로 테스트 진행함 verify(userRepository, times(1)).save(any(User.class)); } + @DisplayName("회원정보 저장 닉네임 중복") + @Test + void saveUserDupliacedName() { + // Given + CreateUserDto createUserDto = CreateUserDto.of("test", "profile.jpg", "testPassword", 0, 75, 1, 25); + BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); + User user = User.createUser(createUserDto.getName(), createUserDto.getImage(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); + user.setId(1L); // 테스트 커밋 중 User에 setId() 메서드 임시적으로 삽입하여 테스트 진행함 + + given(userRepository.existsByName("test")).willReturn(true); + + // When -> 예외처리 + assertThrows(UserException.class, () -> userService.saveUser(createUserDto)); + } + + @DisplayName("회원 기본정보 조회") @Test void getSimpleUserInfo() { // Given @@ -69,6 +86,7 @@ void getSimpleUserInfo() { assertEquals("profile.jpg", result.getImage()); } + @DisplayName("회원정보 조회") @Test void getUserInfo() { // Given @@ -84,6 +102,7 @@ void getUserInfo() { assertEquals(30, result.getAge()); } + @DisplayName("회원정보 수정") @Test void updateUserInfo() { // given @@ -102,6 +121,7 @@ void updateUserInfo() { assertEquals(25, user.getAge()); } + @DisplayName("회원 기준섭취량 조회") @Test void getUserNutrition() { // 임시 코드 사용, 추후 로직 개편 시 테스트코드 수정 // Given @@ -119,6 +139,7 @@ void getUserNutrition() { // 임시 코드 사용, 추후 로직 개편 시 테 assertEquals(80, result.getFat()); } + @DisplayName("회원 기준섭취량 직접 수정") @Test void updateBaseNutrition() { // Given @@ -137,6 +158,7 @@ void updateBaseNutrition() { assertEquals(80, user.getBaseNutrition().getFat()); } + @DisplayName("회원 탈퇴") @Test void deleteUser() { // Given @@ -150,6 +172,7 @@ void deleteUser() { verify(userRepository, times(1)).deleteById(userId); } + @DisplayName("회원의 친구 검색 결과 조회") @Test void searchUser() { // setId() 메서드로 테스트 진행함 // Given @@ -183,6 +206,7 @@ void searchUser() { // setId() 메서드로 테스트 진행함 verify(userRepository, times(1)).findAllByNameContaining(name); } + @DisplayName("회원이 특정 회원 팔로우") @Test void followUser() { // Given @@ -203,6 +227,22 @@ void followUser() { verify(followRepository, times(1)).save(any(Follow.class)); } + @DisplayName("회원이 특정 회원 팔로우 중복 요청") + @Test + void followerUserDuplicate() { + // Given + Long userId = 1L; // 팔로우 요청을 보낸 사용자의 ID + Long followId = 2L; // 팔로우할 사용자의 ID + + given(userRepository.existsById(userId)).willReturn(true); // userId에 해당하는 사용자가 존재함 + given(userRepository.existsById(followId)).willReturn(true); // followId에 해당하는 사용자가 존재함 + given(followRepository.existsByFromUserAndToUser(userId, followId)).willReturn(true); // 아직 팔로우 중이 아님 + + // When -> 예외처리 + assertThrows(UserException.class, () -> userService.followUser(userId, followId)); + } + + @DisplayName("회원이 특정 회원 팔로우 취소") @Test void unfollowUser() { // Given @@ -219,4 +259,19 @@ void unfollowUser() { // Then verify(followRepository, times(1)).delete(any(Follow.class)); } -} \ No newline at end of file + + @DisplayName("회원이 특정 회원 팔로우 취소 중복 요청") + @Test + void unfollowUserDuplicate() { + // Given + Long userId = 1L; // 팔로우 취소를 요청한 사용자의 ID + Long unfollowId = 2L; // 팔로우를 취소할 사용자의 ID + + given(userRepository.existsById(userId)).willReturn(true); // userId에 해당하는 사용자가 존재함 + given(userRepository.existsById(unfollowId)).willReturn(true); // unfollowId에 해당하는 사용자가 존재함 + given(followRepository.existsByFromUserAndToUser(userId, unfollowId)).willReturn(false); + + // When -> 예외처리 + assertThrows(UserException.class, () -> userService.unfollowUser(userId, unfollowId)); + } +} From ce4428ed479d573b7e81b54746ff871bc25b51cc Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 15 Oct 2023 20:49:26 +0900 Subject: [PATCH 096/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20Test:=20UserCo?= =?UTF-8?q?ntrollerTest=20=EA=B5=AC=ED=98=84=20(#28)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/UserControllerTest.java | 222 ++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 src/test/java/com/diareat/diareat/controller/UserControllerTest.java diff --git a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java new file mode 100644 index 0000000..7fbdb95 --- /dev/null +++ b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java @@ -0,0 +1,222 @@ +package com.diareat.diareat.controller; + +import com.diareat.diareat.user.controller.UserController; +import com.diareat.diareat.user.domain.BaseNutrition; +import com.diareat.diareat.user.domain.User; +import com.diareat.diareat.user.dto.*; +import com.diareat.diareat.user.service.UserService; +import com.diareat.diareat.util.api.ApiResponse; +import com.diareat.diareat.util.api.ResponseCode; +import com.fasterxml.jackson.databind.ObjectMapper; +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.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@WebMvcTest(controllers = UserController.class) +class UserControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + @MockBean + private UserService userService; + + private final Long testUserId = 1L; + 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)); + + @BeforeEach + void setUp() { + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + testUser.setId(testUserId); + when(userService.getSimpleUserInfo(testUserId)).thenReturn(ResponseSimpleUserDto.of(testUser.getName(), testUser.getImage(), 100.0)); + when(userService.getUserInfo(testUserId)).thenReturn(ResponseUserDto.from(testUser)); + } + + @DisplayName("회원정보 저장") + @Test + @WithMockUser("test") + void testSaveUser() throws Exception { + // Given + ApiResponse expectedResponse = ApiResponse.success(testUserId, ResponseCode.USER_CREATE_SUCCESS.getMessage()); + String json = "{\"name\":\"test\",\"image\":\"test\",\"keyCode\":\"test\",\"gender\":0,\"height\":180,\"weight\":70,\"age\":20}"; + when(userService.saveUser(any(CreateUserDto.class))).thenReturn(testUserId); + + // When & Then + mockMvc.perform( MockMvcRequestBuilders + .post("/api/user/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("$.msg").value(expectedResponse.getMsg())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data").value(expectedResponse.getData())); + } + + + @DisplayName("회원 기본정보 조회") + @Test + @WithMockUser("test") + void testGetSimpleUserInfo() throws Exception { + // Given + ApiResponse expectedResponse = ApiResponse.success( + ResponseSimpleUserDto.of(testUser.getName(), testUser.getImage(), 100.0), ResponseCode.USER_CREATE_SUCCESS.getMessage()); + + // When & Then + mockMvc.perform( MockMvcRequestBuilders + .get("/api/user/1/info/simple", 1L) + .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.name").value(expectedResponse.getData().getName())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.image").value(expectedResponse.getData().getImage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.nutritionScore").value(expectedResponse.getData().getNutritionScore())); + } + + @DisplayName("회원정보 조회") + @Test + @WithMockUser("test") + void getUserInfo() throws Exception { + // Given + ApiResponse expectedResponse = ApiResponse.success( + ResponseUserDto.from(testUser), ResponseCode.USER_CREATE_SUCCESS.getMessage()); + + // When & Then + mockMvc.perform( MockMvcRequestBuilders + .get("/api/user/1/info", 1L) + .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.name").value(expectedResponse.getData().getName())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.height").value(expectedResponse.getData().getHeight())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.weight").value(expectedResponse.getData().getWeight())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.age").value(expectedResponse.getData().getAge())); + } + + @DisplayName("회원정보 수정") + @Test + @WithMockUser("test") + void updateUser() throws Exception { + // Given + ApiResponse expectedResponse = ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); + UpdateUserDto user = UpdateUserDto.of(testUserId, "test2", 170, 80, 21, true); + String json = mapper.writeValueAsString(user); + + // When & Then + mockMvc.perform( MockMvcRequestBuilders + .put("/api/user/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 getUserNutrition() throws Exception { + // Given + when(userService.getUserNutrition(testUserId)).thenReturn(ResponseUserNutritionDto.of(2000, 300, 300, 80)); + ApiResponse expectedResponse = ApiResponse.success( + ResponseUserNutritionDto.of(2000, 300, 300, 80), ResponseCode.USER_READ_SUCCESS.getMessage()); + + // When & Then + mockMvc.perform( MockMvcRequestBuilders + .get("/api/user/1/nutrition", 1L) + .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.calorie").value(expectedResponse.getData().getCalorie())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.protein").value(expectedResponse.getData().getProtein())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.fat").value(expectedResponse.getData().getFat())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.carbohydrate").value(expectedResponse.getData().getCarbohydrate())); + } + + @DisplayName("회원 기준섭취량 직접 수정") + @Test + @WithMockUser("test") + void updateUserNutrition() throws Exception { + // Given + ApiResponse expectedResponse = ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); + UpdateUserNutritionDto nutrition = UpdateUserNutritionDto.of(testUserId, 2000, 300, 300, 80); + String json = mapper.writeValueAsString(nutrition); + + // When & Then + mockMvc.perform( MockMvcRequestBuilders + .put("/api/user/1/nutrition") + .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 searchUser() throws Exception { + // Given + when(userService.searchUser(testUserId, "test")).thenReturn(List.of(ResponseSearchUserDto.of(2L, "test2", "test2", true))); + ApiResponse> expectedResponse = ApiResponse.success( + List.of(ResponseSearchUserDto.of(2L, "test2", "test2", true)), ResponseCode.USER_SEARCH_SUCCESS.getMessage()); + + // When & Then + mockMvc.perform( MockMvcRequestBuilders + .get("/api/user/1/search/test").param("name", "test") + .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].userId").value(2L)) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].name").value(expectedResponse.getData().get(0).getName())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].image").value(expectedResponse.getData().get(0).getImage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].follow").value(expectedResponse.getData().get(0).isFollow())); + } + + @DisplayName("회원이 특정 회원 팔로우 및 팔로우 취소") + @Test + @WithMockUser("test") + void followUser() throws Exception { + // Given + ApiResponse expectedResponse = ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); + + // When & Then + mockMvc.perform( MockMvcRequestBuilders + .post("/api/user/1/follow/2") + //.delete("/api/user/1/follow/2") + .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())); + } +} From c870e14e1734fb072c6030a65d6712ef7a39a44c Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 22:15:46 +0900 Subject: [PATCH 097/371] :recycle: refactor: testSaveAndGetFood() mocking (#29) --- .../com/diareat/diareat/food/domain/Food.java | 3 +- .../diareat/service/FoodServiceTest.java | 375 +++++++++--------- 2 files changed, 194 insertions(+), 184 deletions(-) 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 851c5e5..8d9f9e2 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -5,7 +5,6 @@ import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; -import org.springframework.data.annotation.CreatedDate; import javax.persistence.*; import java.time.LocalDate; @@ -56,4 +55,6 @@ public void updateFood(String name, BaseNutrition baseNutrition) { public boolean isFavorite() { return this.favoriteFood != null; } + + public void setId(long id) {this.id = id;} } diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 651f7b3..652e35f 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -1,6 +1,5 @@ package com.diareat.diareat.service; -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.repository.FavoriteFoodRepository; @@ -11,218 +10,228 @@ import com.diareat.diareat.user.dto.CreateUserDto; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.user.service.UserService; -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.context.SpringBootTest; -import org.springframework.transaction.annotation.Transactional; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.time.LocalDate; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; -@SpringBootTest -@Transactional +@ExtendWith(MockitoExtension.class) class FoodServiceTest { - @Autowired + @InjectMocks FoodService foodService; - @Autowired + @InjectMocks UserService userService; - @Autowired + @Mock FoodRepository foodRepository; - @Autowired + @Mock FavoriteFoodRepository favoriteFoodRepository; - @Autowired + @Mock UserRepository userRepository; - @BeforeEach - public void setUp() { - userRepository.deleteAll(); - foodRepository.deleteAll(); - favoriteFoodRepository.deleteAll(); - } - + @DisplayName("음식 정보 저장") @Test void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리스트 불러오기 // given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword", 1,180, 80,18)); - - //when - Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood",testBaseNutrition)); - Food testFood = foodRepository.getReferenceById(foodId); - - List responseFoodDtoList = foodService.getFoodListByDate(userId, testFood.getDate()); - - assertNotNull(responseFoodDtoList); - assertEquals("testFood",responseFoodDtoList.get(0).getName()); - } - - @Test - void testUpdateFood() { - //given - BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); - Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); - - //when - BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); - foodService.updateFood(UpdateFoodDto.of(foodId, "testChangedFood", testChangedBaseNutrition)); - - Food changedFood = foodRepository.getReferenceById(foodId); - - assertNotNull(changedFood); - assertEquals("testChangedFood", changedFood.getName()); - assertEquals(2,changedFood.getBaseNutrition().getKcal()); - assertEquals(3,changedFood.getBaseNutrition().getCarbohydrate()); - assertEquals(4,changedFood.getBaseNutrition().getProtein()); - assertEquals(5,changedFood.getBaseNutrition().getFat()); - } - - @Test - void testDeleteFood() { - //given - BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); - Long userId = userService.saveUser(CreateUserDto.of("testUser","testImage", "tessPassword", 1, 180, 80, 18)); - Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); - - //when - foodService.deleteFood(foodId); - - assertNull(foodRepository.findById(foodId).orElse(null)); - } - - @Test - void testSaveAndGetFavoriteFood() { - //given - BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); - Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); - - //when - Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); - - List responseFavoriteFoodDtoList = foodService.getFavoriteFoodList(userId); - - assertNotNull(responseFavoriteFoodDtoList); - assertEquals("testFood",responseFavoriteFoodDtoList.get(0).getName()); - } - - @Test - void testUpdateFavoriteFood() { - //given - BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); - Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); - Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); + CreateUserDto createUserDto = CreateUserDto.of("testUser", "testImage","testPassword", 1,180, 80,18); + User user = User.createUser(createUserDto.getName(), createUserDto.getImage(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), testBaseNutrition); + user.setId(1L); + CreateFoodDto createFoodDto = CreateFoodDto.of(user.getId(), "testFood", testBaseNutrition); + Food food = Food.createFood("testFood", user, testBaseNutrition); + food.setId(2L); - //when - BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); - foodService.updateFavoriteFood(UpdateFavoriteFoodDto.of(favoriteFoodId, "testChangedFood", testChangedBaseNutrition)); - - FavoriteFood changedFood = favoriteFoodRepository.getReferenceById(favoriteFoodId); - - assertNotNull(changedFood); - assertEquals("testChangedFood", changedFood.getName()); - assertEquals(2,changedFood.getBaseNutrition().getKcal()); - assertEquals(3,changedFood.getBaseNutrition().getCarbohydrate()); - assertEquals(4,changedFood.getBaseNutrition().getProtein()); - assertEquals(5,changedFood.getBaseNutrition().getFat()); - } - - @Test - void testDeleteFavoriteFood() { - //given - BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); - Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); - Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); + given(userRepository.findById(any(Long.class))).willReturn(Optional.of(user)); + given(foodRepository.save(any(Food.class))).willReturn(food); + given(foodRepository.findAllByUserIdAndDate(any(Long.class), any(LocalDate.class))).willReturn(List.of(food)); //when - foodService.deleteFavoriteFood(favoriteFoodId); + Long foodId = foodService.saveFood(createFoodDto); - assertNull(favoriteFoodRepository.findById(favoriteFoodId).orElse(null)); - } + List responseFoodDtoList = foodService.getFoodListByDate(user.getId(), food.getDate()); - @Test - void testNutritionSumByDate(){ - //given - BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword",1, 180, 80, 18)); - Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood", testFoodNutrition)); - Food food = foodRepository.getReferenceById(foodId); - - //when - ResponseNutritionSumByDateDto responseNutritionSumByDateDto = foodService.getNutritionSumByDate(userId,food.getDate()); - assertEquals(1400, responseNutritionSumByDateDto.getTotalKcal()); - assertEquals(150, responseNutritionSumByDateDto.getTotalCarbohydrate()); - assertEquals(200, responseNutritionSumByDateDto.getTotalProtein()); - assertEquals(250, responseNutritionSumByDateDto.getTotalFat()); - - assertEquals(Math.round((((double)1400 / (double)2000) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioKcal()); - assertEquals(Math.round((((double)150 / (double)300) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioCarbohydrate()); - assertEquals(Math.round((((double)200 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioProtein()); - assertEquals(Math.round((((double)250 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioFat()); - } - - @Test - void testNutritionSumByWeekAndMonth(){ - //given - BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(100,150,200,250); - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword",1, 180, 80, 18)); - Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood", testFoodNutrition)); - - } - - @Test - void getBest3FoodTest() { - // given - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword", 1, 180, 80, 18)); - foodService.saveFood(CreateFoodDto.of(userId, "Food1", BaseNutrition.createNutrition(100, 100 ,10, 1))); - foodService.saveFood(CreateFoodDto.of(userId, "Food2", BaseNutrition.createNutrition(100, 100 ,8, 2))); - foodService.saveFood(CreateFoodDto.of(userId, "Food3", BaseNutrition.createNutrition(100, 100 ,6, 3))); - foodService.saveFood(CreateFoodDto.of(userId, "Food4", BaseNutrition.createNutrition(100, 100 ,4, 4))); - foodService.saveFood(CreateFoodDto.of(userId, "Food5", BaseNutrition.createNutrition(100, 100 ,2, 5))); - - - // when - ResponseFoodRankDto response = foodService.getBestFoodByWeek(userId); - List top3Foods = response.getRankFoodList(); - - // then - assertEquals(3, top3Foods.size()); - assertEquals("Food1", top3Foods.get(0).getName()); - assertEquals("Food2", top3Foods.get(1).getName()); - assertEquals("Food3", top3Foods.get(2).getName()); + assertEquals(2L, foodId); + assertEquals("testFood",responseFoodDtoList.get(0).getName()); + verify(foodRepository, times(1)).save(any(Food.class)); } - @Test - void getWorst3FoodsTest() { - // given - Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword", 1, 180, 80, 18)); - foodService.saveFood(CreateFoodDto.of(userId, "Food1", BaseNutrition.createNutrition(100, 50 ,10, 1))); - foodService.saveFood(CreateFoodDto.of(userId, "Food2", BaseNutrition.createNutrition(100, 100 ,8, 20))); - foodService.saveFood(CreateFoodDto.of(userId, "Food3", BaseNutrition.createNutrition(100, 80 ,6, 7))); - foodService.saveFood(CreateFoodDto.of(userId, "Food4", BaseNutrition.createNutrition(100, 100 ,4, 5))); - foodService.saveFood(CreateFoodDto.of(userId, "Food5", BaseNutrition.createNutrition(100, 90 ,2, 6))); - - - // when - ResponseFoodRankDto response = foodService.getWorstFoodByWeek(userId); - List top3Foods = response.getRankFoodList(); - - // then - assertEquals(3, top3Foods.size()); - assertEquals("Food2", top3Foods.get(0).getName()); - assertEquals("Food4", top3Foods.get(1).getName()); - assertEquals("Food5", top3Foods.get(2).getName()); - } +// @Test +// void testUpdateFood() { +// //given +// BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); +// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); +// Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); +// +// //when +// BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); +// foodService.updateFood(UpdateFoodDto.of(foodId, "testChangedFood", testChangedBaseNutrition)); +// +// Food changedFood = foodRepository.getReferenceById(foodId); +// +// assertNotNull(changedFood); +// assertEquals("testChangedFood", changedFood.getName()); +// assertEquals(2,changedFood.getBaseNutrition().getKcal()); +// assertEquals(3,changedFood.getBaseNutrition().getCarbohydrate()); +// assertEquals(4,changedFood.getBaseNutrition().getProtein()); +// assertEquals(5,changedFood.getBaseNutrition().getFat()); +// } +// +// @Test +// void testDeleteFood() { +// //given +// BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); +// Long userId = userService.saveUser(CreateUserDto.of("testUser","testImage", "tessPassword", 1, 180, 80, 18)); +// Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); +// +// //when +// foodService.deleteFood(foodId); +// +// assertNull(foodRepository.findById(foodId).orElse(null)); +// } +// +// @Test +// void testSaveAndGetFavoriteFood() { +// //given +// BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); +// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); +// Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); +// +// //when +// Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); +// +// List responseFavoriteFoodDtoList = foodService.getFavoriteFoodList(userId); +// +// assertNotNull(responseFavoriteFoodDtoList); +// assertEquals("testFood",responseFavoriteFoodDtoList.get(0).getName()); +// } +// +// @Test +// void testUpdateFavoriteFood() { +// //given +// BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); +// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); +// Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); +// Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); +// +// +// //when +// BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); +// foodService.updateFavoriteFood(UpdateFavoriteFoodDto.of(favoriteFoodId, "testChangedFood", testChangedBaseNutrition)); +// +// FavoriteFood changedFood = favoriteFoodRepository.getReferenceById(favoriteFoodId); +// +// assertNotNull(changedFood); +// assertEquals("testChangedFood", changedFood.getName()); +// assertEquals(2,changedFood.getBaseNutrition().getKcal()); +// assertEquals(3,changedFood.getBaseNutrition().getCarbohydrate()); +// assertEquals(4,changedFood.getBaseNutrition().getProtein()); +// assertEquals(5,changedFood.getBaseNutrition().getFat()); +// } +// +// @Test +// void testDeleteFavoriteFood() { +// //given +// BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); +// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); +// Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); +// Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); +// +// //when +// foodService.deleteFavoriteFood(favoriteFoodId); +// +// assertNull(favoriteFoodRepository.findById(favoriteFoodId).orElse(null)); +// } +// +// @Test +// void testNutritionSumByDate(){ +// //given +// BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); +// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword",1, 180, 80, 18)); +// Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood", testFoodNutrition)); +// Food food = foodRepository.getReferenceById(foodId); +// +// //when +// ResponseNutritionSumByDateDto responseNutritionSumByDateDto = foodService.getNutritionSumByDate(userId,food.getDate()); +// assertEquals(1400, responseNutritionSumByDateDto.getTotalKcal()); +// assertEquals(150, responseNutritionSumByDateDto.getTotalCarbohydrate()); +// assertEquals(200, responseNutritionSumByDateDto.getTotalProtein()); +// assertEquals(250, responseNutritionSumByDateDto.getTotalFat()); +// +// assertEquals(Math.round((((double)1400 / (double)2000) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioKcal()); +// assertEquals(Math.round((((double)150 / (double)300) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioCarbohydrate()); +// assertEquals(Math.round((((double)200 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioProtein()); +// assertEquals(Math.round((((double)250 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioFat()); +// } +// +// @Test +// void testNutritionSumByWeekAndMonth(){ +// //given +// BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(100,150,200,250); +// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword",1, 180, 80, 18)); +// Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood", testFoodNutrition)); +// +// } +// +// @Test +// void getBest3FoodTest() { +// // given +// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword", 1, 180, 80, 18)); +// foodService.saveFood(CreateFoodDto.of(userId, "Food1", BaseNutrition.createNutrition(100, 100 ,10, 1))); +// foodService.saveFood(CreateFoodDto.of(userId, "Food2", BaseNutrition.createNutrition(100, 100 ,8, 2))); +// foodService.saveFood(CreateFoodDto.of(userId, "Food3", BaseNutrition.createNutrition(100, 100 ,6, 3))); +// foodService.saveFood(CreateFoodDto.of(userId, "Food4", BaseNutrition.createNutrition(100, 100 ,4, 4))); +// foodService.saveFood(CreateFoodDto.of(userId, "Food5", BaseNutrition.createNutrition(100, 100 ,2, 5))); +// +// +// // when +// ResponseFoodRankDto response = foodService.getBestFoodByWeek(userId); +// List top3Foods = response.getRankFoodList(); +// +// // then +// assertEquals(3, top3Foods.size()); +// assertEquals("Food1", top3Foods.get(0).getName()); +// assertEquals("Food2", top3Foods.get(1).getName()); +// assertEquals("Food3", top3Foods.get(2).getName()); +// } +// +// @Test +// void getWorst3FoodsTest() { +// // given +// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword", 1, 180, 80, 18)); +// foodService.saveFood(CreateFoodDto.of(userId, "Food1", BaseNutrition.createNutrition(100, 50 ,10, 1))); +// foodService.saveFood(CreateFoodDto.of(userId, "Food2", BaseNutrition.createNutrition(100, 100 ,8, 20))); +// foodService.saveFood(CreateFoodDto.of(userId, "Food3", BaseNutrition.createNutrition(100, 80 ,6, 7))); +// foodService.saveFood(CreateFoodDto.of(userId, "Food4", BaseNutrition.createNutrition(100, 100 ,4, 5))); +// foodService.saveFood(CreateFoodDto.of(userId, "Food5", BaseNutrition.createNutrition(100, 90 ,2, 6))); +// +// +// // when +// ResponseFoodRankDto response = foodService.getWorstFoodByWeek(userId); +// List top3Foods = response.getRankFoodList(); +// +// // then +// assertEquals(3, top3Foods.size()); +// assertEquals("Food2", top3Foods.get(0).getName()); +// assertEquals("Food4", top3Foods.get(1).getName()); +// assertEquals("Food5", top3Foods.get(2).getName()); +// } } From 30d7c11497113dfd764012190e7889d2b6fb81e0 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 22:21:44 +0900 Subject: [PATCH 098/371] :recycle: refactor: testUpdateFood() mocking (#29) --- .../diareat/service/FoodServiceTest.java | 48 ++++++++++--------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 652e35f..ff62b90 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -52,8 +52,7 @@ class FoodServiceTest { void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리스트 불러오기 // given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); - CreateUserDto createUserDto = CreateUserDto.of("testUser", "testImage","testPassword", 1,180, 80,18); - User user = User.createUser(createUserDto.getName(), createUserDto.getImage(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), testBaseNutrition); + User user = User.createUser("testUser", "testImage","testPassword", 1,180, 80,18, testBaseNutrition); user.setId(1L); CreateFoodDto createFoodDto = CreateFoodDto.of(user.getId(), "testFood", testBaseNutrition); @@ -74,26 +73,31 @@ void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리 verify(foodRepository, times(1)).save(any(Food.class)); } -// @Test -// void testUpdateFood() { -// //given -// BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); -// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); -// Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); -// -// //when -// BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); -// foodService.updateFood(UpdateFoodDto.of(foodId, "testChangedFood", testChangedBaseNutrition)); -// -// Food changedFood = foodRepository.getReferenceById(foodId); -// -// assertNotNull(changedFood); -// assertEquals("testChangedFood", changedFood.getName()); -// assertEquals(2,changedFood.getBaseNutrition().getKcal()); -// assertEquals(3,changedFood.getBaseNutrition().getCarbohydrate()); -// assertEquals(4,changedFood.getBaseNutrition().getProtein()); -// assertEquals(5,changedFood.getBaseNutrition().getFat()); -// } + @Test + void testUpdateFood() { + //given + BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); + User user = User.createUser("testUser", "testImage","tessPassword", 1, 180, 80, 18, testBaseNutrition); + Food food = Food.createFood("testFood", user, testBaseNutrition); + food.setId(1L); + + given(foodRepository.findById(any(Long.class))).willReturn(Optional.of(food)); + given(foodRepository.getReferenceById(any(Long.class))).willReturn(food); + + + //when + BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); + foodService.updateFood(UpdateFoodDto.of(food.getId(), "testChangedFood", testChangedBaseNutrition)); + + Food changedFood = foodRepository.getReferenceById(food.getId()); + + assertNotNull(changedFood); + assertEquals("testChangedFood", changedFood.getName()); + assertEquals(2,changedFood.getBaseNutrition().getKcal()); + assertEquals(3,changedFood.getBaseNutrition().getCarbohydrate()); + assertEquals(4,changedFood.getBaseNutrition().getProtein()); + assertEquals(5,changedFood.getBaseNutrition().getFat()); + } // // @Test // void testDeleteFood() { From 2ec2700dd81f9f1cc478e7e909a497f06481722f Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 22:41:32 +0900 Subject: [PATCH 099/371] :recycle: refactor: testDeleteFood() mocking (#29) --- .../diareat/service/FoodServiceTest.java | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index ff62b90..fc8ecaf 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -59,7 +59,7 @@ void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리 Food food = Food.createFood("testFood", user, testBaseNutrition); food.setId(2L); - given(userRepository.findById(any(Long.class))).willReturn(Optional.of(user)); + given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); given(foodRepository.save(any(Food.class))).willReturn(food); given(foodRepository.findAllByUserIdAndDate(any(Long.class), any(LocalDate.class))).willReturn(List.of(food)); @@ -81,8 +81,8 @@ void testUpdateFood() { Food food = Food.createFood("testFood", user, testBaseNutrition); food.setId(1L); - given(foodRepository.findById(any(Long.class))).willReturn(Optional.of(food)); - given(foodRepository.getReferenceById(any(Long.class))).willReturn(food); + given(foodRepository.findById(food.getId())).willReturn(Optional.of(food)); + given(foodRepository.getReferenceById(food.getId())).willReturn(food); //when @@ -99,19 +99,20 @@ void testUpdateFood() { assertEquals(5,changedFood.getBaseNutrition().getFat()); } // -// @Test -// void testDeleteFood() { -// //given -// BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); -// Long userId = userService.saveUser(CreateUserDto.of("testUser","testImage", "tessPassword", 1, 180, 80, 18)); -// Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); -// -// //when -// foodService.deleteFood(foodId); -// -// assertNull(foodRepository.findById(foodId).orElse(null)); -// } -// + @Test + void testDeleteFood() { + //given + BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); + User user = User.createUser("testUser", "testImage","tessPassword", 1, 180, 80, 18, testBaseNutrition); + Food food = Food.createFood("testFood", user, testBaseNutrition); + food.setId(1L); + + //when + foodService.deleteFood(food.getId()); + + verify(foodRepository, times(1)).deleteById(food.getId()); + } + // @Test // void testSaveAndGetFavoriteFood() { // //given From 2e85c3a6145953d746789bb7326edb0478fe8210 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 22:54:03 +0900 Subject: [PATCH 100/371] =?UTF-8?q?:recycle:=20refactor:=20User=20?= =?UTF-8?q?=ED=99=95=EC=9D=B8=EC=9D=84=20=EC=9C=84=ED=95=9C=20validateUser?= =?UTF-8?q?()=20=EC=B6=94=EA=B0=80=20(#29)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 19 ++++++++++++++++++- 1 file changed, 18 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 f339d56..ce7d9d8 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -15,7 +15,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.rmi.registry.LocateRegistry; import java.time.LocalDate; import java.util.Comparator; import java.util.List; @@ -41,6 +40,7 @@ public Long saveFood(CreateFoodDto createFoodDto) { // 회원이 특정 날짜에 먹은 음식 반환 @Transactional(readOnly = true) public List getFoodListByDate(Long userId, LocalDate date){ + validateUser(userId); List foodList = foodRepository.findAllByUserIdAndDate(userId, date); return foodList.stream() .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getDate(), food.getTime(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); @@ -57,6 +57,7 @@ public void updateFood(UpdateFoodDto updateFoodDto) { // 음식 삭제 @Transactional public void deleteFood(Long foodId) { + validateFood(foodId); foodRepository.deleteById(foodId); } @@ -73,6 +74,7 @@ public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { //즐겨찾기 음식 리스트 반환 @Transactional(readOnly = true) public List getFavoriteFoodList(Long userId){ + validateUser(userId); List foodList = favoriteFoodRepository.findAllByUserId(userId); return foodList.stream() .map(favoriteFood -> ResponseFavoriteFoodDto.of(favoriteFood.getId(), favoriteFood.getName(), @@ -95,6 +97,7 @@ public void deleteFavoriteFood(Long favoriteFoodId) { @Transactional(readOnly = true) // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { + validateUser(userId); List foodList = foodRepository.findAllByUserIdAndDate(userId, date); return calculateNutritionSumAndRatio(userId, foodList, date, 1); } @@ -102,6 +105,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDat @Transactional(readOnly = true) // 유저의 최근 7일간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { + validateUser(userId); LocalDate endDate = LocalDate.now(); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); @@ -111,6 +115,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { @Transactional(readOnly = true) // 유저의 최근 1개월간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { + validateUser(userId); LocalDate endDate = LocalDate.now(); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); @@ -120,6 +125,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { @Transactional(readOnly = true) // 유저의 최근 7일간의 Best 3 음식 조회 (dto 구체적 협의 필요) public ResponseFoodRankDto getBestFoodByWeek(Long userId) { + validateUser(userId); LocalDate endDate = LocalDate.now(); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); @@ -140,6 +146,7 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId) { @Transactional(readOnly = true) // 유저의 최근 7일간의 Worst 3 음식 조회 (dto 구체적 협의 필요) public ResponseFoodRankDto getWorstFoodByWeek(Long userId) { + validateUser(userId); LocalDate endDate = LocalDate.now(); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); @@ -198,6 +205,16 @@ private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, return ResponseNutritionSumByDateDto.of(userId, checkDate, nutritionSumType, totalKcal,totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); } + private void validateUser(Long userId) { + if (!userRepository.existsById(userId)) + throw new UserException(ResponseCode.USER_NOT_FOUND); + } + + private void validateFood(Long foodId) { + if (!foodRepository.existsById(foodId)) + throw new UserException(ResponseCode.FOOD_NOT_FOUND); + } + /** * 메서드 구현 유의사항 From 48664dbfc2333a88f3849c2e7eb428d1156793a1 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 22:57:36 +0900 Subject: [PATCH 101/371] =?UTF-8?q?:recycle:=20refactor:=20validateUser(),?= =?UTF-8?q?=20validateFood()=20=EC=B6=94=EA=B0=80=EC=97=90=20=EB=94=B0?= =?UTF-8?q?=EB=A5=B8=20testCode=20=EC=88=98=EC=A0=95=20(#29)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/com/diareat/diareat/service/FoodServiceTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index fc8ecaf..d916833 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -60,6 +60,7 @@ void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리 food.setId(2L); given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); + given(userRepository.existsById(user.getId())).willReturn(true); given(foodRepository.save(any(Food.class))).willReturn(food); given(foodRepository.findAllByUserIdAndDate(any(Long.class), any(LocalDate.class))).willReturn(List.of(food)); @@ -107,6 +108,8 @@ void testDeleteFood() { Food food = Food.createFood("testFood", user, testBaseNutrition); food.setId(1L); + given(foodRepository.existsById(food.getId())).willReturn(true); + //when foodService.deleteFood(food.getId()); From 34f7762eb32b7073080a9291739beb6c3b014426 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 23:10:52 +0900 Subject: [PATCH 102/371] :recycle: refactor: testSaveAndGetFavoriteFood() mocking (#29) --- .../diareat/food/domain/FavoriteFood.java | 4 ++ .../diareat/food/service/FoodService.java | 6 +++ .../diareat/service/FoodServiceTest.java | 40 ++++++++++++------- 3 files changed, 35 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java index ca1f811..266256a 100644 --- a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java +++ b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java @@ -55,4 +55,8 @@ public static Food createFoodFromFavoriteFood(FavoriteFood favoriteFood) { favoriteFood.addCount(); return Food.createFood(favoriteFood.getName(), favoriteFood.getUser(), favoriteFood.getBaseNutrition()); } + + public void setId(Long id) { + this.id = id; + } } 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 ce7d9d8..f4792c4 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -91,6 +91,7 @@ public void updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto) { // 즐겨찾기 해제 @Transactional public void deleteFavoriteFood(Long favoriteFoodId) { + validateFavoriteFood(favoriteFoodId); favoriteFoodRepository.deleteById(favoriteFoodId); } @@ -215,6 +216,11 @@ private void validateFood(Long foodId) { throw new UserException(ResponseCode.FOOD_NOT_FOUND); } + private void validateFavoriteFood(Long favoriteFoodId) { + if (!foodRepository.existsById(favoriteFoodId)) + throw new UserException(ResponseCode.FAVORITE_NOT_FOUND); + } + /** * 메서드 구현 유의사항 diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index d916833..84ec537 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -1,5 +1,6 @@ package com.diareat.diareat.service; +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.repository.FavoriteFoodRepository; @@ -116,21 +117,30 @@ void testDeleteFood() { verify(foodRepository, times(1)).deleteById(food.getId()); } -// @Test -// void testSaveAndGetFavoriteFood() { -// //given -// BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); -// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); -// Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); -// -// //when -// Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); -// -// List responseFavoriteFoodDtoList = foodService.getFavoriteFoodList(userId); -// -// assertNotNull(responseFavoriteFoodDtoList); -// assertEquals("testFood",responseFavoriteFoodDtoList.get(0).getName()); -// } + @Test + void testSaveAndGetFavoriteFood() { + BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); + User user = User.createUser("testUser", "testImage","testPassword", 1,180, 80,18, testBaseNutrition); + FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("testFavoriteFood", user, testBaseNutrition); + user.setId(1L); + favoriteFood.setId(3L); + + CreateFavoriteFoodDto createFavoriteFoodDto = CreateFavoriteFoodDto.of(favoriteFood.getId(), user.getId(),"testFood", testBaseNutrition); + + given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); + given(userRepository.existsById(user.getId())).willReturn(true); + given(favoriteFoodRepository.save(any(FavoriteFood.class))).willReturn(favoriteFood); + given(favoriteFoodRepository.findAllByUserId(any(Long.class))).willReturn(List.of(favoriteFood)); + + //when + Long foodId = foodService.saveFavoriteFood(createFavoriteFoodDto); + + List responseFavoriteFoodDtoList = foodService.getFavoriteFoodList(user.getId()); + + assertEquals(3L, foodId); + assertEquals("testFavoriteFood",responseFavoriteFoodDtoList.get(0).getName()); + verify(favoriteFoodRepository, times(1)).save(any(FavoriteFood.class)); + } // // @Test // void testUpdateFavoriteFood() { From 76f95db9da30df8cb77fc85b3a86603b11954660 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 23:17:52 +0900 Subject: [PATCH 103/371] :recycle: refactor: testUpdateFavoriteFood() mocking (#29) --- .../diareat/service/FoodServiceTest.java | 57 +++++++++---------- 1 file changed, 26 insertions(+), 31 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 84ec537..9441077 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -84,21 +84,18 @@ void testUpdateFood() { food.setId(1L); given(foodRepository.findById(food.getId())).willReturn(Optional.of(food)); - given(foodRepository.getReferenceById(food.getId())).willReturn(food); //when BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); foodService.updateFood(UpdateFoodDto.of(food.getId(), "testChangedFood", testChangedBaseNutrition)); - Food changedFood = foodRepository.getReferenceById(food.getId()); - assertNotNull(changedFood); - assertEquals("testChangedFood", changedFood.getName()); - assertEquals(2,changedFood.getBaseNutrition().getKcal()); - assertEquals(3,changedFood.getBaseNutrition().getCarbohydrate()); - assertEquals(4,changedFood.getBaseNutrition().getProtein()); - assertEquals(5,changedFood.getBaseNutrition().getFat()); + assertEquals("testChangedFood", food.getName()); + assertEquals(2,food.getBaseNutrition().getKcal()); + assertEquals(3,food.getBaseNutrition().getCarbohydrate()); + assertEquals(4,food.getBaseNutrition().getProtein()); + assertEquals(5,food.getBaseNutrition().getFat()); } // @Test @@ -141,29 +138,27 @@ void testSaveAndGetFavoriteFood() { assertEquals("testFavoriteFood",responseFavoriteFoodDtoList.get(0).getName()); verify(favoriteFoodRepository, times(1)).save(any(FavoriteFood.class)); } -// -// @Test -// void testUpdateFavoriteFood() { -// //given -// BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); -// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); -// Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); -// Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); -// -// -// //when -// BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); -// foodService.updateFavoriteFood(UpdateFavoriteFoodDto.of(favoriteFoodId, "testChangedFood", testChangedBaseNutrition)); -// -// FavoriteFood changedFood = favoriteFoodRepository.getReferenceById(favoriteFoodId); -// -// assertNotNull(changedFood); -// assertEquals("testChangedFood", changedFood.getName()); -// assertEquals(2,changedFood.getBaseNutrition().getKcal()); -// assertEquals(3,changedFood.getBaseNutrition().getCarbohydrate()); -// assertEquals(4,changedFood.getBaseNutrition().getProtein()); -// assertEquals(5,changedFood.getBaseNutrition().getFat()); -// } + @Test + void testUpdateFavoriteFood() { + //given + BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); + User user = User.createUser("testUser", "testImage","tessPassword", 1, 180, 80, 18, testBaseNutrition); + FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("testFavoriteFood", user, testBaseNutrition); + favoriteFood.setId(1L); + + given(favoriteFoodRepository.findById(favoriteFood.getId())).willReturn(Optional.of(favoriteFood)); + + + //when + BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); + foodService.updateFavoriteFood(UpdateFavoriteFoodDto.of(favoriteFood.getId(), "testChangedFood", testChangedBaseNutrition)); + + assertEquals("testChangedFood", favoriteFood.getName()); + assertEquals(2,favoriteFood.getBaseNutrition().getKcal()); + assertEquals(3,favoriteFood.getBaseNutrition().getCarbohydrate()); + assertEquals(4,favoriteFood.getBaseNutrition().getProtein()); + assertEquals(5,favoriteFood.getBaseNutrition().getFat()); + } // // @Test // void testDeleteFavoriteFood() { From 7d3ee8bc7fbd463b47aa93c415aedb66ca1a0e1a Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 23:22:33 +0900 Subject: [PATCH 104/371] =?UTF-8?q?:pencil2:=20fix:=20=EC=9E=98=EB=AA=BB?= =?UTF-8?q?=EB=90=9C=20Exception=20Type=20=EC=88=98=EC=A0=95=20(#29)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/service/FoodService.java | 7 ++++--- 1 file changed, 4 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 f4792c4..d9b5a58 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -9,6 +9,7 @@ import com.diareat.diareat.user.domain.User; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.util.api.ResponseCode; +import com.diareat.diareat.util.exception.FavoriteException; import com.diareat.diareat.util.exception.FoodException; import com.diareat.diareat.util.exception.UserException; import lombok.RequiredArgsConstructor; @@ -213,12 +214,12 @@ private void validateUser(Long userId) { private void validateFood(Long foodId) { if (!foodRepository.existsById(foodId)) - throw new UserException(ResponseCode.FOOD_NOT_FOUND); + throw new FoodException(ResponseCode.FOOD_NOT_FOUND); } private void validateFavoriteFood(Long favoriteFoodId) { - if (!foodRepository.existsById(favoriteFoodId)) - throw new UserException(ResponseCode.FAVORITE_NOT_FOUND); + if (!favoriteFoodRepository.existsById(favoriteFoodId)) + throw new FavoriteException(ResponseCode.FAVORITE_NOT_FOUND); } From 200e5f3669cf5ae8e8944c024fc0a403d7a3e304 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 23:22:56 +0900 Subject: [PATCH 105/371] :recycle: refactor: testDeleteFavoriteFood() mocking (#29) --- .../diareat/service/FoodServiceTest.java | 28 ++++++++++--------- 1 file changed, 15 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 9441077..3bb9c9a 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -160,19 +160,21 @@ void testUpdateFavoriteFood() { assertEquals(5,favoriteFood.getBaseNutrition().getFat()); } // -// @Test -// void testDeleteFavoriteFood() { -// //given -// BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); -// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","tessPassword", 1, 180, 80, 18)); -// Long foodId = foodService.saveFood(CreateFoodDto.of(userId, "testFood", testBaseNutrition)); -// Long favoriteFoodId = foodService.saveFavoriteFood(CreateFavoriteFoodDto.of(foodId, userId, "testFood", testBaseNutrition)); -// -// //when -// foodService.deleteFavoriteFood(favoriteFoodId); -// -// assertNull(favoriteFoodRepository.findById(favoriteFoodId).orElse(null)); -// } + @Test + void testDeleteFavoriteFood() { + //given + BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); + User user = User.createUser("testUser", "testImage","tessPassword", 1, 180, 80, 18, testBaseNutrition); + FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("testFood", user, testBaseNutrition); + favoriteFood.setId(1L); + + given(favoriteFoodRepository.existsById(favoriteFood.getId())).willReturn(true); + + //when + foodService.deleteFavoriteFood(favoriteFood.getId()); + + verify(favoriteFoodRepository, times(1)).deleteById(favoriteFood.getId()); + } // // @Test // void testNutritionSumByDate(){ From 37042ae958d941f0f922456b2a53810b0476afea Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 23:28:38 +0900 Subject: [PATCH 106/371] :recycle: refactor: testNutritionSumByDate() mocking (#29) --- .../diareat/service/FoodServiceTest.java | 46 +++++++++++-------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 3bb9c9a..323b256 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -176,26 +176,32 @@ void testDeleteFavoriteFood() { verify(favoriteFoodRepository, times(1)).deleteById(favoriteFood.getId()); } // -// @Test -// void testNutritionSumByDate(){ -// //given -// BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); -// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword",1, 180, 80, 18)); -// Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood", testFoodNutrition)); -// Food food = foodRepository.getReferenceById(foodId); -// -// //when -// ResponseNutritionSumByDateDto responseNutritionSumByDateDto = foodService.getNutritionSumByDate(userId,food.getDate()); -// assertEquals(1400, responseNutritionSumByDateDto.getTotalKcal()); -// assertEquals(150, responseNutritionSumByDateDto.getTotalCarbohydrate()); -// assertEquals(200, responseNutritionSumByDateDto.getTotalProtein()); -// assertEquals(250, responseNutritionSumByDateDto.getTotalFat()); -// -// assertEquals(Math.round((((double)1400 / (double)2000) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioKcal()); -// assertEquals(Math.round((((double)150 / (double)300) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioCarbohydrate()); -// assertEquals(Math.round((((double)200 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioProtein()); -// assertEquals(Math.round((((double)250 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioFat()); -// } + @Test + void testNutritionSumByDate(){ + //given + BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); + User user = User.createUser("testUser", "testImage","testPassword",1, 180, 80, 18, BaseNutrition.createNutrition(2000,300,80,80)); + user.setId(1L); + Food food = Food.createFood("testFood", user, testFoodNutrition); + food.setId(2L); + + given(userRepository.existsById(user.getId())).willReturn(true); + given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); + given(foodRepository.findAllByUserIdAndDate(any(Long.class), any(LocalDate.class))).willReturn(List.of(food)); + + + //when + ResponseNutritionSumByDateDto responseNutritionSumByDateDto = foodService.getNutritionSumByDate(user.getId(),food.getDate()); + assertEquals(1400, responseNutritionSumByDateDto.getTotalKcal()); + assertEquals(150, responseNutritionSumByDateDto.getTotalCarbohydrate()); + assertEquals(200, responseNutritionSumByDateDto.getTotalProtein()); + assertEquals(250, responseNutritionSumByDateDto.getTotalFat()); + + assertEquals(Math.round((((double)1400 / (double)2000) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioKcal()); + assertEquals(Math.round((((double)150 / (double)300) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioCarbohydrate()); + assertEquals(Math.round((((double)200 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioProtein()); + assertEquals(Math.round((((double)250 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioFat()); + } // // @Test // void testNutritionSumByWeekAndMonth(){ From bbbedd779e43545092586816435bc4c734130558 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 23:32:40 +0900 Subject: [PATCH 107/371] :recycle: refactor: testNutritionSumByWeek(), testNutritionSumByMonth() mocking (#29) --- .../diareat/service/FoodServiceTest.java | 65 ++++++++++++++++--- 1 file changed, 57 insertions(+), 8 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 323b256..dc64e1a 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -203,14 +203,63 @@ void testNutritionSumByDate(){ assertEquals(Math.round((((double)250 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioFat()); } // -// @Test -// void testNutritionSumByWeekAndMonth(){ -// //given -// BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(100,150,200,250); -// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword",1, 180, 80, 18)); -// Long foodId = foodService.saveFood(CreateFoodDto.of(userId,"testFood", testFoodNutrition)); -// -// } + @Test + void testNutritionSumByWeek(){ + //given + BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); + User user = User.createUser("testUser", "testImage","testPassword",1, 180, 80, 18, BaseNutrition.createNutrition(2000,300,80,80)); + user.setId(1L); + Food food = Food.createFood("testFood", user, testFoodNutrition); + food.setId(2L); + + given(userRepository.existsById(user.getId())).willReturn(true); + given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); + given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(List.of(food)); + + + + //when + ResponseNutritionSumByDateDto responseNutritionSumByDateDto = foodService.getNutritionSumByWeek(user.getId()); + assertEquals(1400, responseNutritionSumByDateDto.getTotalKcal()); + assertEquals(150, responseNutritionSumByDateDto.getTotalCarbohydrate()); + assertEquals(200, responseNutritionSumByDateDto.getTotalProtein()); + assertEquals(250, responseNutritionSumByDateDto.getTotalFat()); + + assertEquals(Math.round((((double)1400 / (double)2000) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioKcal()); + assertEquals(Math.round((((double)150 / (double)300) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioCarbohydrate()); + assertEquals(Math.round((((double)200 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioProtein()); + assertEquals(Math.round((((double)250 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioFat()); + + } + + @Test + void testNutritionSumByMonth(){ + //given + BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); + User user = User.createUser("testUser", "testImage","testPassword",1, 180, 80, 18, BaseNutrition.createNutrition(2000,300,80,80)); + user.setId(1L); + Food food = Food.createFood("testFood", user, testFoodNutrition); + food.setId(2L); + + given(userRepository.existsById(user.getId())).willReturn(true); + given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); + given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(List.of(food)); + + + + //when + ResponseNutritionSumByDateDto responseNutritionSumByDateDto = foodService.getNutritionSumByMonth(user.getId()); + assertEquals(1400, responseNutritionSumByDateDto.getTotalKcal()); + assertEquals(150, responseNutritionSumByDateDto.getTotalCarbohydrate()); + assertEquals(200, responseNutritionSumByDateDto.getTotalProtein()); + assertEquals(250, responseNutritionSumByDateDto.getTotalFat()); + + assertEquals(Math.round((((double)1400 / (double)2000) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioKcal()); + assertEquals(Math.round((((double)150 / (double)300) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioCarbohydrate()); + assertEquals(Math.round((((double)200 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioProtein()); + assertEquals(Math.round((((double)250 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioFat()); + + } // // @Test // void getBest3FoodTest() { From 2db260a31e37568cdbe2bf081b6ec22af767022b Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 23:37:28 +0900 Subject: [PATCH 108/371] :recycle: refactor: getBest3FoodTest() mocking (#29) --- .../diareat/service/FoodServiceTest.java | 47 ++++++++++--------- 1 file changed, 26 insertions(+), 21 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index dc64e1a..eff6895 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -261,27 +261,32 @@ void testNutritionSumByMonth(){ } // -// @Test -// void getBest3FoodTest() { -// // given -// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword", 1, 180, 80, 18)); -// foodService.saveFood(CreateFoodDto.of(userId, "Food1", BaseNutrition.createNutrition(100, 100 ,10, 1))); -// foodService.saveFood(CreateFoodDto.of(userId, "Food2", BaseNutrition.createNutrition(100, 100 ,8, 2))); -// foodService.saveFood(CreateFoodDto.of(userId, "Food3", BaseNutrition.createNutrition(100, 100 ,6, 3))); -// foodService.saveFood(CreateFoodDto.of(userId, "Food4", BaseNutrition.createNutrition(100, 100 ,4, 4))); -// foodService.saveFood(CreateFoodDto.of(userId, "Food5", BaseNutrition.createNutrition(100, 100 ,2, 5))); -// -// -// // when -// ResponseFoodRankDto response = foodService.getBestFoodByWeek(userId); -// List top3Foods = response.getRankFoodList(); -// -// // then -// assertEquals(3, top3Foods.size()); -// assertEquals("Food1", top3Foods.get(0).getName()); -// assertEquals("Food2", top3Foods.get(1).getName()); -// assertEquals("Food3", top3Foods.get(2).getName()); -// } + @Test + void getBest3FoodTest() { + // given + User user = User.createUser("testUser", "testImage","testPassword", 1, 180, 80, 18, BaseNutrition.createNutrition(1,1,1,1)); + 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(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(foodList); + given(userRepository.existsById(user.getId())).willReturn(true); + + // when + ResponseFoodRankDto response = foodService.getBestFoodByWeek(user.getId()); + List top3Foods = response.getRankFoodList(); + + // then + assertEquals(3, top3Foods.size()); + assertEquals("Food1", top3Foods.get(0).getName()); + assertEquals("Food2", top3Foods.get(1).getName()); + assertEquals("Food3", top3Foods.get(2).getName()); + } // // @Test // void getWorst3FoodsTest() { From 448cbe3125685d63fe173e438e35dab403421b0b Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 23:38:53 +0900 Subject: [PATCH 109/371] :recycle: refactor: getWorst3FoodsTest() mocking (#29) --- .../diareat/service/FoodServiceTest.java | 47 ++++++++++--------- 1 file changed, 26 insertions(+), 21 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index eff6895..36e30e0 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -288,25 +288,30 @@ void getBest3FoodTest() { assertEquals("Food3", top3Foods.get(2).getName()); } // -// @Test -// void getWorst3FoodsTest() { -// // given -// Long userId = userService.saveUser(CreateUserDto.of("testUser", "testImage","testPassword", 1, 180, 80, 18)); -// foodService.saveFood(CreateFoodDto.of(userId, "Food1", BaseNutrition.createNutrition(100, 50 ,10, 1))); -// foodService.saveFood(CreateFoodDto.of(userId, "Food2", BaseNutrition.createNutrition(100, 100 ,8, 20))); -// foodService.saveFood(CreateFoodDto.of(userId, "Food3", BaseNutrition.createNutrition(100, 80 ,6, 7))); -// foodService.saveFood(CreateFoodDto.of(userId, "Food4", BaseNutrition.createNutrition(100, 100 ,4, 5))); -// foodService.saveFood(CreateFoodDto.of(userId, "Food5", BaseNutrition.createNutrition(100, 90 ,2, 6))); -// -// -// // when -// ResponseFoodRankDto response = foodService.getWorstFoodByWeek(userId); -// List top3Foods = response.getRankFoodList(); -// -// // then -// assertEquals(3, top3Foods.size()); -// assertEquals("Food2", top3Foods.get(0).getName()); -// assertEquals("Food4", top3Foods.get(1).getName()); -// assertEquals("Food5", top3Foods.get(2).getName()); -// } + @Test + void getWorst3FoodsTest() { + // given + User user = User.createUser("testUser", "testImage","testPassword", 1, 180, 80, 18, BaseNutrition.createNutrition(1,1,1,1)); + Food food1 = Food.createFood( "Food1", user, BaseNutrition.createNutrition(100, 50 ,10, 1)); + Food food2 = Food.createFood( "Food2", user, BaseNutrition.createNutrition(100, 100 ,8, 20)); + Food food3 = Food.createFood( "Food3", user, BaseNutrition.createNutrition(100, 80 ,6, 7)); + Food food4 = Food.createFood( "Food4", user, BaseNutrition.createNutrition(100, 100 ,4, 5)); + Food food5 = Food.createFood( "Food5", user, BaseNutrition.createNutrition(100, 90 ,2, 6)); + user.setId(1L); + + List foodList = List.of(food1, food2, food3, food4, food5); + + given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(foodList); + given(userRepository.existsById(user.getId())).willReturn(true); + + // when + ResponseFoodRankDto response = foodService.getWorstFoodByWeek(user.getId()); + List top3Foods = response.getRankFoodList(); + + // then + assertEquals(3, top3Foods.size()); + assertEquals("Food2", top3Foods.get(0).getName()); + assertEquals("Food4", top3Foods.get(1).getName()); + assertEquals("Food5", top3Foods.get(2).getName()); + } } From ffd4ecd0ac20db86a3a9dd8aab8a03a642c1368c Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 23:44:51 +0900 Subject: [PATCH 110/371] =?UTF-8?q?:recycle:=20refactor:=20=EB=B6=88?= =?UTF-8?q?=ED=95=84=EC=9A=94=ED=95=9C=20=EC=9D=98=EC=A1=B4=EC=84=B1=20?= =?UTF-8?q?=EC=A0=9C=EA=B1=B0=20(#29)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/com/diareat/diareat/service/FoodServiceTest.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 36e30e0..a40a8d3 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -36,9 +36,6 @@ class FoodServiceTest { @InjectMocks FoodService foodService; - @InjectMocks - UserService userService; - @Mock FoodRepository foodRepository; From 111c0f40192663c6f0f47bdcc801232d4779d929 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 15 Oct 2023 23:45:42 +0900 Subject: [PATCH 111/371] =?UTF-8?q?:recycle:=20refactor:=20=EB=B6=88?= =?UTF-8?q?=ED=95=84=EC=9A=94=ED=95=9C=20=EB=9D=BC=EC=9D=B4=EB=B8=8C?= =?UTF-8?q?=EB=9F=AC=EB=A6=AC=20=EC=A0=9C=EA=B1=B0=20(#29)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/com/diareat/diareat/service/FoodServiceTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index a40a8d3..31b9e8e 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -8,9 +8,7 @@ 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.CreateUserDto; import com.diareat.diareat.user.repository.UserRepository; -import com.diareat.diareat.user.service.UserService; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; From 4f15ff9a769c779d931152750d54448aedc9af4d Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 00:51:18 +0900 Subject: [PATCH 112/371] =?UTF-8?q?:heavy=5Fplus=5Fsign:=20Chore:=20?= =?UTF-8?q?=EB=A1=9C=EA=B7=B8=EC=9D=B8=20=EA=B4=80=EB=A0=A8=20=EC=9D=98?= =?UTF-8?q?=EC=A1=B4=EC=84=B1=20=EC=B6=94=EA=B0=80=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 4 ++++ .../com/diareat/diareat/auth/AuthService.java | 22 ------------------- 2 files changed, 4 insertions(+), 22 deletions(-) delete mode 100644 src/main/java/com/diareat/diareat/auth/AuthService.java diff --git a/build.gradle b/build.gradle index a33ed66..889b7f0 100644 --- a/build.gradle +++ b/build.gradle @@ -39,6 +39,10 @@ dependencies { // Swagger dependency implementation 'io.springfox:springfox-boot-starter:3.0.0' implementation 'io.springfox:springfox-swagger-ui:3.0.0' + + // Webclient dependency + implementation platform('org.springframework.boot:spring-boot-dependencies:2.5.4') // Replace with your Spring Boot version + implementation 'org.springframework.boot:spring-boot-starter-webflux' } tasks.named('test') { diff --git a/src/main/java/com/diareat/diareat/auth/AuthService.java b/src/main/java/com/diareat/diareat/auth/AuthService.java deleted file mode 100644 index cadde6e..0000000 --- a/src/main/java/com/diareat/diareat/auth/AuthService.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.diareat.diareat.auth; - -import com.diareat.diareat.user.repository.UserRepository; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -@RequiredArgsConstructor -@Service -public class AuthService { // 회원가입 및 로그인 기능 전담 - - private final UserRepository userRepository; - - // 회원가입 - public void signUp() { - - } - - // 로그인 - public void signIn() { - - } -} From 8c81c46cca1f945fa642f1e31f84eeb7e2dee3bc Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 00:52:23 +0900 Subject: [PATCH 113/371] =?UTF-8?q?:sparkles:=20Feat:=20=EC=B9=B4=EC=B9=B4?= =?UTF-8?q?=EC=98=A4=EB=A1=9C=EA=B7=B8=EC=9D=B8=20=EA=B4=80=EB=A0=A8=20?= =?UTF-8?q?=EA=B0=9D=EC=B2=B4=20=EC=B6=94=EA=B0=80=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/auth/component/KakaoUserInfo.java | 24 +++++++++++++++++++ .../diareat/auth/dto/KakaoAccount.java | 9 +++++++ .../diareat/auth/dto/KakaoProfile.java | 12 ++++++++++ .../auth/dto/KakaoUserInfoResponse.java | 11 +++++++++ 4 files changed, 56 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/auth/component/KakaoUserInfo.java create mode 100644 src/main/java/com/diareat/diareat/auth/dto/KakaoAccount.java create mode 100644 src/main/java/com/diareat/diareat/auth/dto/KakaoProfile.java create mode 100644 src/main/java/com/diareat/diareat/auth/dto/KakaoUserInfoResponse.java diff --git a/src/main/java/com/diareat/diareat/auth/component/KakaoUserInfo.java b/src/main/java/com/diareat/diareat/auth/component/KakaoUserInfo.java new file mode 100644 index 0000000..5727ffc --- /dev/null +++ b/src/main/java/com/diareat/diareat/auth/component/KakaoUserInfo.java @@ -0,0 +1,24 @@ +package com.diareat.diareat.auth.component; + +import com.diareat.diareat.auth.dto.KakaoUserInfoResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Flux; + +@RequiredArgsConstructor +@Component +public class KakaoUserInfo { + + private final WebClient webClient; + private static final String USER_INFO_URI = "https://kapi.kakao.com/v2/user/me"; + + public KakaoUserInfoResponse getUserInfo(String token) { + Flux response = webClient.get() + .uri(USER_INFO_URI) + .header("Authorization", "Bearer " + token) + .retrieve() + .bodyToFlux(KakaoUserInfoResponse.class); + return response.blockFirst(); + } +} diff --git a/src/main/java/com/diareat/diareat/auth/dto/KakaoAccount.java b/src/main/java/com/diareat/diareat/auth/dto/KakaoAccount.java new file mode 100644 index 0000000..faf7a48 --- /dev/null +++ b/src/main/java/com/diareat/diareat/auth/dto/KakaoAccount.java @@ -0,0 +1,9 @@ +package com.diareat.diareat.auth.dto; + +import lombok.Getter; + +@Getter +public class KakaoAccount { + + private KakaoProfile profile; +} diff --git a/src/main/java/com/diareat/diareat/auth/dto/KakaoProfile.java b/src/main/java/com/diareat/diareat/auth/dto/KakaoProfile.java new file mode 100644 index 0000000..1c50d73 --- /dev/null +++ b/src/main/java/com/diareat/diareat/auth/dto/KakaoProfile.java @@ -0,0 +1,12 @@ +package com.diareat.diareat.auth.dto; + +import lombok.Getter; + +@Getter +public class KakaoProfile { + + private String nickname; + private String profileImageUrl; + private String thumbnailImageUrl; + private boolean isDefaultImage; +} diff --git a/src/main/java/com/diareat/diareat/auth/dto/KakaoUserInfoResponse.java b/src/main/java/com/diareat/diareat/auth/dto/KakaoUserInfoResponse.java new file mode 100644 index 0000000..a4e4adb --- /dev/null +++ b/src/main/java/com/diareat/diareat/auth/dto/KakaoUserInfoResponse.java @@ -0,0 +1,11 @@ +package com.diareat.diareat.auth.dto; + +import lombok.Getter; + +@Getter +public class KakaoUserInfoResponse { + + private Long id; + private boolean hasSignedUp; + private KakaoAccount kakaoAccount; +} From af26095b6d9a6af63d5e84702c3a8da9d04637ca Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 00:53:32 +0900 Subject: [PATCH 114/371] =?UTF-8?q?:sparkles:=20Feat:=20AuthService=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20=EB=B0=8F=20UserController=EC=97=90=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/auth/KakaoAuthService.java | 26 +++++++++++++++++++ .../user/controller/UserController.java | 9 +++++++ .../user/repository/UserRepository.java | 2 ++ 3 files changed, 37 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/auth/KakaoAuthService.java diff --git a/src/main/java/com/diareat/diareat/auth/KakaoAuthService.java b/src/main/java/com/diareat/diareat/auth/KakaoAuthService.java new file mode 100644 index 0000000..ef14d5d --- /dev/null +++ b/src/main/java/com/diareat/diareat/auth/KakaoAuthService.java @@ -0,0 +1,26 @@ +package com.diareat.diareat.auth; + +import com.diareat.diareat.auth.component.KakaoUserInfo; +import com.diareat.diareat.auth.dto.KakaoUserInfoResponse; +import com.diareat.diareat.user.domain.User; +import com.diareat.diareat.user.repository.UserRepository; +import com.diareat.diareat.util.api.ResponseCode; +import com.diareat.diareat.util.exception.UserException; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@RequiredArgsConstructor +@Service +public class KakaoAuthService { // 카카오 소셜로그인, 세션 관리는 추후 구현 예정 + + private final KakaoUserInfo kakaoUserInfo; + private final UserRepository userRepository; + + @Transactional(readOnly = true) + public Long isSignedUp(String token) { // 클라이언트가 보낸 token을 이용해 카카오 API에 유저 정보를 요청, 유저가 존재하지 않으면 예외 발생, 존재하면 회원번호 반환 + KakaoUserInfoResponse userInfo = kakaoUserInfo.getUserInfo(token); + User user = userRepository.findByKeyCode(userInfo.getId().toString()).orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); + return user.getId(); + } +} diff --git a/src/main/java/com/diareat/diareat/user/controller/UserController.java b/src/main/java/com/diareat/diareat/user/controller/UserController.java index 66693b6..f7bd86b 100644 --- a/src/main/java/com/diareat/diareat/user/controller/UserController.java +++ b/src/main/java/com/diareat/diareat/user/controller/UserController.java @@ -1,5 +1,6 @@ package com.diareat.diareat.user.controller; +import com.diareat.diareat.auth.KakaoAuthService; import com.diareat.diareat.user.dto.*; import com.diareat.diareat.user.service.UserService; import com.diareat.diareat.util.api.ApiResponse; @@ -18,6 +19,14 @@ public class UserController { private final UserService userService; + private final KakaoAuthService kakaoAuthService; + + // 카카오 로그인을 위해 회원가입 여부 확인 + @Operation(summary = "[로그인] 카카오 로그인을 위해 회원가입 여부 확인", description = "카카오 로그인을 위해 회원가입 여부를 확인합니다.") + @GetMapping("/auth") + public ApiResponse authCheck(@RequestParam String token) { + return ApiResponse.success(kakaoAuthService.isSignedUp(token), ResponseCode.USER_READ_SUCCESS.getMessage()); + } // 회원정보 저장 @Operation(summary = "[회원가입] 회원정보 저장", description = "신규 회원정보를 저장합니다.") diff --git a/src/main/java/com/diareat/diareat/user/repository/UserRepository.java b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java index 743ec3a..c47a13b 100644 --- a/src/main/java/com/diareat/diareat/user/repository/UserRepository.java +++ b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java @@ -4,8 +4,10 @@ import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; +import java.util.Optional; public interface UserRepository extends JpaRepository { List findAllByNameContaining(String name); // 회원이 팔로우를 위해 검색한 유저 목록 조회 boolean existsByName(String name); // 회원가입 시 닉네임 중복 확인 + Optional findByKeyCode(String keyCode); // 카카오 회원가입 시 중복 확인 } From ca7e9f51245b1a03db64faa9eb790b33973522b7 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 01:09:07 +0900 Subject: [PATCH 115/371] =?UTF-8?q?:heavy=5Fplus=5Fsign:=20Chore:=20WebCli?= =?UTF-8?q?entConfig=20dependency=20=EB=88=84=EB=9D=BD=20=EB=B0=98?= =?UTF-8?q?=EC=98=81=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/auth/config/WebClientConfig.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/auth/config/WebClientConfig.java diff --git a/src/main/java/com/diareat/diareat/auth/config/WebClientConfig.java b/src/main/java/com/diareat/diareat/auth/config/WebClientConfig.java new file mode 100644 index 0000000..24c82ff --- /dev/null +++ b/src/main/java/com/diareat/diareat/auth/config/WebClientConfig.java @@ -0,0 +1,39 @@ +package com.diareat.diareat.auth.config; + +import io.netty.channel.ChannelOption; +import io.netty.handler.timeout.ReadTimeoutHandler; +import io.netty.handler.timeout.WriteTimeoutHandler; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.reactive.ClientHttpConnector; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.http.client.reactive.ReactorResourceFactory; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.netty.http.client.HttpClient; + +import java.time.Duration; +import java.util.function.Function; + +@Configuration +public class WebClientConfig { + + @Bean + public ReactorResourceFactory resourceFactory() { + ReactorResourceFactory factory = new ReactorResourceFactory(); + factory.setUseGlobalResources(false); + return factory; + } + + @Bean + public WebClient webClient() { + Function mapper = client -> HttpClient.create() + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000) + .doOnConnected(connection -> connection.addHandlerLast(new ReadTimeoutHandler(10)) + .addHandlerLast(new WriteTimeoutHandler(10))) + .responseTimeout(Duration.ofSeconds(1)); + + ClientHttpConnector connector = + new ReactorClientHttpConnector(resourceFactory(), mapper); + return WebClient.builder().clientConnector(connector).build(); + } +} \ No newline at end of file From b1740bab8141ee7fd194cf8fd1facea97730ef9a Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 01:20:07 +0900 Subject: [PATCH 116/371] =?UTF-8?q?:heavy=5Fplus=5Fsign:=20Chore:=20build.?= =?UTF-8?q?gradle=20=EB=88=84=EB=9D=BD=EB=90=9C=20=EC=9D=98=EC=A1=B4?= =?UTF-8?q?=EC=84=B1=20=EC=B6=94=EA=B0=80=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 889b7f0..7acb73b 100644 --- a/build.gradle +++ b/build.gradle @@ -41,8 +41,10 @@ dependencies { implementation 'io.springfox:springfox-swagger-ui:3.0.0' // Webclient dependency - implementation platform('org.springframework.boot:spring-boot-dependencies:2.5.4') // Replace with your Spring Boot version + implementation platform('org.springframework.boot:spring-boot-dependencies:2.7.15') implementation 'org.springframework.boot:spring-boot-starter-webflux' + + implementation 'io.netty:netty-resolver-dns-native-macos:4.1.68.Final:osx-aarch_64' } tasks.named('test') { From f1b5e9cd690eb5a5ea39cfc5cd4e2969818954e2 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 01:25:09 +0900 Subject: [PATCH 117/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20Fix:=20UserCon?= =?UTF-8?q?trollerTest=EC=97=90=20KakaoAuthService=20=EB=B0=98=EC=98=81=20?= =?UTF-8?q?(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/controller/UserControllerTest.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java index 7fbdb95..0ca90c2 100644 --- a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java @@ -1,5 +1,6 @@ package com.diareat.diareat.controller; +import com.diareat.diareat.auth.KakaoAuthService; import com.diareat.diareat.user.controller.UserController; import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; @@ -40,6 +41,9 @@ class UserControllerTest { @MockBean private UserService userService; + @MockBean + private KakaoAuthService kakaoAuthService; + private final Long testUserId = 1L; 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)); From 6671250c43b3960e680e6bccbe8414cb010325d7 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 21:24:56 +0900 Subject: [PATCH 118/371] =?UTF-8?q?:heavy=5Fplus=5Fsign:=20Chore:=20Jwt=20?= =?UTF-8?q?=EA=B4=80=EB=A0=A8=20=EC=9D=98=EC=A1=B4=EC=84=B1=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20=EB=B0=8F=20Auth=20=EA=B8=B0=EB=8A=A5=20=ED=8C=A8?= =?UTF-8?q?=ED=82=A4=EC=A7=80=20=EB=B6=84=EB=A6=AC=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 4 ++++ .../diareat/diareat/auth/{ => service}/KakaoAuthService.java | 2 +- .../diareat/diareat/{auth => }/config/WebClientConfig.java | 2 +- src/main/resources/application-db.properties | 5 ++++- 4 files changed, 10 insertions(+), 3 deletions(-) rename src/main/java/com/diareat/diareat/auth/{ => service}/KakaoAuthService.java (96%) rename src/main/java/com/diareat/diareat/{auth => }/config/WebClientConfig.java (97%) diff --git a/build.gradle b/build.gradle index 7acb73b..ed15302 100644 --- a/build.gradle +++ b/build.gradle @@ -45,6 +45,10 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-webflux' implementation 'io.netty:netty-resolver-dns-native-macos:4.1.68.Final:osx-aarch_64' + + // Jwt dependency + implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.2' // Spring Boot MyBatis + implementation "io.jsonwebtoken:jjwt:0.9.1" } tasks.named('test') { diff --git a/src/main/java/com/diareat/diareat/auth/KakaoAuthService.java b/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java similarity index 96% rename from src/main/java/com/diareat/diareat/auth/KakaoAuthService.java rename to src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java index ef14d5d..ffabdb4 100644 --- a/src/main/java/com/diareat/diareat/auth/KakaoAuthService.java +++ b/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java @@ -1,4 +1,4 @@ -package com.diareat.diareat.auth; +package com.diareat.diareat.auth.service; import com.diareat.diareat.auth.component.KakaoUserInfo; import com.diareat.diareat.auth.dto.KakaoUserInfoResponse; diff --git a/src/main/java/com/diareat/diareat/auth/config/WebClientConfig.java b/src/main/java/com/diareat/diareat/config/WebClientConfig.java similarity index 97% rename from src/main/java/com/diareat/diareat/auth/config/WebClientConfig.java rename to src/main/java/com/diareat/diareat/config/WebClientConfig.java index 24c82ff..80d7496 100644 --- a/src/main/java/com/diareat/diareat/auth/config/WebClientConfig.java +++ b/src/main/java/com/diareat/diareat/config/WebClientConfig.java @@ -1,4 +1,4 @@ -package com.diareat.diareat.auth.config; +package com.diareat.diareat.config; import io.netty.channel.ChannelOption; import io.netty.handler.timeout.ReadTimeoutHandler; diff --git a/src/main/resources/application-db.properties b/src/main/resources/application-db.properties index ee08c3d..e8c79c8 100644 --- a/src/main/resources/application-db.properties +++ b/src/main/resources/application-db.properties @@ -8,4 +8,7 @@ spring.datasource.password=${DB_PASSWORD} spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect -spring.jpa.properties.hibernate.format_sql=true \ No newline at end of file +spring.jpa.properties.hibernate.format_sql=true + +# JWT +jwt.secret=${JWT_KEY} \ No newline at end of file From 249f05ae1b472b46309f77e9a103eb2ad585e15c Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 21:27:43 +0900 Subject: [PATCH 119/371] =?UTF-8?q?:safety=5Fvest:=20Fix:=20UserService=20?= =?UTF-8?q?keyCode=20=EA=B4=80=EB=A0=A8=20=EC=98=88=EC=99=B8=EC=B2=98?= =?UTF-8?q?=EB=A6=AC=20=EB=A1=9C=EC=A7=81=20=EB=B3=B4=EA=B0=95=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/user/repository/UserRepository.java | 1 + .../java/com/diareat/diareat/user/service/UserService.java | 2 ++ src/main/java/com/diareat/diareat/util/api/ResponseCode.java | 4 +++- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/user/repository/UserRepository.java b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java index c47a13b..03b4e66 100644 --- a/src/main/java/com/diareat/diareat/user/repository/UserRepository.java +++ b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java @@ -9,5 +9,6 @@ public interface UserRepository extends JpaRepository { List findAllByNameContaining(String name); // 회원이 팔로우를 위해 검색한 유저 목록 조회 boolean existsByName(String name); // 회원가입 시 닉네임 중복 확인 + boolean existsByKeyCode(String keyCode); // 카카오 회원가입 시 중복 확인 Optional findByKeyCode(String keyCode); // 카카오 회원가입 시 중복 확인 } diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 22e85ef..ce2528f 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -29,6 +29,8 @@ public Long saveUser(CreateUserDto createUserDto) { BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); // BaseNutrition baseNutrition = BaseNutrition.createNutrition(createUserDto.getGender(), createUserDto.getAge(), createUserDto.getHeight(), createUserDto.getWeight()); if (userRepository.existsByName(createUserDto.getName())) + throw new UserException(ResponseCode.USER_NAME_ALREADY_EXIST); + if(userRepository.existsByKeyCode(createUserDto.getKeyCode())) throw new UserException(ResponseCode.USER_ALREADY_EXIST); User user = User.createUser(createUserDto.getName(), createUserDto.getImage(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); return userRepository.save(user).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 0f1574b..06dd872 100644 --- a/src/main/java/com/diareat/diareat/util/api/ResponseCode.java +++ b/src/main/java/com/diareat/diareat/util/api/ResponseCode.java @@ -24,7 +24,8 @@ public enum ResponseCode { METHOD_NOT_ALLOWED(HttpStatus.METHOD_NOT_ALLOWED, false, "허용되지 않은 메소드입니다."), // 409 Conflict - USER_ALREADY_EXIST(HttpStatus.CONFLICT, false, "이미 존재하는 닉네임입니다."), + USER_ALREADY_EXIST(HttpStatus.CONFLICT, false, "이미 가입한 사용자입니다."), + USER_NAME_ALREADY_EXIST(HttpStatus.CONFLICT, false, "이미 존재하는 닉네임입니다."), FOLLOWED_ALREADY(HttpStatus.CONFLICT, false, "이미 팔로우한 사용자입니다."), UNFOLLOWED_ALREADY(HttpStatus.CONFLICT, false, "이미 언팔로우한 사용자입니다."), FOOD_ALREADY_EXIST(HttpStatus.CONFLICT, false, "이미 즐겨찾기에 존재하는 음식입니다."), @@ -38,6 +39,7 @@ public enum ResponseCode { USER_SEARCH_SUCCESS(HttpStatus.OK, true, "사용자 검색 성공"), USER_FOLLOW_SUCCESS(HttpStatus.OK, true, "사용자 팔로우 성공"), USER_UNFOLLOW_SUCCESS(HttpStatus.OK, true, "사용자 언팔로우 성공"), + USER_LOGIN_SUCCESS(HttpStatus.OK, true, "사용자 로그인 성공"), FOOD_READ_SUCCESS(HttpStatus.OK, true, "음식 정보 조회 성공"), FOOD_UPDATE_SUCCESS(HttpStatus.OK, true, "음식 정보 수정 성공"), From 40a908914878534fe51d753e09776b468b92a8dc Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 21:30:14 +0900 Subject: [PATCH 120/371] =?UTF-8?q?:fire:=20Fix:=20UserController=20?= =?UTF-8?q?=EB=A1=9C=EA=B7=B8=EC=9D=B8=20=EA=B8=B0=EB=8A=A5=20=EC=82=AD?= =?UTF-8?q?=EC=A0=9C=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/controller/UserController.java | 16 ------------ .../controller/UserControllerTest.java | 26 +------------------ 2 files changed, 1 insertion(+), 41 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/controller/UserController.java b/src/main/java/com/diareat/diareat/user/controller/UserController.java index f7bd86b..e8c4af9 100644 --- a/src/main/java/com/diareat/diareat/user/controller/UserController.java +++ b/src/main/java/com/diareat/diareat/user/controller/UserController.java @@ -1,6 +1,5 @@ package com.diareat.diareat.user.controller; -import com.diareat.diareat.auth.KakaoAuthService; import com.diareat.diareat.user.dto.*; import com.diareat.diareat.user.service.UserService; import com.diareat.diareat.util.api.ApiResponse; @@ -19,21 +18,6 @@ public class UserController { private final UserService userService; - private final KakaoAuthService kakaoAuthService; - - // 카카오 로그인을 위해 회원가입 여부 확인 - @Operation(summary = "[로그인] 카카오 로그인을 위해 회원가입 여부 확인", description = "카카오 로그인을 위해 회원가입 여부를 확인합니다.") - @GetMapping("/auth") - public ApiResponse authCheck(@RequestParam String token) { - return ApiResponse.success(kakaoAuthService.isSignedUp(token), ResponseCode.USER_READ_SUCCESS.getMessage()); - } - - // 회원정보 저장 - @Operation(summary = "[회원가입] 회원정보 저장", description = "신규 회원정보를 저장합니다.") - @PostMapping("/save") - public ApiResponse saveUser(CreateUserDto createUserDto) { - return ApiResponse.success(userService.saveUser(createUserDto), ResponseCode.USER_CREATE_SUCCESS.getMessage()); - } // 회원 기본정보 조회 @Operation(summary = "[프로필] 회원 기본정보 조회", description = "회원 기본정보를 조회합니다.") diff --git a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java index 0ca90c2..b769c9e 100644 --- a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java @@ -1,6 +1,6 @@ package com.diareat.diareat.controller; -import com.diareat.diareat.auth.KakaoAuthService; +import com.diareat.diareat.auth.service.KakaoAuthService; import com.diareat.diareat.user.controller.UserController; import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; @@ -26,7 +26,6 @@ import java.util.List; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @WebMvcTest(controllers = UserController.class) @@ -56,29 +55,6 @@ void setUp() { when(userService.getUserInfo(testUserId)).thenReturn(ResponseUserDto.from(testUser)); } - @DisplayName("회원정보 저장") - @Test - @WithMockUser("test") - void testSaveUser() throws Exception { - // Given - ApiResponse expectedResponse = ApiResponse.success(testUserId, ResponseCode.USER_CREATE_SUCCESS.getMessage()); - String json = "{\"name\":\"test\",\"image\":\"test\",\"keyCode\":\"test\",\"gender\":0,\"height\":180,\"weight\":70,\"age\":20}"; - when(userService.saveUser(any(CreateUserDto.class))).thenReturn(testUserId); - - // When & Then - mockMvc.perform( MockMvcRequestBuilders - .post("/api/user/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("$.msg").value(expectedResponse.getMsg())) - .andExpect(MockMvcResultMatchers.jsonPath("$.data").value(expectedResponse.getData())); - } - - @DisplayName("회원 기본정보 조회") @Test @WithMockUser("test") From 229ac32904f6678ec8f7da0349fb27d63e45f41f Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 21:33:06 +0900 Subject: [PATCH 121/371] =?UTF-8?q?:sparkles:=20Feat:=20Spring=20Security?= =?UTF-8?q?=EB=A5=BC=20=EC=9C=84=ED=95=9C=20User=20=EA=B0=9D=EC=B2=B4?= =?UTF-8?q?=EC=97=90=20UserDetails=20=EC=9D=B8=ED=84=B0=ED=8E=98=EC=9D=B4?= =?UTF-8?q?=EC=8A=A4=20=EC=83=81=EC=86=8D=20=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/service/CustomUserDetailService.java | 22 ++++++++ .../com/diareat/diareat/user/domain/User.java | 56 +++++++++++++++++-- 2 files changed, 74 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java diff --git a/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java b/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java new file mode 100644 index 0000000..622e09f --- /dev/null +++ b/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java @@ -0,0 +1,22 @@ +package com.diareat.diareat.auth.service; + +import com.diareat.diareat.user.repository.UserRepository; +import com.diareat.diareat.util.api.ResponseCode; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@RequiredArgsConstructor +@Service +public class CustomUserDetailService implements UserDetailsService { + + private final UserRepository userRepository; + + @Override + public UserDetails loadUserByUsername(String keyCode) throws UsernameNotFoundException { + return userRepository.findByKeyCode(keyCode) + .orElseThrow(() -> new UsernameNotFoundException(ResponseCode.USER_NOT_FOUND.getMessage())); + } +} diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index 6852f48..98e16d7 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -3,18 +3,21 @@ import com.diareat.diareat.food.domain.FavoriteFood; import com.diareat.diareat.food.domain.Food; import com.fasterxml.jackson.annotation.JsonIgnore; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.NoArgsConstructor; +import lombok.*; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.authority.SimpleGrantedAuthority; import javax.persistence.*; import java.util.ArrayList; +import java.util.Collection; import java.util.List; +import java.util.stream.Collectors; @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @Entity -public class User { +public class User implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_id") @@ -23,6 +26,7 @@ public class User { private String name; // 닉네임 @JsonIgnore + @Column(length = 100, nullable = false, unique = true) private String keyCode; // 로그인 식별키 private String image; // 프로필 사진 경로 @@ -43,6 +47,50 @@ public class User { @OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) // 유저가 탈퇴하면 즐겨찾기 음식도 삭제 private List favoriteFoods = new ArrayList<>(); + // Jwt 전용 설정 (UserDetails 인터페이스 구현) + + @ElementCollection(fetch = FetchType.EAGER) //roles 컬렉션 + private List roles = new ArrayList<>(); + + @Override //사용자의 권한 목록 리턴 + public Collection getAuthorities() { + return this.roles.stream() + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toList()); + } + + @Override + public String getUsername() { + return keyCode; + } + + @Override + public String getPassword() { + return null; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + // Jwt 전용 설정 종료 + // 생성 메서드 public static User createUser(String name, String image, String keyCode, int height, int weight, int gender, int age, BaseNutrition baseNutrition) { User user = new User(); From 39c628bb6017410b754b61186cda4a0ac9a2a390 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 21:33:40 +0900 Subject: [PATCH 122/371] =?UTF-8?q?:sparkles:=20Feat:=20WebSecurity=20?= =?UTF-8?q?=EC=84=A4=EC=A0=95=20=EB=B0=8F=20Jwt=20=ED=86=A0=ED=81=B0=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/auth/component/JwtAuthFilter.java | 36 ++++++++++ .../auth/component/JwtTokenProvider.java | 72 +++++++++++++++++++ .../diareat/config/WebSecurityConfig.java | 36 ++++++++++ 3 files changed, 144 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/auth/component/JwtAuthFilter.java create mode 100644 src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java create mode 100644 src/main/java/com/diareat/diareat/config/WebSecurityConfig.java diff --git a/src/main/java/com/diareat/diareat/auth/component/JwtAuthFilter.java b/src/main/java/com/diareat/diareat/auth/component/JwtAuthFilter.java new file mode 100644 index 0000000..e90b21a --- /dev/null +++ b/src/main/java/com/diareat/diareat/auth/component/JwtAuthFilter.java @@ -0,0 +1,36 @@ +package com.diareat.diareat.auth.component; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.GenericFilterBean; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +@RequiredArgsConstructor +public class JwtAuthFilter extends GenericFilterBean { + + private final JwtTokenProvider jwtTokenProvider; + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + // 헤더에서 토큰 받아오기 + String token = jwtTokenProvider.resolveToken((HttpServletRequest) request); + + // 토큰이 유효하다면 + if (token != null && jwtTokenProvider.validateToken(token)) { + // 토큰으로부터 유저 정보를 받아 + Authentication authentication = jwtTokenProvider.getAuthentication(token); + // SecurityContext 에 객체 저장 + SecurityContextHolder.getContext().setAuthentication(authentication); + } + + // 다음 Filter 실행 + chain.doFilter(request, response); + } +} diff --git a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java new file mode 100644 index 0000000..76ff826 --- /dev/null +++ b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java @@ -0,0 +1,72 @@ +package com.diareat.diareat.auth.component; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletRequest; +import java.util.Base64; +import java.util.Date; + +@RequiredArgsConstructor +@Component +public class JwtTokenProvider { + + @Value("${jwt.secret}") + private String secretKey; + + private final UserDetailsService userDetailsService; + + // 객체 초기화, secretKey를 Base64로 인코딩 + @PostConstruct + protected void init() { + secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); + } + + // 토큰 생성 + public String createToken(String userPk) { + Claims claims = Jwts.claims().setSubject(userPk); // JWT payload 에 저장되는 정보단위 + Date now = new Date(); + return Jwts.builder() + .setClaims(claims) // 정보 저장 + .setIssuedAt(now) // 토큰 발행 시간 정보 + .setExpiration(new Date(now.getTime() + (30 * 60 * 1000L))) // 토큰 유효시각 설정 (30분) + .signWith(SignatureAlgorithm.HS256, secretKey) // 암호화 알고리즘과, secret 값 + .compact(); + } + + // 인증 정보 조회 + public Authentication getAuthentication(String token) { + UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUserPk(token)); + return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); + } + + // 토큰에서 회원 정보 추출 + public String getUserPk(String token) { + return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject(); + } + + // 토큰 유효성, 만료일자 확인 + public boolean validateToken(String jwtToken) { + try { + Jws claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken); + return !claims.getBody().getExpiration().before(new Date()); + } catch (Exception e) { + return false; + } + } + + // Request의 Header에서 token 값 가져오기 + public String resolveToken(HttpServletRequest request) { + return request.getHeader("X-AUTH-TOKEN"); + } +} diff --git a/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java b/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java new file mode 100644 index 0000000..401c31b --- /dev/null +++ b/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java @@ -0,0 +1,36 @@ +package com.diareat.diareat.config; + +import com.diareat.diareat.auth.component.JwtAuthFilter; +import com.diareat.diareat.auth.component.JwtTokenProvider; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@RequiredArgsConstructor +@EnableWebSecurity +public class WebSecurityConfig { + + private final JwtTokenProvider jwtTokenProvider; + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http + .csrf().disable() + //세션 사용 안함 + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + //URL 관리 + .authorizeRequests() + .antMatchers("/api/auth/**").permitAll() // 이 API 는 누구나 접근 가능 + .anyRequest().authenticated() + .and() + // JwtAuthenticationFilter를 먼저 적용 + .addFilterBefore(new JwtAuthFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } +} From f8a8505afa3781ada909ccb8ea5661b23b697d32 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 21:34:14 +0900 Subject: [PATCH 123/371] =?UTF-8?q?:sparkles:=20Feat:=20=ED=9A=8C=EC=9B=90?= =?UTF-8?q?=EA=B0=80=EC=9E=85=20=EB=B0=8F=20=EB=A1=9C=EA=B7=B8=EC=9D=B8=20?= =?UTF-8?q?AuthController=20=EA=B5=AC=ED=98=84=20(=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=20X)=20=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/controller/AuthController.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/auth/controller/AuthController.java diff --git a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java new file mode 100644 index 0000000..6682d22 --- /dev/null +++ b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java @@ -0,0 +1,45 @@ +package com.diareat.diareat.auth.controller; + +import com.diareat.diareat.auth.component.JwtTokenProvider; +import com.diareat.diareat.auth.service.KakaoAuthService; +import com.diareat.diareat.user.dto.CreateUserDto; +import com.diareat.diareat.user.service.UserService; +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.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; + +@Api(tags = "2. Auth") +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/auth") +public class AuthController { + + private final UserService userService; + private final KakaoAuthService kakaoAuthService; + private final JwtTokenProvider jwtTokenProvider; + + // 카카오 로그인을 위해 회원가입 여부 확인, 이미 회원이면 Jwt 토큰 발급 + @Operation(summary = "[로그인] 카카오로그인 및 토큰 발급", description = "카카오 로그인을 위해 회원가입 여부를 확인하고, 이미 회원이면 Jwt 토큰을 발급합니다.") + @PostMapping("/login") + public ApiResponse> authCheck(@RequestHeader String accessToken) { + Long userId = kakaoAuthService.isSignedUp(accessToken); // 유저 고유번호 추출 + HashMap map = new HashMap<>(); + map.put(userId, jwtTokenProvider.createToken(userId.toString())); + return ApiResponse.success(map, ResponseCode.USER_LOGIN_SUCCESS.getMessage()); + } + + // 회원가입 (성공 시 Jwt 토큰 발급) + @Operation(summary = "[회원가입] 회원가입 및 토큰 발급", description = "신규 회원가입을 처리하고, 회원가입 성공 시 Jwt 토큰을 발급합니다.") + @PostMapping("/join") + public ApiResponse> saveUser(CreateUserDto createUserDto) { + Long userId = userService.saveUser(createUserDto); + HashMap map = new HashMap<>(); + map.put(userId, jwtTokenProvider.createToken(userId.toString())); + return ApiResponse.success(map, ResponseCode.USER_CREATE_SUCCESS.getMessage()); + } +} From 4fb390956dbd47852e4a977d4f33ebe23f737363 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 21:44:50 +0900 Subject: [PATCH 124/371] =?UTF-8?q?:heavy=5Fplus=5Fsign:=20Chore:=20?= =?UTF-8?q?=ED=94=84=EB=A1=9C=ED=8D=BC=ED=8B=B0=20=EA=B0=9C=ED=96=89=20?= =?UTF-8?q?=EB=88=84=EB=9D=BD=20=EC=88=98=EC=A0=95=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/application-db.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/application-db.properties b/src/main/resources/application-db.properties index e8c79c8..4843c34 100644 --- a/src/main/resources/application-db.properties +++ b/src/main/resources/application-db.properties @@ -11,4 +11,4 @@ spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.jpa.properties.hibernate.format_sql=true # JWT -jwt.secret=${JWT_KEY} \ No newline at end of file +jwt.secret=${JWT_KEY} From 90c29f4f52042cc40879f7989f0d05e6c11adff9 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 16 Oct 2023 21:53:37 +0900 Subject: [PATCH 125/371] =?UTF-8?q?:fire:=20Chore:=20ApplicationTests=20@W?= =?UTF-8?q?ebAppConfiguration=20=EC=96=B4=EB=85=B8=ED=85=8C=EC=9D=B4?= =?UTF-8?q?=EC=85=98=20=EC=B6=94=EA=B0=80=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/DiareatApplicationTests.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/diareat/diareat/DiareatApplicationTests.java b/src/test/java/com/diareat/diareat/DiareatApplicationTests.java index 222773b..61b9333 100644 --- a/src/test/java/com/diareat/diareat/DiareatApplicationTests.java +++ b/src/test/java/com/diareat/diareat/DiareatApplicationTests.java @@ -1,9 +1,9 @@ package com.diareat.diareat; import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.web.WebAppConfiguration; -@SpringBootTest +@WebAppConfiguration // 현재 API가 존재하고 있는 웹 어플리케이션이므로 WebAppConfiguration 어노테이션을 붙여주어야 class DiareatApplicationTests { @Test From 7e6066dd8d531bebcf680741c745dbd43dc1221a Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 17 Oct 2023 00:42:36 +0900 Subject: [PATCH 126/371] =?UTF-8?q?:sparkles:=20Feat:=20AuthController=20?= =?UTF-8?q?=ED=86=A0=ED=81=B0=20=EA=B2=80=EC=A6=9D=20=EB=A1=9C=EC=A7=81=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20(#31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/auth/controller/AuthController.java | 7 +++++++ .../java/com/diareat/diareat/util/api/ResponseCode.java | 2 ++ 2 files changed, 9 insertions(+) diff --git a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java index 6682d22..1d01ad3 100644 --- a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java +++ b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java @@ -42,4 +42,11 @@ public ApiResponse> saveUser(CreateUserDto createUserDto) map.put(userId, jwtTokenProvider.createToken(userId.toString())); return ApiResponse.success(map, ResponseCode.USER_CREATE_SUCCESS.getMessage()); } + + // 토큰 검증 (Jwt 토큰을 서버에 전송하여, 서버가 유효한 토큰인지 확인하고 True 혹은 예외 반환) + @Operation(summary = "[토큰 검증] 토큰 검증", description = "클라이언트가 가지고 있던 Jwt 토큰을 서버에 전송하여, 서버가 유효한 토큰인지 확인하고 OK 혹은 예외를 반환합니다.") + @GetMapping("/token") + public ApiResponse tokenCheck(@RequestHeader String jwtToken) { + return ApiResponse.success(jwtTokenProvider.validateToken(jwtToken), ResponseCode.TOKEN_CHECK_SUCCESS.getMessage()); + } } 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 06dd872..63eae5b 100644 --- a/src/main/java/com/diareat/diareat/util/api/ResponseCode.java +++ b/src/main/java/com/diareat/diareat/util/api/ResponseCode.java @@ -48,6 +48,8 @@ public enum ResponseCode { FOOD_FAVORITE_UPDATE_SUCCESS(HttpStatus.OK, true, "즐겨찾기 음식 수정 성공"), FOOD_FAVORITE_DELETE_SUCCESS(HttpStatus.OK, true, "즐겨찾기 음식 삭제 성공"), + TOKEN_CHECK_SUCCESS(HttpStatus.OK, true, "토큰 검증 완료"), + // 201 Created USER_CREATE_SUCCESS(HttpStatus.CREATED, true, "사용자 생성 성공"), From efcafeabf5ac0ec500da33bd1133acb1def02ff7 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 17 Oct 2023 02:20:33 +0900 Subject: [PATCH 127/371] =?UTF-8?q?:sparkles:=20Feat:=20=EC=84=B1=EB=B3=84?= =?UTF-8?q?=EA=B3=BC=20=EC=97=B0=EB=A0=B9=EC=97=90=20=EB=94=B0=EB=A5=B8=20?= =?UTF-8?q?=EC=9C=A0=EC=A0=80=20=EB=B6=84=EB=A5=98=20=ED=95=A8=EC=88=98=20?= =?UTF-8?q?UserTypeUtil=20=EA=B5=AC=ED=98=84=20(#35)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/util/UserTypeUtil.java | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/util/UserTypeUtil.java diff --git a/src/main/java/com/diareat/diareat/util/UserTypeUtil.java b/src/main/java/com/diareat/diareat/util/UserTypeUtil.java new file mode 100644 index 0000000..d2e4332 --- /dev/null +++ b/src/main/java/com/diareat/diareat/util/UserTypeUtil.java @@ -0,0 +1,109 @@ +package com.diareat.diareat.util; + +import java.util.ArrayList; +import java.util.List; + +public class UserTypeUtil { + + public static int decideUserType(int gender, int age){ // 성별과 연령에 따른 유저 타입 분류 + if(gender == 0){ // 남자 + if(age < 11) return 1; + else if(age < 19) return 2; + else if(age < 30) return 3; + else if(age < 50) return 4; + else if(age < 65) return 5; + else return 6; + } else { // 여자 + if(age < 11) return 7; + else if(age < 19) return 8; + else if(age < 30) return 9; + else if(age < 50) return 10; + else if(age < 65) return 11; + else return 12; + } + } + + public static List getStanardByUserType(int type){ + ArrayList standard = new ArrayList<>(); + // 칼, 지, 탄의 순서로 3개 저장 + + /** 기준섭취량 산정을 위한 type + * 1. 11세 미만 남성 + * 2. 12~18세 남성 + * 3. 19~29세 남성 + * 4. 30~49세 남성 + * 5. 50~64세 남성 + * 6. 65세 이상 남성 + * 7. 11세 미만 여성 + * 8. 12~18세 여성 + * 9. 19~29세 여성 + * 10. 30~49세 여성 + * 11. 50~64세 여성 + * 12. 65세 이상 여성 + */ + + switch(type){ + case 1: // 남자 + standard.add(1630); // 칼로리 + standard.add(45); // 지방 + standard.add(240); // 탄수화물 + break; + case 2: + standard.add(1950); + standard.add(60); + standard.add(280); + break; + case 3: + standard.add(2070); + standard.add(60); + standard.add(270); + break; + case 4: + standard.add(2180); + standard.add(60); + standard.add(280); + break; + case 5: + standard.add(1980); + standard.add(50); + standard.add(280); + break; + case 6: + standard.add(1610); + standard.add(30); + standard.add(260); + break; + case 7: // 여자 + standard.add(1430); + standard.add(40); + standard.add(210); + break; + case 8: + standard.add(1480); + standard.add(40); + standard.add(215); + break; + case 9: + standard.add(1470); + standard.add(45); + standard.add(200); + break; + case 10: + standard.add(1500); + standard.add(40); + standard.add(210); + break; + case 11: + standard.add(1430); + standard.add(35); + standard.add(225); + break; + default: // 12 + standard.add(1230); + standard.add(20); + standard.add(210); + break; + } + return standard; + } +} From e7494e74d8ba1296b4e5680f68f1c6b12d5aba9b Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 17 Oct 2023 02:21:49 +0900 Subject: [PATCH 128/371] =?UTF-8?q?:sparkles:=20Feat:=20=EC=9C=A0=EC=A0=80?= =?UTF-8?q?=EC=97=90=20type=20=EC=86=8D=EC=84=B1=20=EC=B6=94=EA=B0=80=20?= =?UTF-8?q?=EB=B0=8F=20=EA=B8=B0=EC=A4=80=EC=84=AD=EC=B7=A8=EB=9F=89=20?= =?UTF-8?q?=EC=9D=91=EB=8B=B5=20dto=20=EA=B0=92=20=EC=B6=94=EA=B0=80=20(#3?= =?UTF-8?q?5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/user/domain/User.java | 9 ++++++++- .../user/dto/ResponseUserNutritionDto.java | 16 +++++++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index 98e16d7..5af69ea 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -2,6 +2,7 @@ import com.diareat.diareat.food.domain.FavoriteFood; import com.diareat.diareat.food.domain.Food; +import com.diareat.diareat.util.UserTypeUtil; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import org.springframework.security.core.GrantedAuthority; @@ -39,6 +40,8 @@ public class User implements UserDetails { private int age; // 나이 + private int type; // 성별과 연령에 따른 유저 타입 (1~12) + private BaseNutrition baseNutrition; // 기준영양소 @OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) // 유저가 탈퇴하면 촬영한 음식도 삭제 @@ -102,15 +105,19 @@ public static User createUser(String name, String image, String keyCode, int hei user.gender = gender; user.age = age; user.baseNutrition = baseNutrition; + user.type = UserTypeUtil.decideUserType(gender, age); return user; } // 회원정보 수정 - public void updateUser(String name, int height, int weight, int age) { + public void updateUser(String name, int height, int weight, int age, boolean autoUpdate) { this.name = name; this.height = height; this.weight = weight; this.age = age; + if(autoUpdate) { + this.type = UserTypeUtil.decideUserType(this.gender, this.age); + } } // 회원 기준영양소 직접 수정 diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseUserNutritionDto.java b/src/main/java/com/diareat/diareat/user/dto/ResponseUserNutritionDto.java index a2db114..41a6826 100644 --- a/src/main/java/com/diareat/diareat/user/dto/ResponseUserNutritionDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/ResponseUserNutritionDto.java @@ -8,16 +8,22 @@ @AllArgsConstructor public class ResponseUserNutritionDto { - private int calorie; + private int calorie; // 유저가 설정한(할 수 있는) 현재 영양소 기준섭취량 private int carbohydrate; private int protein; private int fat; - public static ResponseUserNutritionDto of(int calorie, int carbohydrate, int protein, int fat) { - return new ResponseUserNutritionDto(calorie, carbohydrate, protein, fat); + private int defaultCalorie; // 개인정보에 따라 기본적으로 설정되는 영양소 기준섭취량 + private int defaultCarbohydrate; + private int defaultProtein; + private int defaultFat; + + public static ResponseUserNutritionDto of(int calorie, int carbohydrate, int protein, int fat, int defaultCalorie, int defaultCarbohydrate, int defaultProtein, int defaultFat) { + return new ResponseUserNutritionDto(calorie, carbohydrate, protein, fat, defaultCalorie, defaultCarbohydrate, defaultProtein, defaultFat); } - public static ResponseUserNutritionDto from(User user) { - return new ResponseUserNutritionDto(user.getBaseNutrition().getKcal(), user.getBaseNutrition().getCarbohydrate(), user.getBaseNutrition().getProtein(), user.getBaseNutrition().getFat()); + public static ResponseUserNutritionDto from(User user, int defaultCalorie, int defaultCarbohydrate, int defaultProtein, int defaultFat) { + return new ResponseUserNutritionDto(user.getBaseNutrition().getKcal(), user.getBaseNutrition().getCarbohydrate(), + user.getBaseNutrition().getProtein(), user.getBaseNutrition().getFat(), defaultCalorie, defaultCarbohydrate, defaultProtein, defaultFat); } } From 9a5f5fb492f51f306db379503f8735bd4ff2de09 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 17 Oct 2023 02:22:19 +0900 Subject: [PATCH 129/371] =?UTF-8?q?:sparkles:=20Feat:=20UserService?= =?UTF-8?q?=EC=97=90=20type=EB=B3=84=20=EA=B8=B0=EC=A4=80=EC=84=AD?= =?UTF-8?q?=EC=B7=A8=EB=9F=89=20=EB=B0=98=ED=99=98=20=EB=A1=9C=EC=A7=81=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20(#35)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/service/UserService.java | 17 +++++++++++------ .../diareat/controller/UserControllerTest.java | 10 +++++++--- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index ce2528f..4c877e9 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -6,6 +6,7 @@ import com.diareat.diareat.user.dto.*; import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; +import com.diareat.diareat.util.UserTypeUtil; import com.diareat.diareat.util.api.ResponseCode; import com.diareat.diareat.util.exception.UserException; import lombok.RequiredArgsConstructor; @@ -26,12 +27,14 @@ public class UserService { // 회원정보 저장 @Transactional public Long saveUser(CreateUserDto createUserDto) { - BaseNutrition baseNutrition = BaseNutrition.createNutrition(2000, 300, 80, 80); - // BaseNutrition baseNutrition = BaseNutrition.createNutrition(createUserDto.getGender(), createUserDto.getAge(), createUserDto.getHeight(), createUserDto.getWeight()); if (userRepository.existsByName(createUserDto.getName())) throw new UserException(ResponseCode.USER_NAME_ALREADY_EXIST); if(userRepository.existsByKeyCode(createUserDto.getKeyCode())) throw new UserException(ResponseCode.USER_ALREADY_EXIST); + + int type = UserTypeUtil.decideUserType(createUserDto.getGender(), createUserDto.getAge()); + List standard = UserTypeUtil.getStanardByUserType(type); // 유저 타입에 따른 기본 기준섭취량 조회 + BaseNutrition baseNutrition = BaseNutrition.createNutrition(standard.get(0), standard.get(2), createUserDto.getWeight(), standard.get(1)); // 단백질은 자신 체중 기준으로 계산 User user = User.createUser(createUserDto.getName(), createUserDto.getImage(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); return userRepository.save(user).getId(); } @@ -40,7 +43,7 @@ public Long saveUser(CreateUserDto createUserDto) { @Transactional(readOnly = true) public ResponseSimpleUserDto getSimpleUserInfo(Long userId) { User user = getUserById(userId); - double nutritionScore = 100; // 로직 확정 전에는 임시 값으로 대체 + double nutritionScore = 100; // 점수 계산 로직 확정 전 기본값 -> 추후 수정 필요 return ResponseSimpleUserDto.of(user.getName(), user.getImage(), nutritionScore); } @@ -55,14 +58,16 @@ public ResponseUserDto getUserInfo(Long userId) { @Transactional public void updateUserInfo(UpdateUserDto updateUserDto) { User user = getUserById(updateUserDto.getUserId()); - user.updateUser(updateUserDto.getName(), updateUserDto.getHeight(), updateUserDto.getWeight(), updateUserDto.getAge()); + user.updateUser(updateUserDto.getName(), updateUserDto.getHeight(), updateUserDto.getWeight(), updateUserDto.getAge(), updateUserDto.isAutoUpdateNutrition()); + userRepository.save(user); } // 회원 기준섭취량 조회 @Transactional(readOnly = true) public ResponseUserNutritionDto getUserNutrition(Long userId) { User user = getUserById(userId); - return ResponseUserNutritionDto.from(user); + List standard = UserTypeUtil.getStanardByUserType(user.getType()); // 유저 타입에 따른 기본 기준섭취량 조회 + return ResponseUserNutritionDto.from(user, standard.get(0), standard.get(2), user.getWeight(), standard.get(1)); // 단백질은 자신 체중 기준으로 계산 } // 회원 기준섭취량 직접 수정 @@ -131,4 +136,4 @@ private User getUserById(Long userId) { return userRepository.findById(userId) .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); } -} +} \ No newline at end of file diff --git a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java index b769c9e..e3dc3e0 100644 --- a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java @@ -122,9 +122,9 @@ void updateUser() throws Exception { @WithMockUser("test") void getUserNutrition() throws Exception { // Given - when(userService.getUserNutrition(testUserId)).thenReturn(ResponseUserNutritionDto.of(2000, 300, 300, 80)); + when(userService.getUserNutrition(testUserId)).thenReturn(ResponseUserNutritionDto.of(2000, 300, 300, 80, 1000, 200, 200, 60)); ApiResponse expectedResponse = ApiResponse.success( - ResponseUserNutritionDto.of(2000, 300, 300, 80), ResponseCode.USER_READ_SUCCESS.getMessage()); + ResponseUserNutritionDto.of(2000, 300, 300, 80, 1000, 200, 200, 60), ResponseCode.USER_READ_SUCCESS.getMessage()); // When & Then mockMvc.perform( MockMvcRequestBuilders @@ -136,7 +136,11 @@ void getUserNutrition() throws Exception { .andExpect(MockMvcResultMatchers.jsonPath("$.data.calorie").value(expectedResponse.getData().getCalorie())) .andExpect(MockMvcResultMatchers.jsonPath("$.data.protein").value(expectedResponse.getData().getProtein())) .andExpect(MockMvcResultMatchers.jsonPath("$.data.fat").value(expectedResponse.getData().getFat())) - .andExpect(MockMvcResultMatchers.jsonPath("$.data.carbohydrate").value(expectedResponse.getData().getCarbohydrate())); + .andExpect(MockMvcResultMatchers.jsonPath("$.data.carbohydrate").value(expectedResponse.getData().getCarbohydrate())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.defaultCalorie").value(expectedResponse.getData().getDefaultCalorie())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.defaultProtein").value(expectedResponse.getData().getDefaultProtein())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.defaultFat").value(expectedResponse.getData().getDefaultFat())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.defaultCarbohydrate").value(expectedResponse.getData().getDefaultCarbohydrate())); } @DisplayName("회원 기준섭취량 직접 수정") From 6333bb232f2c6af5c89c9c93ed4c7bbd58411f99 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 17 Oct 2023 15:08:22 +0900 Subject: [PATCH 130/371] =?UTF-8?q?:wrench:=20Fix:=20=EC=9D=B8=EC=A6=9D=20?= =?UTF-8?q?=EB=8F=84=EC=9E=85=EC=9C=BC=EB=A1=9C=20=EC=9D=B8=ED=95=9C=20Swa?= =?UTF-8?q?gger=20API=20=EC=A0=91=EA=B7=BC=EC=A0=9C=ED=95=9C=20=EC=98=A4?= =?UTF-8?q?=EB=A5=98=20=EC=88=98=EC=A0=95=20(#35)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/config/SwaggerConfig.java | 35 +++++++++++++++++++ .../diareat/config/WebSecurityConfig.java | 13 +++---- 2 files changed, 42 insertions(+), 6 deletions(-) create mode 100644 src/main/java/com/diareat/diareat/config/SwaggerConfig.java diff --git a/src/main/java/com/diareat/diareat/config/SwaggerConfig.java b/src/main/java/com/diareat/diareat/config/SwaggerConfig.java new file mode 100644 index 0000000..3f108ca --- /dev/null +++ b/src/main/java/com/diareat/diareat/config/SwaggerConfig.java @@ -0,0 +1,35 @@ +package com.diareat.diareat.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Configuration +@EnableSwagger2 +public class SwaggerConfig implements WebMvcConfigurer { + + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build() + .apiInfo(apiInfo()); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Diareat API") + .description("Diareat API 설명서") + .version("1.0") + .build(); + } +} diff --git a/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java b/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java index 401c31b..0bd9f3a 100644 --- a/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java +++ b/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java @@ -16,21 +16,22 @@ public class WebSecurityConfig { private final JwtTokenProvider jwtTokenProvider; + private static final String[] AUTH_LIST = { // swagger 관련 URl + "/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html", "/swagger-ui/**" + }; + @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf().disable() - //세션 사용 안함 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() - //URL 관리 .authorizeRequests() - .antMatchers("/api/auth/**").permitAll() // 이 API 는 누구나 접근 가능 - .anyRequest().authenticated() + .antMatchers(AUTH_LIST).permitAll() // swagger 관련 URL은 인증 없이 접근 가능 (테스트용) + .antMatchers("/api/auth/**").permitAll() // 회원가입/로그인 관련 URL은 인증 없이 접근 가능 + .anyRequest().authenticated() // 나머지 모든 URL은 Jwt 인증 필요 .and() - // JwtAuthenticationFilter를 먼저 적용 .addFilterBefore(new JwtAuthFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); - return http.build(); } } From 5497f6c0f6c0e690f96e975672866fb271a3ddcd Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Tue, 17 Oct 2023 19:40:22 +0900 Subject: [PATCH 131/371] =?UTF-8?q?:green=5Fheart:=20fix:=20=EB=88=84?= =?UTF-8?q?=EB=9D=BD=EB=90=9C=20JWT=5FKEY=20=ED=99=98=EA=B2=BD=EB=B3=80?= =?UTF-8?q?=EC=88=98=20=EC=B6=94=EA=B0=80=20(#33)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/Diareat-CICD.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/Diareat-CICD.yml b/.github/workflows/Diareat-CICD.yml index fb1be37..4a11ca1 100644 --- a/.github/workflows/Diareat-CICD.yml +++ b/.github/workflows/Diareat-CICD.yml @@ -63,8 +63,9 @@ jobs: echo "DB_ENDPOINT=${{ secrets.DB_ENDPOINT }}" > env.list echo "DB_USERNAME=${{ secrets.DB_USERNAME }}" >> env.list echo "DB_PASSWORD=${{ secrets.DB_PASSWORD }}" >> env.list + echo "JWT_KEY=${{ secrets.JWT_KEY }}" >> env.list - sudo docker run -d -p 22:22/tcp --env-file env.list --name Diareat_Backend ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest + sudo docker run -d -p 8080:8080/tcp --env-file env.list --name Diareat_Backend ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest sleep 10s - sudo docker ps | grep ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest + sudo docker ps | grep ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest \ No newline at end of file From 2cb0bb1c7e505f8c3640f43e45fddef9424cb5c8 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 17 Oct 2023 22:04:28 +0900 Subject: [PATCH 132/371] =?UTF-8?q?:sparkles:=20Feat:=20=EC=9C=A0=EC=A0=80?= =?UTF-8?q?=EA=B0=80=20=ED=9A=8C=EC=9B=90=EA=B0=80=EC=9E=85=20=EC=8B=9C=20?= =?UTF-8?q?=EB=B3=B4=EB=82=B4=EB=8A=94=20JoinUserDto=20=EC=B6=94=EA=B0=80?= =?UTF-8?q?=20(#38)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/user/dto/JoinUserDto.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/user/dto/JoinUserDto.java diff --git a/src/main/java/com/diareat/diareat/user/dto/JoinUserDto.java b/src/main/java/com/diareat/diareat/user/dto/JoinUserDto.java new file mode 100644 index 0000000..2433db1 --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/dto/JoinUserDto.java @@ -0,0 +1,18 @@ +package com.diareat.diareat.user.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class JoinUserDto { + + private String token; + private String nickName; + private int gender; + private int height; + private int weight; + private int age; +} From b8c0b18bc9234bf3e617da13d955801b7cac72ea Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 17 Oct 2023 22:05:41 +0900 Subject: [PATCH 133/371] =?UTF-8?q?:adhesive=5Fbandage:=20Fix:=20JoinUserD?= =?UTF-8?q?to=20=EB=8F=84=EC=9E=85=EC=97=90=20=EB=94=B0=EB=A5=B8=20?= =?UTF-8?q?=ED=9A=8C=EC=9B=90=EA=B0=80=EC=9E=85=20=EB=A1=9C=EC=A7=81=20?= =?UTF-8?q?=EC=9D=BC=EB=B6=80=20=EA=B0=9C=ED=8E=B8=20(#38)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/auth/controller/AuthController.java | 6 +++--- .../diareat/auth/service/KakaoAuthService.java | 11 ++++++++++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java index 1d01ad3..385b7d2 100644 --- a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java +++ b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java @@ -2,7 +2,7 @@ import com.diareat.diareat.auth.component.JwtTokenProvider; import com.diareat.diareat.auth.service.KakaoAuthService; -import com.diareat.diareat.user.dto.CreateUserDto; +import com.diareat.diareat.user.dto.JoinUserDto; import com.diareat.diareat.user.service.UserService; import com.diareat.diareat.util.api.ApiResponse; import com.diareat.diareat.util.api.ResponseCode; @@ -36,8 +36,8 @@ public ApiResponse> authCheck(@RequestHeader String access // 회원가입 (성공 시 Jwt 토큰 발급) @Operation(summary = "[회원가입] 회원가입 및 토큰 발급", description = "신규 회원가입을 처리하고, 회원가입 성공 시 Jwt 토큰을 발급합니다.") @PostMapping("/join") - public ApiResponse> saveUser(CreateUserDto createUserDto) { - Long userId = userService.saveUser(createUserDto); + public ApiResponse> saveUser(JoinUserDto joinUserDto) { + Long userId = userService.saveUser(kakaoAuthService.createUserDto(joinUserDto)); HashMap map = new HashMap<>(); map.put(userId, jwtTokenProvider.createToken(userId.toString())); return ApiResponse.success(map, ResponseCode.USER_CREATE_SUCCESS.getMessage()); diff --git a/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java b/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java index ffabdb4..0d22bc4 100644 --- a/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java +++ b/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java @@ -3,6 +3,8 @@ import com.diareat.diareat.auth.component.KakaoUserInfo; import com.diareat.diareat.auth.dto.KakaoUserInfoResponse; import com.diareat.diareat.user.domain.User; +import com.diareat.diareat.user.dto.CreateUserDto; +import com.diareat.diareat.user.dto.JoinUserDto; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.util.api.ResponseCode; import com.diareat.diareat.util.exception.UserException; @@ -12,7 +14,7 @@ @RequiredArgsConstructor @Service -public class KakaoAuthService { // 카카오 소셜로그인, 세션 관리는 추후 구현 예정 +public class KakaoAuthService { private final KakaoUserInfo kakaoUserInfo; private final UserRepository userRepository; @@ -23,4 +25,11 @@ public Long isSignedUp(String token) { // 클라이언트가 보낸 token을 이 User user = userRepository.findByKeyCode(userInfo.getId().toString()).orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); return user.getId(); } + + @Transactional(readOnly = true) + public CreateUserDto createUserDto(JoinUserDto joinUserDto) { // 카카오로부터 프사 URL, 유저 고유ID를 얻어온 후, 이를 유저가 입력한 정보와 함께 CreateUserDto로 반환 + KakaoUserInfoResponse userInfo = kakaoUserInfo.getUserInfo(joinUserDto.getToken()); + return CreateUserDto.of(joinUserDto.getNickName(), userInfo.getKakaoAccount().getProfile().getProfileImageUrl(), + userInfo.getId().toString(), joinUserDto.getGender(), joinUserDto.getHeight(), joinUserDto.getWeight(), joinUserDto.getAge()); + } } From 90ef3a9bafe0927bf53320129ba17bff6fb6ee20 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 30 Oct 2023 19:58:06 +0900 Subject: [PATCH 134/371] =?UTF-8?q?:sparkles:=20Feat:=20FoodRepository=20?= =?UTF-8?q?=ED=95=84=EC=9A=94=ED=95=9C=20=EB=A9=94=EC=84=9C=EB=93=9C=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20(#42)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/repository/FavoriteFoodRepository.java | 1 + .../com/diareat/diareat/food/repository/FoodRepository.java | 2 +- src/main/java/com/diareat/diareat/util/api/ResponseCode.java | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java b/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java index 549a7cb..1bd1248 100644 --- a/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java +++ b/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java @@ -7,4 +7,5 @@ public interface FavoriteFoodRepository extends JpaRepository { List findAllByUserId(Long userId); + boolean existsByFoodId(Long foodId); // 이미 즐겨찾기에 추가된 음식인지 확인하기 위함 } 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 5cd6d90..7625379 100644 --- a/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java +++ b/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java @@ -8,5 +8,5 @@ public interface FoodRepository extends JpaRepository { List findAllByUserIdAndDate(Long userId, LocalDate date); //유저가 특정 날짜에 먹은 음식 반환 - List findAllByUserIdAndDateBetween(Long userId, LocalDate startDate, LocalDate endDate); //유저가 특정 기간 내에 먹은 음식 반환 + List findAllByUserIdAndDateBetween(Long userId, LocalDate startDate, LocalDate endDate); // 유저가 특정 기간 내에 먹은 음식 반환 } 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 63eae5b..3185dd9 100644 --- a/src/main/java/com/diareat/diareat/util/api/ResponseCode.java +++ b/src/main/java/com/diareat/diareat/util/api/ResponseCode.java @@ -28,7 +28,7 @@ public enum ResponseCode { USER_NAME_ALREADY_EXIST(HttpStatus.CONFLICT, false, "이미 존재하는 닉네임입니다."), FOLLOWED_ALREADY(HttpStatus.CONFLICT, false, "이미 팔로우한 사용자입니다."), UNFOLLOWED_ALREADY(HttpStatus.CONFLICT, false, "이미 언팔로우한 사용자입니다."), - FOOD_ALREADY_EXIST(HttpStatus.CONFLICT, false, "이미 즐겨찾기에 존재하는 음식입니다."), + FAVORITE_ALREADY_EXIST(HttpStatus.CONFLICT, false, "이미 즐겨찾기에 존재하는 음식입니다."), // 500 Internal Server Error INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, false, "서버에 오류가 발생하였습니다."), From 8124c3be52f6e3695ea04dc3de4849f784462fe0 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 30 Oct 2023 19:59:10 +0900 Subject: [PATCH 135/371] =?UTF-8?q?:sparkles:=20Feat:=20FoodService=20?= =?UTF-8?q?=EC=A3=BC=EA=B0=84=20=EB=9E=AD=ED=82=B9=20=EA=B8=B0=EB=8A=A5=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20(#42)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 113 +++++++++++++++--- 1 file changed, 99 insertions(+), 14 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 d9b5a58..cadc46a 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -7,6 +7,8 @@ import com.diareat.diareat.food.repository.FoodRepository; import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; +import com.diareat.diareat.user.dto.ResponseRankUserDto; +import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.util.api.ResponseCode; import com.diareat.diareat.util.exception.FavoriteException; @@ -16,9 +18,9 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.time.DayOfWeek; import java.time.LocalDate; -import java.util.Comparator; -import java.util.List; +import java.util.*; import java.util.stream.Collectors; @RequiredArgsConstructor @@ -27,7 +29,7 @@ public class FoodService { private final FoodRepository foodRepository; // 유저:음식은 1:다 private final FavoriteFoodRepository favoriteFoodRepository; // 유저:즐찾음식은 1:다 - + private final FollowRepository followRepository; private final UserRepository userRepository; // 촬영 후, 음식 정보 저장 @@ -65,9 +67,9 @@ public void deleteFood(Long foodId) { // 즐겨찾기에 음식 저장 @Transactional public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { - User user = getUserById(createFavoriteFoodDto.getUserId()); - + if (favoriteFoodRepository.existsByFoodId(createFavoriteFoodDto.getFoodId())) + throw new FavoriteException(ResponseCode.FAVORITE_ALREADY_EXIST); FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood(createFavoriteFoodDto.getName(), user, createFavoriteFoodDto.getBaseNutrition()); return favoriteFoodRepository.save(favoriteFood).getId(); } @@ -169,22 +171,75 @@ public ResponseFoodRankDto getWorstFoodByWeek(Long userId) { return ResponseFoodRankDto.of(userId, worst3FoodDtoList, endDate, false); } - private User getUserById(Long userId){ + // 잔여 기능 구현 부분 + + // 유저의 구체적인 점수 현황과 Best3, Worst3 조회 + + // 유저의 일기 분석 그래프 데이터 및 식습관 totalScore 조회 + + + @Transactional(readOnly = true) + // 유저의 식습관 점수를 기반으로 한 주간 랭킹 조회 + public List getUserRankByWeek(Long userId) { + List rankUserDtos = new ArrayList<>(); + List users = followRepository.findAllByFromUser(userId); // 유저의 팔로우 유저 명단 + rankUserDtos.add(calculateUserScoreThisWeek(getUserById(userId), LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now())); + if (users.isEmpty()) { // 팔로우한 유저가 없는 경우 본인의 점수 및 정보만 반환함 + return rankUserDtos; + } + + // 팔로우한 유저들의 점수를 계산하여 rankUserDtos에 추가 + rankUserDtos.forEach(rankUserDto -> + users.forEach(user -> + rankUserDtos.add(calculateUserScoreThisWeek(user, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now())))); + + // 식습관 총점 기준 내림차순 정렬 + rankUserDtos.sort(Comparator.comparing(ResponseRankUserDto::getTotalScore).reversed()); + return rankUserDtos; + } + + + private User getUserById(Long userId) { return userRepository.findById(userId) .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); } - private Food getFoodById(Long foodId){ + private Food getFoodById(Long foodId) { return foodRepository.findById(foodId) .orElseThrow(() -> new FoodException(ResponseCode.FOOD_NOT_FOUND)); } - private FavoriteFood getFavoriteFoodById(Long foodId){ + private FavoriteFood getFavoriteFoodById(Long foodId) { return favoriteFoodRepository.findById(foodId) .orElseThrow(() -> new FoodException(ResponseCode.FOOD_NOT_FOUND)); } - private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, List foodList, LocalDate checkDate, int nutritionSumType){ + private ResponseRankUserDto calculateUserScoreThisWeek(User targetUser, LocalDate startDate, LocalDate endDate) { + Map> maps = getNutritionSumByDateMap(targetUser.getId(), startDate, endDate); + double kcalScore = 0.0; + double carbohydrateScore = 0.0; + double proteinScore = 0.0; + double fatScore = 0.0; + double totalScore; + + for (LocalDate date : maps.keySet()) { + // 해당 날짜에 먹은 음식들의 영양성분 총합 계산 + int totalKcal = maps.get(date).stream().mapToInt(BaseNutrition::getKcal).sum(); + int totalCarbohydrate = maps.get(date).stream().mapToInt(BaseNutrition::getCarbohydrate).sum(); + int totalProtein = maps.get(date).stream().mapToInt(BaseNutrition::getProtein).sum(); + int totalFat = maps.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); + } + totalScore = (kcalScore + carbohydrateScore + proteinScore + fatScore); + return ResponseRankUserDto.of(targetUser.getId(), targetUser.getName(), targetUser.getImage(), kcalScore, carbohydrateScore, proteinScore, fatScore, totalScore); + } + + private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, List foodList, LocalDate checkDate, int nutritionSumType) { User targetUser = getUserById(userId); int totalKcal = 0; int totalCarbohydrate = 0; @@ -199,12 +254,12 @@ private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, totalFat += targetFoodNutrition.getFat(); } - double ratioKcal = Math.round((((double) totalKcal /(double) targetUser.getBaseNutrition().getKcal())*100.0)*10.0)/10.0; - double ratioCarbohydrate = Math.round((((double) totalCarbohydrate /(double) targetUser.getBaseNutrition().getCarbohydrate())*100.0)*10.0)/10.0; - double ratioProtein = Math.round((((double) totalProtein /(double) targetUser.getBaseNutrition().getProtein())*100.0)*10.0)/10.0; - double ratioFat =Math.round((((double) totalFat /(double) targetUser.getBaseNutrition().getFat())*100.0)*10.0)/10.0; + double ratioKcal = Math.round((((double) totalKcal / (double) targetUser.getBaseNutrition().getKcal()) * 100.0) * 10.0) / 10.0; + double ratioCarbohydrate = Math.round((((double) totalCarbohydrate / (double) targetUser.getBaseNutrition().getCarbohydrate()) * 100.0) * 10.0) / 10.0; + double ratioProtein = Math.round((((double) totalProtein / (double) targetUser.getBaseNutrition().getProtein()) * 100.0) * 10.0) / 10.0; + double ratioFat = Math.round((((double) totalFat / (double) targetUser.getBaseNutrition().getFat()) * 100.0) * 10.0) / 10.0; - return ResponseNutritionSumByDateDto.of(userId, checkDate, nutritionSumType, totalKcal,totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); + return ResponseNutritionSumByDateDto.of(userId, checkDate, nutritionSumType, totalKcal, totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); } private void validateUser(Long userId) { @@ -222,6 +277,36 @@ private void validateFavoriteFood(Long favoriteFoodId) { throw new FavoriteException(ResponseCode.FAVORITE_NOT_FOUND); } + // 1주일동안 먹은 음식들의 영양성분 총합을 요일을 Key로 한 Map을 통해 반환 + private HashMap> getNutritionSumByDateMap(Long userId, LocalDate startDate, LocalDate endDate) { + HashMap> maps = new HashMap<>(); + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, endDate); + for (Food food : foodList) { + if (maps.containsKey(food.getDate())) { + maps.get(food.getDate()).add(food.getBaseNutrition()); + } else { + List baseNutritions = new ArrayList<>(); + baseNutritions.add(food.getBaseNutrition()); + maps.put(food.getDate(), baseNutritions); + } + } + return maps; + } + + // 영양성분 총합 대비 기준섭취량 비율을 계산하여 성분별 식습관 점수를 반환 + private double calculateNutriRatioAndScore(double total, double standard, int type) { + double ratio = Math.round(((total / standard) * 100.0) * 10.0) / 10.0; + if (type == 0) { // 단백질 + if (ratio <= 100.0) return ratio; + else if (ratio <= 150) return 100; + else return (-2 * ratio + 400 < 0) ? 0 : (-2 * ratio + 400); + } else { // 칼탄지 + double gradient = 1.11; // (9분의 10) + if (ratio <= 90.0) return ratio * gradient; + else if (ratio <= 110) return 100; + else return (-gradient * (ratio - 200) < 0) ? 0 : (-gradient * (ratio - 200)); + } + } /** * 메서드 구현 유의사항 From 8c483142959088a2117385fb56d6b96996796464 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 30 Oct 2023 19:59:39 +0900 Subject: [PATCH 136/371] =?UTF-8?q?:sparkles:=20Feat:=20FoodService=20?= =?UTF-8?q?=EC=9E=94=EC=97=AC=20=EA=B8=B0=EB=8A=A5=20Dto=20=EA=B5=AC?= =?UTF-8?q?=EC=B6=95=20(#42)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/dto/ResponseAnalysisDto.java | 25 +++++++++++++++++ .../food/dto/ResponseScoreBestWorstDto.java | 23 +++++++++++++++ .../food/dto/ResponseSimpleFoodDto.java | 28 +++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java create mode 100644 src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java create mode 100644 src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java new file mode 100644 index 0000000..071206b --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java @@ -0,0 +1,25 @@ +package com.diareat.diareat.food.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.util.List; + +@Getter +@AllArgsConstructor +public class ResponseAnalysisDto { // 그래프 + 점수에 사용되는 DTO + + private double totalScore; + private List calorieLastSevenDays; // 최근 7일간의 칼로리 (7개 과거부터 나열) + private List calorieLastFourWeek; // 최근 4주간의 칼로리 (4개 과거부터 나열) + private List carbohydrateLastSevenDays; // 최근 7일간의 탄수화물 + private List carbohydrateLastFourWeek; // 최근 4주간의 탄수화물 + private List proteinLastSevenDays; // 최근 7일간의 단백질 + private List proteinLastFourWeek; // 최근 4주간의 단백질 + private List fatLastSevenDays; // 최근 7일간의 지방 + private List fatLastFourWeek; // 최근 4주간의 지방 + + public static ResponseAnalysisDto of(double totalScore, List calorieLastSevenDays, List calorieLastFourWeek, List carbohydrateLastSevenDays, List carbohydrateLastFourWeek, List proteinLastSevenDays, List proteinLastFourWeek, List fatLastSevenDays, List fatLastFourWeek) { + return new ResponseAnalysisDto(totalScore, calorieLastSevenDays, calorieLastFourWeek, carbohydrateLastSevenDays, carbohydrateLastFourWeek, proteinLastSevenDays, proteinLastFourWeek, fatLastSevenDays, fatLastFourWeek); + } +} diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java new file mode 100644 index 0000000..0e00c9d --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java @@ -0,0 +1,23 @@ +package com.diareat.diareat.food.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.util.List; + +@Getter +@AllArgsConstructor +public class ResponseScoreBestWorstDto { // 일기 분석 자세히보기에 사용되는 DTO + + private double calorieScore; + private double carbohydrateScore; + private double proteinScore; + private double fatScore; + private double totalScore; + private List best; + private List worst; + + public static ResponseScoreBestWorstDto of(double calorieScore, double carbohydrateScore, double proteinScore, double fatScore, double totalScore, List best, List worst) { + return new ResponseScoreBestWorstDto(calorieScore, carbohydrateScore, proteinScore, fatScore, totalScore, best, worst); + } +} diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java new file mode 100644 index 0000000..7238afa --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java @@ -0,0 +1,28 @@ +package com.diareat.diareat.food.dto; + +import com.diareat.diareat.food.domain.Food; +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.time.LocalDate; + +@Getter +@AllArgsConstructor +public class ResponseSimpleFoodDto { // Best 3 and Worst 3에 사용될 객체 + + private String name; + private double calorie; + private double carbohydrate; + private double protein; + private double fat; + private LocalDate date; + + public static ResponseSimpleFoodDto of(String name, double calorie, double carbohydrate, double protein, double fat, LocalDate date) { + return new ResponseSimpleFoodDto(name, calorie, carbohydrate, protein, fat, date); + } + + public static ResponseSimpleFoodDto from(Food food) { + return new ResponseSimpleFoodDto(food.getName(), food.getBaseNutrition().getKcal(), food.getBaseNutrition().getCarbohydrate(), + food.getBaseNutrition().getProtein(), food.getBaseNutrition().getFat(), food.getDate()); + } +} From 113074b86416cb5cc5018c51b2cded40b1484057 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 31 Oct 2023 01:10:51 +0900 Subject: [PATCH 137/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20Test:=20?= =?UTF-8?q?=EB=B2=84=EA=B7=B8=20=EC=88=98=EC=A0=95=20=EB=B0=8F=20=EB=9E=AD?= =?UTF-8?q?=ED=82=B9=20=ED=85=8C=EC=8A=A4=ED=8A=B8=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1=20(#42)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 11 +++-- .../diareat/service/FoodServiceTest.java | 46 +++++++++++++++++++ 2 files changed, 52 insertions(+), 5 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 cadc46a..ea55b59 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -189,9 +189,10 @@ public List getUserRankByWeek(Long userId) { } // 팔로우한 유저들의 점수를 계산하여 rankUserDtos에 추가 - rankUserDtos.forEach(rankUserDto -> - users.forEach(user -> - rankUserDtos.add(calculateUserScoreThisWeek(user, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now())))); + for (User user : users) { + ResponseRankUserDto userDto = calculateUserScoreThisWeek(user, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()); + rankUserDtos.add(userDto); + } // 식습관 총점 기준 내림차순 정렬 rankUserDtos.sort(Comparator.comparing(ResponseRankUserDto::getTotalScore).reversed()); @@ -297,12 +298,12 @@ private HashMap> getNutritionSumByDateMap(Long us private double calculateNutriRatioAndScore(double total, double standard, int type) { double ratio = Math.round(((total / standard) * 100.0) * 10.0) / 10.0; if (type == 0) { // 단백질 - if (ratio <= 100.0) return ratio; + if (ratio < 100.0) return ratio; else if (ratio <= 150) return 100; else return (-2 * ratio + 400 < 0) ? 0 : (-2 * ratio + 400); } else { // 칼탄지 double gradient = 1.11; // (9분의 10) - if (ratio <= 90.0) return ratio * gradient; + if (ratio < 90.0) return ratio * gradient; else if (ratio <= 110) return 100; else return (-gradient * (ratio - 200) < 0) ? 0 : (-gradient * (ratio - 200)); } diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 31b9e8e..cf29add 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -8,6 +8,8 @@ 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.ResponseRankUserDto; +import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -23,6 +25,7 @@ import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -43,6 +46,9 @@ class FoodServiceTest { @Mock UserRepository userRepository; + @Mock + FollowRepository followRepository; + @DisplayName("음식 정보 저장") @Test void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리스트 불러오기 @@ -309,4 +315,44 @@ void getWorst3FoodsTest() { assertEquals("Food4", top3Foods.get(1).getName()); assertEquals("Food5", top3Foods.get(2).getName()); } + + @Test + void getUserRankByWeek() { + // given + User user1 = User.createUser("testUser1", "testImage","testPassword", 180, 80, 0, 18, BaseNutrition.createNutrition(1000,100,100,100)); + User user2 = User.createUser("testUser2", "testImage","testPassword", 180, 80, 0, 18, BaseNutrition.createNutrition(1000,100,100,100)); + user1.setId(1L); + user2.setId(2L); + + Food food1 = Food.createFood( "Food1", user1, BaseNutrition.createNutrition(1000, 100 ,100, 100)); + Food food2 = Food.createFood( "Food2", user2, BaseNutrition.createNutrition(2000, 110 ,50, 90)); + + given(userRepository.findById(user1.getId())).willReturn(Optional.of(user1)); + given(followRepository.findAllByFromUser(user1.getId())).willReturn(List.of(user2)); + given(foodRepository.findAllByUserIdAndDateBetween(eq(1L), any(LocalDate.class), any(LocalDate.class))).willReturn(List.of(food1)); + given(foodRepository.findAllByUserIdAndDateBetween(eq(2L), any(LocalDate.class), any(LocalDate.class))).willReturn(List.of(food2)); + + // when + List response = foodService.getUserRankByWeek(user1.getId()); + + // then + assertEquals(2, response.size()); + assertEquals("testUser1", response.get(0).getName()); + assertEquals("testUser2", response.get(1).getName()); + assertEquals(100, response.get(0).getCalorieScore()); + assertEquals(100, response.get(0).getCarbohydrateScore()); + assertEquals(100, response.get(0).getProteinScore()); + assertEquals(100, response.get(0).getFatScore()); + assertEquals(400, response.get(0).getTotalScore()); + + assertEquals(0, response.get(1).getCalorieScore()); + assertEquals(100, response.get(1).getCarbohydrateScore()); + assertEquals(50, response.get(1).getProteinScore()); + assertEquals(100, response.get(1).getFatScore()); + assertEquals(250, response.get(1).getTotalScore()); + verify(userRepository, times(1)).findById(user1.getId()); + verify(followRepository, times(1)).findAllByFromUser(user1.getId()); + 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)); + } } From 33768e107ba9cf8f9a3d20023c1525c14979d6d0 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 31 Oct 2023 21:45:48 +0900 Subject: [PATCH 138/371] =?UTF-8?q?:sparkles:=20Feat:=20Redis=20=EC=9D=98?= =?UTF-8?q?=EC=A1=B4=EC=84=B1=20=EB=B0=8F=20=EC=84=A4=EC=A0=95=ED=8C=8C?= =?UTF-8?q?=EC=9D=BC=20=EC=B6=94=EA=B0=80=20(#44)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 3 ++ .../diareat/config/RedisCacheConfig.java | 28 +++++++++++++++++++ src/main/resources/application.properties | 7 ++++- 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/diareat/diareat/config/RedisCacheConfig.java diff --git a/build.gradle b/build.gradle index ed15302..601d52e 100644 --- a/build.gradle +++ b/build.gradle @@ -49,6 +49,9 @@ dependencies { // Jwt dependency implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.2' // Spring Boot MyBatis implementation "io.jsonwebtoken:jjwt:0.9.1" + + // Redis dependency + implementation 'org.springframework.boot:spring-boot-starter-data-redis' } tasks.named('test') { diff --git a/src/main/java/com/diareat/diareat/config/RedisCacheConfig.java b/src/main/java/com/diareat/diareat/config/RedisCacheConfig.java new file mode 100644 index 0000000..8eeb6bb --- /dev/null +++ b/src/main/java/com/diareat/diareat/config/RedisCacheConfig.java @@ -0,0 +1,28 @@ +package com.diareat.diareat.config; + +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import java.time.Duration; + +@Configuration +@EnableCaching +public class RedisCacheConfig { // Redis Cache 설정 + + @Bean + public CacheManager diareatCacheManager(RedisConnectionFactory cf) { + RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() + .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) + .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) + .entryTtl(Duration.ofMinutes(3L)); // 캐시 만료 시간 3분 + return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(cf).cacheDefaults(redisCacheConfiguration).build(); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 61a7a3e..98fd09d 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -2,4 +2,9 @@ spring.profiles.include = db # swagger -spring.mvc.pathmatch.matching-strategy=ant_path_matcher \ No newline at end of file +spring.mvc.pathmatch.matching-strategy=ant_path_matcher + +# redis +spring.redis.serializer=org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer +spring.cache.type=redis +spring.cache.redis.cache-null-values=true From 21eff6ba2f362c4a2c419a5f4cfd181588e4fbb4 Mon Sep 17 00:00:00 2001 From: CHAE Date: Wed, 1 Nov 2023 00:06:01 +0900 Subject: [PATCH 139/371] =?UTF-8?q?:sparkles:=20Feat:=20UserService=20?= =?UTF-8?q?=EC=BA=90=EC=8B=B1=20=EC=A0=81=EC=9A=A9=20(#44)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/service/UserService.java | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 4c877e9..f1206cd 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -10,6 +10,8 @@ import com.diareat.diareat.util.api.ResponseCode; import com.diareat.diareat.util.exception.UserException; import lombok.RequiredArgsConstructor; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -40,6 +42,7 @@ public Long saveUser(CreateUserDto createUserDto) { } // 회원 기본정보 조회 + @Cacheable(value = "ResponseSimpleUserDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) public ResponseSimpleUserDto getSimpleUserInfo(Long userId) { User user = getUserById(userId); @@ -48,6 +51,7 @@ public ResponseSimpleUserDto getSimpleUserInfo(Long userId) { } // 회원정보 조회 + @Cacheable(value = "ResponseUserDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) public ResponseUserDto getUserInfo(Long userId) { User user = getUserById(userId); @@ -55,6 +59,7 @@ public ResponseUserDto getUserInfo(Long userId) { } // 회원정보 수정 + @CacheEvict(value = {"ResponseSimpleUserDto", "ResponseUserDto"}, key = "#updateUserDto.userId", cacheManager = "diareatCacheManager") @Transactional public void updateUserInfo(UpdateUserDto updateUserDto) { User user = getUserById(updateUserDto.getUserId()); @@ -63,6 +68,7 @@ public void updateUserInfo(UpdateUserDto updateUserDto) { } // 회원 기준섭취량 조회 + @Cacheable(value = "ResponseUserNutritionDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) public ResponseUserNutritionDto getUserNutrition(Long userId) { User user = getUserById(userId); @@ -71,6 +77,7 @@ public ResponseUserNutritionDto getUserNutrition(Long userId) { } // 회원 기준섭취량 직접 수정 + @CacheEvict(value = "ResponseUserNutritionDto", key = "#updateUserNutritionDto.userId", cacheManager = "diareatCacheManager") @Transactional public void updateBaseNutrition(UpdateUserNutritionDto updateUserNutritionDto) { User user = getUserById(updateUserNutritionDto.getUserId()); @@ -80,13 +87,14 @@ public void updateBaseNutrition(UpdateUserNutritionDto updateUserNutritionDto) { } // 회원 탈퇴 + @CacheEvict(value = {"ResponseSimpleUserDto", "ResponseUserDto", "ResponseUserNutritionDto"}, key = "#userId", cacheManager = "diareatCacheManager") @Transactional public void deleteUser(Long userId) { validateUser(userId); userRepository.deleteById(userId); } - // 회원의 친구 검색 결과 조회 + // 회원의 친구 검색 결과 조회 -> 검색 및 팔로우는 굉장히 돌발적으로 이루어질 가능성이 높아 캐시 적용 X @Transactional(readOnly = true) public List searchUser(Long hostId, String name) { validateUser(hostId); @@ -118,15 +126,6 @@ public void unfollowUser(Long userId, Long unfollowId) { followRepository.delete(Follow.makeFollow(userId, unfollowId)); } - // 회원의 팔로우 목록 조회 (현재 외부 Dto 변환은 Food에서 위임받아 진행할지 협의하지 않았기에 일단 User 리스트로 반환) - @Transactional(readOnly = true) - public List getFollowList(Long userId) { - validateUser(userId); - List users = followRepository.findAllByFromUser(userId); - users.add(getUserById(userId)); // 자기 자신도 랭킹에 포함 - return users; - } - private void validateUser(Long userId) { if (!userRepository.existsById(userId)) throw new UserException(ResponseCode.USER_NOT_FOUND); @@ -136,4 +135,4 @@ private User getUserById(Long userId) { return userRepository.findById(userId) .orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); } -} \ No newline at end of file +} From 462c8508e4fc71160cb0c88cdc593802086f0d9b Mon Sep 17 00:00:00 2001 From: CHAE Date: Wed, 1 Nov 2023 00:31:23 +0900 Subject: [PATCH 140/371] =?UTF-8?q?:sparkles:=20Feat:=20EnableCaching=20?= =?UTF-8?q?=EC=96=B4=EB=85=B8=ED=85=8C=EC=9D=B4=EC=85=98=20=EB=8F=84?= =?UTF-8?q?=EC=9E=85=20(#44)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/DiareatApplication.java | 2 ++ src/main/java/com/diareat/diareat/config/RedisCacheConfig.java | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/DiareatApplication.java b/src/main/java/com/diareat/diareat/DiareatApplication.java index 87fdffa..79fcc2e 100644 --- a/src/main/java/com/diareat/diareat/DiareatApplication.java +++ b/src/main/java/com/diareat/diareat/DiareatApplication.java @@ -2,7 +2,9 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; +@EnableCaching @SpringBootApplication public class DiareatApplication { diff --git a/src/main/java/com/diareat/diareat/config/RedisCacheConfig.java b/src/main/java/com/diareat/diareat/config/RedisCacheConfig.java index 8eeb6bb..9d828ec 100644 --- a/src/main/java/com/diareat/diareat/config/RedisCacheConfig.java +++ b/src/main/java/com/diareat/diareat/config/RedisCacheConfig.java @@ -1,7 +1,6 @@ package com.diareat.diareat.config; import org.springframework.cache.CacheManager; -import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; @@ -14,7 +13,6 @@ import java.time.Duration; @Configuration -@EnableCaching public class RedisCacheConfig { // Redis Cache 설정 @Bean From 50f7883f3de926c8df32ae9e4da30ad0984ac99b Mon Sep 17 00:00:00 2001 From: CHAE Date: Wed, 1 Nov 2023 01:19:13 +0900 Subject: [PATCH 141/371] =?UTF-8?q?:sparkles:=20Feat:=20=EC=BA=90=EC=8B=B1?= =?UTF-8?q?=20Key=EB=A5=BC=20=EC=9C=84=ED=95=9C=20=EC=88=98=EC=A0=95/?= =?UTF-8?q?=EC=82=AD=EC=A0=9C=20=EA=B4=80=EB=A0=A8=20=EC=9A=94=EC=B2=AD=20?= =?UTF-8?q?dto=20=EB=B0=8F=20=ED=97=A4=EB=8D=94=20=EC=88=98=EC=A0=95=20(#4?= =?UTF-8?q?4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/controller/FoodController.java | 8 ++++---- .../diareat/diareat/food/dto/UpdateFavoriteFoodDto.java | 5 +++-- .../java/com/diareat/diareat/food/dto/UpdateFoodDto.java | 5 +++-- .../java/com/diareat/diareat/service/FoodServiceTest.java | 8 ++++---- 4 files changed, 14 insertions(+), 12 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 293eb3e..7f60221 100644 --- a/src/main/java/com/diareat/diareat/food/controller/FoodController.java +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -49,8 +49,8 @@ public ApiResponse updateFood(UpdateFoodDto updateFoodDto){ //음식 삭제 @Operation(summary = "[음식] 음식 정보 삭제",description = "음식에 대한 정보를 삭제합니다.") @DeleteMapping("/{foodId}/delete") - public ApiResponse deleteFood(@PathVariable Long foodId){ - foodService.deleteFood(foodId); + public ApiResponse deleteFood(@PathVariable Long foodId, @RequestHeader Long userId){ + foodService.deleteFood(foodId, userId); return ApiResponse.success(null, ResponseCode.FOOD_DELETE_SUCCESS.getMessage()); } @@ -79,8 +79,8 @@ public ApiResponse updateFavoriteFood(UpdateFavoriteFoodDto updateFavorite //즐겨찾기 음식 해제 @Operation(summary = "[즐겨찾기] 즐겨찾기 해제",description = "유저의 즐겨찾기에 등록된 음식을 해제합니다.") @DeleteMapping("/favorite/{favoriteFoodId}") - public ApiResponse deleteFavoriteFood(@PathVariable Long favoriteFoodId){ - foodService.deleteFavoriteFood(favoriteFoodId); + public ApiResponse deleteFavoriteFood(@PathVariable Long favoriteFoodId, @RequestHeader Long userId){ + foodService.deleteFavoriteFood(favoriteFoodId, userId); return ApiResponse.success(null, ResponseCode.FOOD_FAVORITE_DELETE_SUCCESS.getMessage()); } diff --git a/src/main/java/com/diareat/diareat/food/dto/UpdateFavoriteFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/UpdateFavoriteFoodDto.java index 705591e..df7ecbf 100644 --- a/src/main/java/com/diareat/diareat/food/dto/UpdateFavoriteFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/UpdateFavoriteFoodDto.java @@ -11,10 +11,11 @@ public class UpdateFavoriteFoodDto { private Long favoriteFoodId; + private Long userId; private String name; private BaseNutrition baseNutrition; - public static UpdateFavoriteFoodDto of(Long favoriteFoodId, String name, BaseNutrition baseNutrition) { - return new UpdateFavoriteFoodDto(favoriteFoodId, name, baseNutrition); + public static UpdateFavoriteFoodDto of(Long favoriteFoodId, Long userId, String name, BaseNutrition baseNutrition) { + return new UpdateFavoriteFoodDto(favoriteFoodId, userId, name, baseNutrition); } } diff --git a/src/main/java/com/diareat/diareat/food/dto/UpdateFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/UpdateFoodDto.java index 7471e85..55b2dac 100644 --- a/src/main/java/com/diareat/diareat/food/dto/UpdateFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/UpdateFoodDto.java @@ -11,10 +11,11 @@ public class UpdateFoodDto { private Long foodId; + private Long userId; private String name; private BaseNutrition baseNutrition; - public static UpdateFoodDto of(Long foodId, String name, BaseNutrition baseNutrition) { - return new UpdateFoodDto(foodId, name, baseNutrition); + public static UpdateFoodDto of(Long foodId, Long userId, String name, BaseNutrition baseNutrition) { + return new UpdateFoodDto(foodId, userId, name, baseNutrition); } } diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index cf29add..f44fd11 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -89,7 +89,7 @@ void testUpdateFood() { //when BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); - foodService.updateFood(UpdateFoodDto.of(food.getId(), "testChangedFood", testChangedBaseNutrition)); + foodService.updateFood(UpdateFoodDto.of(food.getId(), 1L,"testChangedFood", testChangedBaseNutrition)); assertEquals("testChangedFood", food.getName()); @@ -110,7 +110,7 @@ void testDeleteFood() { given(foodRepository.existsById(food.getId())).willReturn(true); //when - foodService.deleteFood(food.getId()); + foodService.deleteFood(food.getId(), user.getId()); verify(foodRepository, times(1)).deleteById(food.getId()); } @@ -152,7 +152,7 @@ void testUpdateFavoriteFood() { //when BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); - foodService.updateFavoriteFood(UpdateFavoriteFoodDto.of(favoriteFood.getId(), "testChangedFood", testChangedBaseNutrition)); + foodService.updateFavoriteFood(UpdateFavoriteFoodDto.of(favoriteFood.getId(), 1L,"testChangedFood", testChangedBaseNutrition)); assertEquals("testChangedFood", favoriteFood.getName()); assertEquals(2,favoriteFood.getBaseNutrition().getKcal()); @@ -172,7 +172,7 @@ void testDeleteFavoriteFood() { given(favoriteFoodRepository.existsById(favoriteFood.getId())).willReturn(true); //when - foodService.deleteFavoriteFood(favoriteFood.getId()); + foodService.deleteFavoriteFood(favoriteFood.getId(), user.getId()); verify(favoriteFoodRepository, times(1)).deleteById(favoriteFood.getId()); } From 97ed35b695df69ad586a3e89b3034d5ffea4a7f2 Mon Sep 17 00:00:00 2001 From: CHAE Date: Wed, 1 Nov 2023 01:21:52 +0900 Subject: [PATCH 142/371] =?UTF-8?q?:sparkles:=20Feat:=20CreateFoodDto?= =?UTF-8?q?=EC=97=90=20date=20=EC=86=8D=EC=84=B1=20=EC=B6=94=EA=B0=80=20(#?= =?UTF-8?q?44)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/dto/CreateFoodDto.java | 7 +++++-- .../java/com/diareat/diareat/service/FoodServiceTest.java | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java index 1b4a7df..0f07e40 100644 --- a/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java @@ -5,6 +5,8 @@ import lombok.Getter; import lombok.NoArgsConstructor; +import java.time.LocalDate; + @Getter @NoArgsConstructor @AllArgsConstructor @@ -13,8 +15,9 @@ public class CreateFoodDto { private Long userId; private String name; private BaseNutrition baseNutrition; + private LocalDate date; - public static CreateFoodDto of(Long userId, String name, BaseNutrition baseNutrition) { - return new CreateFoodDto(userId, name, baseNutrition); + public static CreateFoodDto of(Long userId, String name, BaseNutrition baseNutrition, LocalDate date) { + return new CreateFoodDto(userId, name, baseNutrition, date); } } diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index f44fd11..6ab8090 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -57,7 +57,7 @@ void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리 User user = User.createUser("testUser", "testImage","testPassword", 1,180, 80,18, testBaseNutrition); user.setId(1L); - CreateFoodDto createFoodDto = CreateFoodDto.of(user.getId(), "testFood", testBaseNutrition); + CreateFoodDto createFoodDto = CreateFoodDto.of(user.getId(), "testFood", testBaseNutrition, LocalDate.now()); Food food = Food.createFood("testFood", user, testBaseNutrition); food.setId(2L); From dbe60788fcdf80dd7e38b5b3da9d0d30a2f448e4 Mon Sep 17 00:00:00 2001 From: CHAE Date: Wed, 1 Nov 2023 01:23:21 +0900 Subject: [PATCH 143/371] =?UTF-8?q?:sparkles:=20Feat:=20FoodService=20?= =?UTF-8?q?=EC=BA=90=EC=8B=B1=20=EC=A0=81=EC=9A=A9=20(#44)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 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 ea55b59..16a968f 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -15,8 +15,10 @@ import com.diareat.diareat.util.exception.FoodException; import com.diareat.diareat.util.exception.UserException; import lombok.RequiredArgsConstructor; +import org.springframework.cache.annotation.CacheEvict; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.cache.annotation.Cacheable; import java.time.DayOfWeek; import java.time.LocalDate; @@ -33,6 +35,7 @@ public class FoodService { private final UserRepository userRepository; // 촬영 후, 음식 정보 저장 + @CacheEvict(value = "ResponseFoodDto", key = "#createFoodDto.getUserId()+#createFoodDto.getDate()", cacheManager = "diareatCacheManager") @Transactional public Long saveFood(CreateFoodDto createFoodDto) { User user = getUserById(createFoodDto.getUserId()); @@ -40,7 +43,8 @@ public Long saveFood(CreateFoodDto createFoodDto) { return foodRepository.save(food).getId(); } - // 회원이 특정 날짜에 먹은 음식 반환 + // 회원이 특정 날짜에 먹은 음식 조회 + @Cacheable(value = "ResponseFoodDto", key = "#userId+#date", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) public List getFoodListByDate(Long userId, LocalDate date){ validateUser(userId); @@ -49,22 +53,25 @@ public List getFoodListByDate(Long userId, LocalDate date){ .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getDate(), food.getTime(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); } - // 음식 정보 수정 + @CacheEvict(value = "ResponseFoodDto", key = "#updateFoodDto.getUserId()", cacheManager = "diareatCacheManager") @Transactional public void updateFood(UpdateFoodDto updateFoodDto) { Food food = getFoodById(updateFoodDto.getFoodId()); food.updateFood(updateFoodDto.getName(), updateFoodDto.getBaseNutrition()); + foodRepository.save(food); } // 음식 삭제 + @CacheEvict(value = "ResponseFoodDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional - public void deleteFood(Long foodId) { + public void deleteFood(Long foodId, Long userId) { validateFood(foodId); foodRepository.deleteById(foodId); } // 즐겨찾기에 음식 저장 + @CacheEvict(value = "ResponseFavoriteFoodDto", key = "#createFavoriteFoodDto.getUserId()", cacheManager = "diareatCacheManager") @Transactional public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { User user = getUserById(createFavoriteFoodDto.getUserId()); @@ -75,6 +82,7 @@ public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { } //즐겨찾기 음식 리스트 반환 + @Cacheable(value = "ResponseFavoriteFoodDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) public List getFavoriteFoodList(Long userId){ validateUser(userId); @@ -85,19 +93,23 @@ public List getFavoriteFoodList(Long userId){ } // 즐겨찾기 음식 수정 + @CacheEvict(value = "ResponseFavoriteFoodDto", key = "updateFavoriteFoodDto.getUserId()", cacheManager = "diareatCacheManager") @Transactional public void updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto) { FavoriteFood food = getFavoriteFoodById(updateFavoriteFoodDto.getFavoriteFoodId()); food.updateFavoriteFood(updateFavoriteFoodDto.getName(), updateFavoriteFoodDto.getBaseNutrition()); + favoriteFoodRepository.save(food); } // 즐겨찾기 해제 + @CacheEvict(value = "ResponseFavoriteFoodDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional - public void deleteFavoriteFood(Long favoriteFoodId) { + public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { validateFavoriteFood(favoriteFoodId); favoriteFoodRepository.deleteById(favoriteFoodId); } + @Cacheable(value = "ResponseNutritionSumByDateDto", key = "#userId+#date", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { @@ -178,6 +190,7 @@ public ResponseFoodRankDto getWorstFoodByWeek(Long userId) { // 유저의 일기 분석 그래프 데이터 및 식습관 totalScore 조회 + @Cacheable(value = "ResponseRankUserDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) // 유저의 식습관 점수를 기반으로 한 주간 랭킹 조회 public List getUserRankByWeek(Long userId) { From 25ba044829b87765fb58c5f73f8989fe54447d0f Mon Sep 17 00:00:00 2001 From: CHAE Date: Wed, 1 Nov 2023 01:31:39 +0900 Subject: [PATCH 144/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20Refactor:=20?= =?UTF-8?q?=EC=9D=8C=EC=8B=9D/=EC=A6=90=EC=B0=BE=EC=9D=8C=EC=8B=9D=20?= =?UTF-8?q?=EC=82=AD=EC=A0=9C=20=EA=B8=B0=EB=8A=A5=20=EC=9C=A0=ED=9A=A8?= =?UTF-8?q?=EC=84=B1=EA=B2=80=EC=82=AC=20=EB=B3=B4=EA=B0=95=20(#44)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../food/repository/FavoriteFoodRepository.java | 1 + .../diareat/food/repository/FoodRepository.java | 1 + .../diareat/food/service/FoodService.java | 16 ++++++++++------ .../diareat/diareat/util/api/ResponseCode.java | 1 + 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java b/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java index 1bd1248..fad8f7c 100644 --- a/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java +++ b/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java @@ -7,5 +7,6 @@ public interface FavoriteFoodRepository extends JpaRepository { List findAllByUserId(Long userId); + boolean existsByIdAndUserId(Long id, Long userId); // 유저가 즐겨찾기에 추가한 음식인지 확인 boolean existsByFoodId(Long foodId); // 이미 즐겨찾기에 추가된 음식인지 확인하기 위함 } 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 7625379..b206e45 100644 --- a/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java +++ b/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java @@ -7,6 +7,7 @@ import java.util.List; public interface FoodRepository extends JpaRepository { + boolean existsByIdAndUserId(Long id, Long userId); // 유저가 먹은 음식인지 확인 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 16a968f..281c627 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -66,7 +66,7 @@ public void updateFood(UpdateFoodDto updateFoodDto) { @CacheEvict(value = "ResponseFoodDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional public void deleteFood(Long foodId, Long userId) { - validateFood(foodId); + validateFood(foodId, userId); foodRepository.deleteById(foodId); } @@ -105,7 +105,7 @@ public void updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto) { @CacheEvict(value = "ResponseFavoriteFoodDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { - validateFavoriteFood(favoriteFoodId); + validateFavoriteFood(favoriteFoodId, userId); favoriteFoodRepository.deleteById(favoriteFoodId); } @@ -281,14 +281,18 @@ private void validateUser(Long userId) { throw new UserException(ResponseCode.USER_NOT_FOUND); } - private void validateFood(Long foodId) { - if (!foodRepository.existsById(foodId)) + private void validateFood(Long foodId, Long userId) { + if(!foodRepository.existsById(foodId)) throw new FoodException(ResponseCode.FOOD_NOT_FOUND); + if (!foodRepository.existsByIdAndUserId(foodId, userId)) // 음식의 주인이 유저인지 아닌지 판정 + throw new FoodException(ResponseCode.NOT_FOOD_OWNER); } - private void validateFavoriteFood(Long favoriteFoodId) { - if (!favoriteFoodRepository.existsById(favoriteFoodId)) + private void validateFavoriteFood(Long favoriteFoodId, Long userId) { + if(!favoriteFoodRepository.existsById(favoriteFoodId)) throw new FavoriteException(ResponseCode.FAVORITE_NOT_FOUND); + if(!favoriteFoodRepository.existsByIdAndUserId(favoriteFoodId, userId)) // 즐겨찾는 음식의 주인이 유저인지 아닌지 판정 + throw new FavoriteException(ResponseCode.NOT_FOOD_OWNER); } // 1주일동안 먹은 음식들의 영양성분 총합을 요일을 Key로 한 Map을 통해 반환 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 3185dd9..d80d3de 100644 --- a/src/main/java/com/diareat/diareat/util/api/ResponseCode.java +++ b/src/main/java/com/diareat/diareat/util/api/ResponseCode.java @@ -14,6 +14,7 @@ public enum ResponseCode { // 403 Forbidden FORBIDDEN(HttpStatus.FORBIDDEN, false, "권한이 없습니다."), + NOT_FOOD_OWNER(HttpStatus.FORBIDDEN, false, "음식의 주인 유저가 아닙니다."), // 404 Not Found USER_NOT_FOUND(HttpStatus.NOT_FOUND, false, "사용자를 찾을 수 없습니다."), From 804286355d425a26c42f6d043ed19def60f4918d Mon Sep 17 00:00:00 2001 From: CHAE Date: Wed, 1 Nov 2023 01:40:47 +0900 Subject: [PATCH 145/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20Refactor:=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=EC=BD=94=EB=93=9C=EC=97=90=20?= =?UTF-8?q?=EC=9C=A0=ED=9A=A8=EC=84=B1=EA=B2=80=EC=82=AC=20=EB=B0=98?= =?UTF-8?q?=EC=98=81=20(#44)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/FoodServiceTest.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 6ab8090..b2bf4ac 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -98,7 +98,7 @@ void testUpdateFood() { assertEquals(4,food.getBaseNutrition().getProtein()); assertEquals(5,food.getBaseNutrition().getFat()); } -// + // @Test void testDeleteFood() { //given @@ -108,9 +108,10 @@ void testDeleteFood() { food.setId(1L); given(foodRepository.existsById(food.getId())).willReturn(true); + given(foodRepository.existsByIdAndUserId(food.getId(), 1L)).willReturn(true); //when - foodService.deleteFood(food.getId(), user.getId()); + foodService.deleteFood(food.getId(), 1L); verify(foodRepository, times(1)).deleteById(food.getId()); } @@ -160,7 +161,7 @@ void testUpdateFavoriteFood() { assertEquals(4,favoriteFood.getBaseNutrition().getProtein()); assertEquals(5,favoriteFood.getBaseNutrition().getFat()); } -// + // @Test void testDeleteFavoriteFood() { //given @@ -170,13 +171,14 @@ void testDeleteFavoriteFood() { favoriteFood.setId(1L); given(favoriteFoodRepository.existsById(favoriteFood.getId())).willReturn(true); + given(favoriteFoodRepository.existsByIdAndUserId(favoriteFood.getId(), 1L)).willReturn(true); //when - foodService.deleteFavoriteFood(favoriteFood.getId(), user.getId()); + foodService.deleteFavoriteFood(favoriteFood.getId(), 1L); verify(favoriteFoodRepository, times(1)).deleteById(favoriteFood.getId()); } -// + // @Test void testNutritionSumByDate(){ //given @@ -203,7 +205,7 @@ void testNutritionSumByDate(){ assertEquals(Math.round((((double)200 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioProtein()); assertEquals(Math.round((((double)250 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioFat()); } -// + // @Test void testNutritionSumByWeek(){ //given @@ -261,7 +263,7 @@ void testNutritionSumByMonth(){ assertEquals(Math.round((((double)250 / (double)80) * 100.0)*100.0)/100.0, responseNutritionSumByDateDto.getRatioFat()); } -// + // @Test void getBest3FoodTest() { // given @@ -288,7 +290,7 @@ void getBest3FoodTest() { assertEquals("Food2", top3Foods.get(1).getName()); assertEquals("Food3", top3Foods.get(2).getName()); } -// + // @Test void getWorst3FoodsTest() { // given From 96c374326fc4b42f42fb4a14d15d03dbeec791c9 Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 2 Nov 2023 10:01:27 +0900 Subject: [PATCH 146/371] =?UTF-8?q?:package:=20Chore:=20Dto=20=EC=9A=94?= =?UTF-8?q?=EC=B2=AD/=EC=9D=91=EB=8B=B5=EC=9C=BC=EB=A1=9C=20=ED=8C=A8?= =?UTF-8?q?=ED=82=A4=EC=A7=80=20=EB=B6=84=EB=A6=AC=20(#47)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/service/KakaoAuthService.java | 4 +-- .../diareat/food/service/FoodService.java | 2 +- .../diareat/user/dto/FollowUserDto.java | 14 --------- .../diareat/diareat/user/dto/JoinUserDto.java | 18 ----------- .../user/dto/{ => request}/CreateUserDto.java | 2 +- .../diareat/user/dto/request/JoinUserDto.java | 30 +++++++++++++++++++ .../user/dto/{ => request}/SearchUserDto.java | 8 ++++- .../user/dto/{ => request}/UpdateUserDto.java | 2 +- .../{ => request}/UpdateUserNutritionDto.java | 2 +- .../{ => response}/ResponseRankUserDto.java | 2 +- .../{ => response}/ResponseSearchUserDto.java | 2 +- .../{ => response}/ResponseSimpleUserDto.java | 2 +- .../dto/{ => response}/ResponseUserDto.java | 2 +- .../ResponseUserNutritionDto.java | 2 +- .../diareat/user/service/UserService.java | 8 ++++- .../controller/UserControllerTest.java | 7 ++++- .../diareat/service/FoodServiceTest.java | 2 +- .../diareat/service/UserServiceTest.java | 8 ++++- 18 files changed, 69 insertions(+), 48 deletions(-) delete mode 100644 src/main/java/com/diareat/diareat/user/dto/FollowUserDto.java delete mode 100644 src/main/java/com/diareat/diareat/user/dto/JoinUserDto.java rename src/main/java/com/diareat/diareat/user/dto/{ => request}/CreateUserDto.java (92%) create mode 100644 src/main/java/com/diareat/diareat/user/dto/request/JoinUserDto.java rename src/main/java/com/diareat/diareat/user/dto/{ => request}/SearchUserDto.java (55%) rename src/main/java/com/diareat/diareat/user/dto/{ => request}/UpdateUserDto.java (93%) rename src/main/java/com/diareat/diareat/user/dto/{ => request}/UpdateUserNutritionDto.java (91%) rename src/main/java/com/diareat/diareat/user/dto/{ => response}/ResponseRankUserDto.java (93%) rename src/main/java/com/diareat/diareat/user/dto/{ => response}/ResponseSearchUserDto.java (90%) rename src/main/java/com/diareat/diareat/user/dto/{ => response}/ResponseSimpleUserDto.java (89%) rename src/main/java/com/diareat/diareat/user/dto/{ => response}/ResponseUserDto.java (92%) rename src/main/java/com/diareat/diareat/user/dto/{ => response}/ResponseUserNutritionDto.java (96%) diff --git a/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java b/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java index 0d22bc4..c5ce759 100644 --- a/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java +++ b/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java @@ -3,8 +3,8 @@ import com.diareat.diareat.auth.component.KakaoUserInfo; import com.diareat.diareat.auth.dto.KakaoUserInfoResponse; import com.diareat.diareat.user.domain.User; -import com.diareat.diareat.user.dto.CreateUserDto; -import com.diareat.diareat.user.dto.JoinUserDto; +import com.diareat.diareat.user.dto.request.CreateUserDto; +import com.diareat.diareat.user.dto.request.JoinUserDto; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.util.api.ResponseCode; import com.diareat.diareat.util.exception.UserException; 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 281c627..be3f3cf 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -7,7 +7,7 @@ import com.diareat.diareat.food.repository.FoodRepository; import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; -import com.diareat.diareat.user.dto.ResponseRankUserDto; +import com.diareat.diareat.user.dto.response.ResponseRankUserDto; import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.util.api.ResponseCode; diff --git a/src/main/java/com/diareat/diareat/user/dto/FollowUserDto.java b/src/main/java/com/diareat/diareat/user/dto/FollowUserDto.java deleted file mode 100644 index 336a337..0000000 --- a/src/main/java/com/diareat/diareat/user/dto/FollowUserDto.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.diareat.diareat.user.dto; - -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; - -@Getter -@NoArgsConstructor -@AllArgsConstructor -public class FollowUserDto { - - private Long userId; - private Long followUserId; -} diff --git a/src/main/java/com/diareat/diareat/user/dto/JoinUserDto.java b/src/main/java/com/diareat/diareat/user/dto/JoinUserDto.java deleted file mode 100644 index 2433db1..0000000 --- a/src/main/java/com/diareat/diareat/user/dto/JoinUserDto.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.diareat.diareat.user.dto; - -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; - -@Getter -@NoArgsConstructor -@AllArgsConstructor -public class JoinUserDto { - - private String token; - private String nickName; - private int gender; - private int height; - private int weight; - private int age; -} diff --git a/src/main/java/com/diareat/diareat/user/dto/CreateUserDto.java b/src/main/java/com/diareat/diareat/user/dto/request/CreateUserDto.java similarity index 92% rename from src/main/java/com/diareat/diareat/user/dto/CreateUserDto.java rename to src/main/java/com/diareat/diareat/user/dto/request/CreateUserDto.java index 5c463ef..3f96ce9 100644 --- a/src/main/java/com/diareat/diareat/user/dto/CreateUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/CreateUserDto.java @@ -1,4 +1,4 @@ -package com.diareat.diareat.user.dto; +package com.diareat.diareat.user.dto.request; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/com/diareat/diareat/user/dto/request/JoinUserDto.java b/src/main/java/com/diareat/diareat/user/dto/request/JoinUserDto.java new file mode 100644 index 0000000..e0cde9d --- /dev/null +++ b/src/main/java/com/diareat/diareat/user/dto/request/JoinUserDto.java @@ -0,0 +1,30 @@ +package com.diareat.diareat.user.dto.request; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.*; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class JoinUserDto { + + @NotNull(message = "token은 null이 될 수 없습니다.") + private String token; + + @NotBlank(message = "nickName은 비어있을 수 없습니다.") + private String nickName; + + @DecimalMin(value = "0", message = "gender는 0(남자), 1(여자)만 가능합니다.") + @DecimalMax(value = "1", message = "gender는 0(남자), 1(여자)만 가능합니다.") + private int gender; + + private int height; + + private int weight; + + private int age; + +} diff --git a/src/main/java/com/diareat/diareat/user/dto/SearchUserDto.java b/src/main/java/com/diareat/diareat/user/dto/request/SearchUserDto.java similarity index 55% rename from src/main/java/com/diareat/diareat/user/dto/SearchUserDto.java rename to src/main/java/com/diareat/diareat/user/dto/request/SearchUserDto.java index d6aa5db..e2c97c3 100644 --- a/src/main/java/com/diareat/diareat/user/dto/SearchUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/SearchUserDto.java @@ -1,15 +1,21 @@ -package com.diareat.diareat.user.dto; +package com.diareat.diareat.user.dto.request; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + @Getter @NoArgsConstructor @AllArgsConstructor public class SearchUserDto { + @NotNull(message = "userId는 null이 될 수 없습니다.") private Long userId; + + @NotEmpty(message = "검색 문자열은 비어있을 수 없습니다.") private String inputName; public static SearchUserDto of(Long userId, String inputName) { diff --git a/src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java similarity index 93% rename from src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java rename to src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java index 1a643d4..f3010fc 100644 --- a/src/main/java/com/diareat/diareat/user/dto/UpdateUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java @@ -1,4 +1,4 @@ -package com.diareat.diareat.user.dto; +package com.diareat.diareat.user.dto.request; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/com/diareat/diareat/user/dto/UpdateUserNutritionDto.java b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserNutritionDto.java similarity index 91% rename from src/main/java/com/diareat/diareat/user/dto/UpdateUserNutritionDto.java rename to src/main/java/com/diareat/diareat/user/dto/request/UpdateUserNutritionDto.java index a5e6aee..e334ac9 100644 --- a/src/main/java/com/diareat/diareat/user/dto/UpdateUserNutritionDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserNutritionDto.java @@ -1,4 +1,4 @@ -package com.diareat.diareat.user.dto; +package com.diareat.diareat.user.dto.request; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseRankUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java similarity index 93% rename from src/main/java/com/diareat/diareat/user/dto/ResponseRankUserDto.java rename to src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java index c4c0700..5e1829d 100644 --- a/src/main/java/com/diareat/diareat/user/dto/ResponseRankUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java @@ -1,4 +1,4 @@ -package com.diareat.diareat.user.dto; +package com.diareat.diareat.user.dto.response; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java similarity index 90% rename from src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java rename to src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java index 811fa92..247e548 100644 --- a/src/main/java/com/diareat/diareat/user/dto/ResponseSearchUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java @@ -1,4 +1,4 @@ -package com.diareat.diareat.user.dto; +package com.diareat.diareat.user.dto.response; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseSimpleUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java similarity index 89% rename from src/main/java/com/diareat/diareat/user/dto/ResponseSimpleUserDto.java rename to src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java index b56e7f6..650b9cb 100644 --- a/src/main/java/com/diareat/diareat/user/dto/ResponseSimpleUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java @@ -1,4 +1,4 @@ -package com.diareat.diareat.user.dto; +package com.diareat.diareat.user.dto.response; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java similarity index 92% rename from src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java rename to src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java index dcda49f..495c975 100644 --- a/src/main/java/com/diareat/diareat/user/dto/ResponseUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java @@ -1,4 +1,4 @@ -package com.diareat.diareat.user.dto; +package com.diareat.diareat.user.dto.response; import com.diareat.diareat.user.domain.User; import lombok.AllArgsConstructor; diff --git a/src/main/java/com/diareat/diareat/user/dto/ResponseUserNutritionDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java similarity index 96% rename from src/main/java/com/diareat/diareat/user/dto/ResponseUserNutritionDto.java rename to src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java index 41a6826..1fece0d 100644 --- a/src/main/java/com/diareat/diareat/user/dto/ResponseUserNutritionDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java @@ -1,4 +1,4 @@ -package com.diareat.diareat.user.dto; +package com.diareat.diareat.user.dto.response; import com.diareat.diareat.user.domain.User; import lombok.AllArgsConstructor; diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index f1206cd..894bed9 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -3,7 +3,13 @@ import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.Follow; import com.diareat.diareat.user.domain.User; -import com.diareat.diareat.user.dto.*; +import com.diareat.diareat.user.dto.request.CreateUserDto; +import com.diareat.diareat.user.dto.request.UpdateUserDto; +import com.diareat.diareat.user.dto.request.UpdateUserNutritionDto; +import com.diareat.diareat.user.dto.response.ResponseSearchUserDto; +import com.diareat.diareat.user.dto.response.ResponseSimpleUserDto; +import com.diareat.diareat.user.dto.response.ResponseUserDto; +import com.diareat.diareat.user.dto.response.ResponseUserNutritionDto; import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.util.UserTypeUtil; diff --git a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java index e3dc3e0..9eb7c22 100644 --- a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java @@ -4,7 +4,12 @@ import com.diareat.diareat.user.controller.UserController; import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; -import com.diareat.diareat.user.dto.*; +import com.diareat.diareat.user.dto.request.UpdateUserDto; +import com.diareat.diareat.user.dto.request.UpdateUserNutritionDto; +import com.diareat.diareat.user.dto.response.ResponseSearchUserDto; +import com.diareat.diareat.user.dto.response.ResponseSimpleUserDto; +import com.diareat.diareat.user.dto.response.ResponseUserDto; +import com.diareat.diareat.user.dto.response.ResponseUserNutritionDto; import com.diareat.diareat.user.service.UserService; import com.diareat.diareat.util.api.ApiResponse; import com.diareat.diareat.util.api.ResponseCode; diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index b2bf4ac..d44077f 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -8,7 +8,7 @@ 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.ResponseRankUserDto; +import com.diareat.diareat.user.dto.response.ResponseRankUserDto; import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; import org.junit.jupiter.api.DisplayName; diff --git a/src/test/java/com/diareat/diareat/service/UserServiceTest.java b/src/test/java/com/diareat/diareat/service/UserServiceTest.java index 98641d4..1bbbbc6 100644 --- a/src/test/java/com/diareat/diareat/service/UserServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/UserServiceTest.java @@ -3,7 +3,13 @@ import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.Follow; import com.diareat.diareat.user.domain.User; -import com.diareat.diareat.user.dto.*; +import com.diareat.diareat.user.dto.request.CreateUserDto; +import com.diareat.diareat.user.dto.request.UpdateUserDto; +import com.diareat.diareat.user.dto.request.UpdateUserNutritionDto; +import com.diareat.diareat.user.dto.response.ResponseSearchUserDto; +import com.diareat.diareat.user.dto.response.ResponseSimpleUserDto; +import com.diareat.diareat.user.dto.response.ResponseUserDto; +import com.diareat.diareat.user.dto.response.ResponseUserNutritionDto; import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; import com.diareat.diareat.user.service.UserService; From d410bc7b3783d0c3c2429af0d9d019366d821315 Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 2 Nov 2023 10:07:50 +0900 Subject: [PATCH 147/371] =?UTF-8?q?:art:=20Chore:=20validation=20=EC=9D=98?= =?UTF-8?q?=EC=A1=B4=EC=84=B1=20=EC=B6=94=EA=B0=80=20=EB=B0=8F=20=EC=9D=91?= =?UTF-8?q?=EB=8B=B5=EA=B0=9D=EC=B2=B4=20=EC=88=98=EC=A0=95,=20=EC=98=88?= =?UTF-8?q?=EC=99=B8=EC=B2=98=EB=A6=AC=20=EB=B3=B4=EA=B0=95=20(#47)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 3 +++ .../diareat/diareat/util/api/ApiResponse.java | 4 +-- .../exception/GlobalExceptionHandler.java | 27 +++++++++++++++---- 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/build.gradle b/build.gradle index 601d52e..9fc03f3 100644 --- a/build.gradle +++ b/build.gradle @@ -52,6 +52,9 @@ dependencies { // Redis dependency implementation 'org.springframework.boot:spring-boot-starter-data-redis' + + // Validation dependency + implementation 'org.springframework.boot:spring-boot-starter-validation' } tasks.named('test') { diff --git a/src/main/java/com/diareat/diareat/util/api/ApiResponse.java b/src/main/java/com/diareat/diareat/util/api/ApiResponse.java index ba96c5e..1f5c4d9 100644 --- a/src/main/java/com/diareat/diareat/util/api/ApiResponse.java +++ b/src/main/java/com/diareat/diareat/util/api/ApiResponse.java @@ -23,7 +23,7 @@ public static ApiResponse success(T data, String message) { return new ApiResponse(new ApiHeader(SUCCESS, "SUCCESS"), data, message); } - public static ApiResponse fail(ResponseCode responseCode) { - return new ApiResponse(new ApiHeader(responseCode.getHttpStatusCode(), responseCode.getMessage()), null, responseCode.getMessage()); + public static ApiResponse fail(ResponseCode responseCode, T data) { + return new ApiResponse(new ApiHeader(responseCode.getHttpStatusCode(), responseCode.getMessage()), data, responseCode.getMessage()); } } \ No newline at end of file diff --git a/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java b/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java index d8e5cad..4eb97d2 100644 --- a/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java @@ -1,29 +1,46 @@ package com.diareat.diareat.util.exception; import com.diareat.diareat.util.api.ApiResponse; +import com.diareat.diareat.util.api.ResponseCode; import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.HashMap; +import java.util.Map; @Slf4j -@ControllerAdvice +@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(UserException.class) public ApiResponse handleUserException(UserException e) { log.info("UserException: {}", e.getMessage()); - return ApiResponse.fail(e.getResponseCode()); + return ApiResponse.fail(e.getResponseCode(), null); } @ExceptionHandler(FavoriteException.class) public ApiResponse handleFavoriteException(FavoriteException e) { log.info("FavoriteException: {}", e.getMessage()); - return ApiResponse.fail(e.getResponseCode()); + return ApiResponse.fail(e.getResponseCode(), null); } @ExceptionHandler(FoodException.class) public ApiResponse handleFoodException(FoodException e) { log.info("FoodException: {}", e.getMessage()); - return ApiResponse.fail(e.getResponseCode()); + return ApiResponse.fail(e.getResponseCode(), null); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) // 요청의 유효성 검사 실패 시 + public ApiResponse> handleInValidRequestException(MethodArgumentNotValidException e) { + // 에러가 발생한 객체 내 필드와 대응하는 에러 메시지를 map에 저장하여 반환 + Map errors = new HashMap<>(); + e.getBindingResult().getFieldErrors().forEach(error -> { + String fieldName = error.getField(); + String errorMessage = error.getDefaultMessage(); + errors.put(fieldName, errorMessage); + }); + return ApiResponse.fail(ResponseCode.BAD_REQUEST, errors); } } From 58d55d55ed611088f20e02997660b1c728ca8285 Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 2 Nov 2023 10:09:24 +0900 Subject: [PATCH 148/371] =?UTF-8?q?:adhesive=5Fbandage:=20Fix:=20Jwt=20?= =?UTF-8?q?=ED=86=A0=ED=81=B0=20=EB=B0=98=ED=99=98=EC=8B=9C=EA=B0=84=206?= =?UTF-8?q?=EC=8B=9C=EA=B0=84=EC=9C=BC=EB=A1=9C=20=EC=97=B0=EC=9E=A5=20(#4?= =?UTF-8?q?7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/auth/component/JwtTokenProvider.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java index 76ff826..eed48e3 100644 --- a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java +++ b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java @@ -39,7 +39,7 @@ public String createToken(String userPk) { return Jwts.builder() .setClaims(claims) // 정보 저장 .setIssuedAt(now) // 토큰 발행 시간 정보 - .setExpiration(new Date(now.getTime() + (30 * 60 * 1000L))) // 토큰 유효시각 설정 (30분) + .setExpiration(new Date(now.getTime() + (360 * 60 * 1000L))) // 토큰 유효시각 설정 (360분) .signWith(SignatureAlgorithm.HS256, secretKey) // 암호화 알고리즘과, secret 값 .compact(); } From 1f5633e47c569ff12b39b079fd733fd7039bd315 Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 2 Nov 2023 10:10:27 +0900 Subject: [PATCH 149/371] =?UTF-8?q?:safety=5Fvest:=20Refactor:=20Auth,=20U?= =?UTF-8?q?ser=20Controller=20@Valid=20=EC=B6=94=EA=B0=80=20(#47)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/controller/AuthController.java | 5 ++-- .../user/controller/UserController.java | 25 +++++++++++-------- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java index 385b7d2..05032eb 100644 --- a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java +++ b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java @@ -2,7 +2,7 @@ import com.diareat.diareat.auth.component.JwtTokenProvider; import com.diareat.diareat.auth.service.KakaoAuthService; -import com.diareat.diareat.user.dto.JoinUserDto; +import com.diareat.diareat.user.dto.request.JoinUserDto; import com.diareat.diareat.user.service.UserService; import com.diareat.diareat.util.api.ApiResponse; import com.diareat.diareat.util.api.ResponseCode; @@ -11,6 +11,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; +import javax.validation.Valid; import java.util.HashMap; @Api(tags = "2. Auth") @@ -36,7 +37,7 @@ public ApiResponse> authCheck(@RequestHeader String access // 회원가입 (성공 시 Jwt 토큰 발급) @Operation(summary = "[회원가입] 회원가입 및 토큰 발급", description = "신규 회원가입을 처리하고, 회원가입 성공 시 Jwt 토큰을 발급합니다.") @PostMapping("/join") - public ApiResponse> saveUser(JoinUserDto joinUserDto) { + public ApiResponse> saveUser(@Valid @RequestBody JoinUserDto joinUserDto) { Long userId = userService.saveUser(kakaoAuthService.createUserDto(joinUserDto)); HashMap map = new HashMap<>(); map.put(userId, jwtTokenProvider.createToken(userId.toString())); diff --git a/src/main/java/com/diareat/diareat/user/controller/UserController.java b/src/main/java/com/diareat/diareat/user/controller/UserController.java index e8c4af9..67fecb3 100644 --- a/src/main/java/com/diareat/diareat/user/controller/UserController.java +++ b/src/main/java/com/diareat/diareat/user/controller/UserController.java @@ -1,6 +1,12 @@ package com.diareat.diareat.user.controller; -import com.diareat.diareat.user.dto.*; +import com.diareat.diareat.user.dto.request.SearchUserDto; +import com.diareat.diareat.user.dto.request.UpdateUserDto; +import com.diareat.diareat.user.dto.request.UpdateUserNutritionDto; +import com.diareat.diareat.user.dto.response.ResponseSearchUserDto; +import com.diareat.diareat.user.dto.response.ResponseSimpleUserDto; +import com.diareat.diareat.user.dto.response.ResponseUserDto; +import com.diareat.diareat.user.dto.response.ResponseUserNutritionDto; import com.diareat.diareat.user.service.UserService; import com.diareat.diareat.util.api.ApiResponse; import com.diareat.diareat.util.api.ResponseCode; @@ -9,6 +15,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; +import javax.validation.Valid; import java.util.List; @Api(tags = "1. User") @@ -36,7 +43,7 @@ public ApiResponse getUserInfo(@PathVariable Long userId) { // 회원정보 수정 @Operation(summary = "[프로필] 회원 정보 수정", description = "회원 정보를 수정합니다.") @PutMapping("/update") - public ApiResponse updateUserInfo(UpdateUserDto updateUserDto) { + public ApiResponse updateUserInfo(@Valid @RequestBody UpdateUserDto updateUserDto) { userService.updateUserInfo(updateUserDto); return ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); } @@ -51,26 +58,24 @@ public ApiResponse getUserNutrition(@PathVariable Long // 회원 기준섭취량 직접 수정 @Operation(summary = "[프로필] 회원 기준섭취량 직접 수정", description = "회원 기준섭취량을 직접 수정합니다.") @PutMapping("{userId}/nutrition") - public ApiResponse updateUserNutrition(UpdateUserNutritionDto updateUserNutritionDto) { + public ApiResponse updateUserNutrition(@Valid @RequestBody UpdateUserNutritionDto updateUserNutritionDto) { userService.updateBaseNutrition(updateUserNutritionDto); return ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); } // 회원의 친구 검색 결과 조회 @Operation(summary = "[주간 랭킹] 회원의 친구 검색 결과 조회", description = "회원의 친구 검색 결과를 조회합니다.") - @GetMapping("{userId}/search/{name}") - public ApiResponse> searchUser(@PathVariable Long userId, @RequestParam String name) { - return ApiResponse.success(userService.searchUser(userId, name), ResponseCode.USER_SEARCH_SUCCESS.getMessage()); + @GetMapping("/search") + public ApiResponse> searchUser(@Valid @RequestBody SearchUserDto searchUserDto) { + return ApiResponse.success(userService.searchUser(searchUserDto.getUserId(), searchUserDto.getInputName()), ResponseCode.USER_SEARCH_SUCCESS.getMessage()); } - // 실제 팔로잉 유저들의 점수 계산하여 랭킹 형태로 반환하는 API: FoodService에서 계산할지 UserService에서 FoodRepository를 콜해서 처리할지 협의 필요 - // 회원이 특정 회원 팔로우 @Operation(summary = "[주간 랭킹] 회원이 특정 회원 팔로우", description = "회원이 특정 회원을 팔로우합니다.") @PostMapping("{userId}/follow/{followId}") public ApiResponse followUser(@PathVariable Long userId, @PathVariable Long followId) { userService.followUser(userId, followId); - return ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); + return ApiResponse.success(null, ResponseCode.USER_FOLLOW_SUCCESS.getMessage()); } // 회원이 특정 회원 팔로우 취소 @@ -78,6 +83,6 @@ public ApiResponse followUser(@PathVariable Long userId, @PathVariable Lon @DeleteMapping("{userId}/follow/{followId}") public ApiResponse unfollowUser(@PathVariable Long userId, @PathVariable Long followId) { userService.unfollowUser(userId, followId); - return ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); + return ApiResponse.success(null, ResponseCode.USER_UNFOLLOW_SUCCESS.getMessage()); } } From 727e612ed3fb58f8c52b0ff35a7b769db7f7f950 Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 2 Nov 2023 11:01:27 +0900 Subject: [PATCH 150/371] =?UTF-8?q?:recycle:=20Refactor:=20ValidCheck=20?= =?UTF-8?q?=EA=B4=80=EB=A0=A8=20=EB=A9=94=EC=8B=9C=EC=A7=80=20=ED=86=B5?= =?UTF-8?q?=ED=95=A9=20=EA=B4=80=EB=A6=AC=20=ED=81=B4=EB=9E=98=EC=8A=A4=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1=20(#47)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/util/MessageUtil.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/util/MessageUtil.java diff --git a/src/main/java/com/diareat/diareat/util/MessageUtil.java b/src/main/java/com/diareat/diareat/util/MessageUtil.java new file mode 100644 index 0000000..df542a7 --- /dev/null +++ b/src/main/java/com/diareat/diareat/util/MessageUtil.java @@ -0,0 +1,21 @@ +package com.diareat.diareat.util; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class MessageUtil { // 반복되는 메시지의 형식을 저장하고 관리 + + public static final String NOT_NULL = "값이 존재해야 합니다."; + public static final String NOT_BLANK = "값이 비어있을 수 없습니다."; + + public static final String HEIGHT_RANGE = "키는 100 이상, 250 이하의 값을 입력해주세요."; + public static final String WEIGHT_RANGE = "몸무게는 30 이상, 200 이하의 값을 입력해주세요."; + public static final String AGE_RANGE = "나이는 5 이상, 100 이하의 값을 입력해주세요."; + public static final String GENDER_RANGE = "성별은 0(남자) 또는 1(여자)의 값을 입력해주세요."; + + public static final String CALORIE_RANGE = "칼로리는 100 이상, 10000 이하의 값을 입력해주세요."; + public static final String CARBOHYDRATE_RANGE = "탄수화물은 100 이상, 500 이하의 값을 입력해주세요."; + public static final String PROTEIN_RANGE = "단백질은 25 이상, 500 이하의 값을 입력해주세요."; + public static final String FAT_RANGE = "지방은 25 이상, 500 이하의 값을 입력해주세요."; +} From 854ace8a85c7e4bc5d65ad3efdea8191ff5f84ae Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 2 Nov 2023 11:02:39 +0900 Subject: [PATCH 151/371] =?UTF-8?q?:recycle:=20Refactor:=20User=20?= =?UTF-8?q?=ED=8C=A8=ED=82=A4=EC=A7=80=20RequestDto=20=EC=9C=A0=ED=9A=A8?= =?UTF-8?q?=EC=84=B1=EA=B2=80=EC=82=AC=20=EA=B5=AC=ED=98=84=20(#47)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/dto/request/CreateUserDto.java | 2 +- .../diareat/user/dto/request/JoinUserDto.java | 15 +++++++++++---- .../user/dto/request/SearchUserDto.java | 7 ++++--- .../user/dto/request/UpdateUserDto.java | 19 +++++++++++++++++++ .../dto/request/UpdateUserNutritionDto.java | 18 ++++++++++++++++++ 5 files changed, 53 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/dto/request/CreateUserDto.java b/src/main/java/com/diareat/diareat/user/dto/request/CreateUserDto.java index 3f96ce9..0e45fde 100644 --- a/src/main/java/com/diareat/diareat/user/dto/request/CreateUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/CreateUserDto.java @@ -7,7 +7,7 @@ @Getter @NoArgsConstructor @AllArgsConstructor -public class CreateUserDto { +public class CreateUserDto { // JoinUserDto에서 검증 절차를 대행하기에 검증절차 생략 private String name; private String image; diff --git a/src/main/java/com/diareat/diareat/user/dto/request/JoinUserDto.java b/src/main/java/com/diareat/diareat/user/dto/request/JoinUserDto.java index e0cde9d..0bd95f7 100644 --- a/src/main/java/com/diareat/diareat/user/dto/request/JoinUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/JoinUserDto.java @@ -1,5 +1,6 @@ package com.diareat.diareat.user.dto.request; +import com.diareat.diareat.util.MessageUtil; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -11,20 +12,26 @@ @AllArgsConstructor public class JoinUserDto { - @NotNull(message = "token은 null이 될 수 없습니다.") + @NotBlank(message = MessageUtil.NOT_BLANK) private String token; - @NotBlank(message = "nickName은 비어있을 수 없습니다.") + @NotBlank(message = MessageUtil.NOT_BLANK) private String nickName; - @DecimalMin(value = "0", message = "gender는 0(남자), 1(여자)만 가능합니다.") - @DecimalMax(value = "1", message = "gender는 0(남자), 1(여자)만 가능합니다.") + @DecimalMin(value = "0", message = MessageUtil.GENDER_RANGE) + @DecimalMax(value = "1", message = MessageUtil.GENDER_RANGE) private int gender; + @DecimalMin(value = "100", message = MessageUtil.HEIGHT_RANGE) + @DecimalMax(value = "250", message = MessageUtil.HEIGHT_RANGE) private int height; + @DecimalMin(value = "30", message = MessageUtil.WEIGHT_RANGE) + @DecimalMax(value = "150", message = MessageUtil.WEIGHT_RANGE) private int weight; + @DecimalMin(value = "5", message = MessageUtil.AGE_RANGE) + @DecimalMax(value = "100", message = MessageUtil.AGE_RANGE) private int age; } diff --git a/src/main/java/com/diareat/diareat/user/dto/request/SearchUserDto.java b/src/main/java/com/diareat/diareat/user/dto/request/SearchUserDto.java index e2c97c3..86843d9 100644 --- a/src/main/java/com/diareat/diareat/user/dto/request/SearchUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/SearchUserDto.java @@ -1,10 +1,11 @@ package com.diareat.diareat.user.dto.request; +import com.diareat.diareat.util.MessageUtil; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; -import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; @Getter @@ -12,10 +13,10 @@ @AllArgsConstructor public class SearchUserDto { - @NotNull(message = "userId는 null이 될 수 없습니다.") + @NotNull(message = MessageUtil.NOT_NULL) private Long userId; - @NotEmpty(message = "검색 문자열은 비어있을 수 없습니다.") + @NotBlank(message = MessageUtil.NOT_BLANK) private String inputName; public static SearchUserDto of(Long userId, String inputName) { diff --git a/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java index f3010fc..9f5821b 100644 --- a/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java @@ -1,19 +1,38 @@ package com.diareat.diareat.user.dto.request; +import com.diareat.diareat.util.MessageUtil; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import javax.validation.constraints.DecimalMax; +import javax.validation.constraints.DecimalMin; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + @Getter @NoArgsConstructor @AllArgsConstructor public class UpdateUserDto { + @NotNull(message = MessageUtil.NOT_NULL) private Long userId; + + @NotBlank(message = MessageUtil.NOT_BLANK) private String name; + + @DecimalMin(value = "100", message = MessageUtil.HEIGHT_RANGE) + @DecimalMax(value = "250", message = MessageUtil.HEIGHT_RANGE) private int height; + + @DecimalMin(value = "30", message = MessageUtil.WEIGHT_RANGE) + @DecimalMax(value = "200", message = MessageUtil.WEIGHT_RANGE) private int weight; + + @DecimalMin(value = "5", message = MessageUtil.AGE_RANGE) + @DecimalMax(value = "100", message = MessageUtil.AGE_RANGE) private int age; + private boolean isAutoUpdateNutrition; // 개인정보를 활용한 기준 영양소 자동계산 여부 public static UpdateUserDto of(Long userId, String userName, int userHeight, int userWeight, int userAge, boolean isAutoUpdateNutrition) { diff --git a/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserNutritionDto.java b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserNutritionDto.java index e334ac9..1ed25d6 100644 --- a/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserNutritionDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserNutritionDto.java @@ -1,18 +1,36 @@ package com.diareat.diareat.user.dto.request; +import com.diareat.diareat.util.MessageUtil; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import javax.validation.constraints.DecimalMax; +import javax.validation.constraints.DecimalMin; +import javax.validation.constraints.NotNull; + @Getter @NoArgsConstructor @AllArgsConstructor public class UpdateUserNutritionDto { + @NotNull(message = MessageUtil.NOT_NULL) private Long userId; + + @DecimalMin(value = "100", message = MessageUtil.CALORIE_RANGE) + @DecimalMax(value = "10000", message = MessageUtil.CALORIE_RANGE) private int calorie; + + @DecimalMin(value = "100", message = MessageUtil.CARBOHYDRATE_RANGE) + @DecimalMax(value = "500", message = MessageUtil.CARBOHYDRATE_RANGE) private int carbohydrate; + + @DecimalMin(value = "25", message = MessageUtil.PROTEIN_RANGE) + @DecimalMax(value = "500", message = MessageUtil.PROTEIN_RANGE) private int protein; + + @DecimalMin(value = "25", message = MessageUtil.FAT_RANGE) + @DecimalMax(value = "500", message = MessageUtil.FAT_RANGE) private int fat; public static UpdateUserNutritionDto of(Long userId, int calorie, int carbohydrate, int protein, int fat) { From d1e3e0723b72b539a50dc583762276e09842401f Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 2 Nov 2023 13:35:17 +0900 Subject: [PATCH 152/371] =?UTF-8?q?:bug:=20Fix:=20ExceptionHandling=20Stat?= =?UTF-8?q?us=20=EB=88=84=EB=9D=BD=EB=90=98=EB=8D=98=20=EB=B2=84=EA=B7=B8?= =?UTF-8?q?=20=EC=88=98=EC=A0=95=20(#47)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/user/controller/UserController.java | 6 +++--- .../diareat/util/exception/GlobalExceptionHandler.java | 3 +++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/controller/UserController.java b/src/main/java/com/diareat/diareat/user/controller/UserController.java index 67fecb3..ff9f0fe 100644 --- a/src/main/java/com/diareat/diareat/user/controller/UserController.java +++ b/src/main/java/com/diareat/diareat/user/controller/UserController.java @@ -43,7 +43,7 @@ public ApiResponse getUserInfo(@PathVariable Long userId) { // 회원정보 수정 @Operation(summary = "[프로필] 회원 정보 수정", description = "회원 정보를 수정합니다.") @PutMapping("/update") - public ApiResponse updateUserInfo(@Valid @RequestBody UpdateUserDto updateUserDto) { + public ApiResponse updateUserInfo(@RequestBody @Valid UpdateUserDto updateUserDto) { userService.updateUserInfo(updateUserDto); return ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); } @@ -58,7 +58,7 @@ public ApiResponse getUserNutrition(@PathVariable Long // 회원 기준섭취량 직접 수정 @Operation(summary = "[프로필] 회원 기준섭취량 직접 수정", description = "회원 기준섭취량을 직접 수정합니다.") @PutMapping("{userId}/nutrition") - public ApiResponse updateUserNutrition(@Valid @RequestBody UpdateUserNutritionDto updateUserNutritionDto) { + public ApiResponse updateUserNutrition(@RequestBody @Valid UpdateUserNutritionDto updateUserNutritionDto) { userService.updateBaseNutrition(updateUserNutritionDto); return ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); } @@ -66,7 +66,7 @@ public ApiResponse updateUserNutrition(@Valid @RequestBody UpdateUserNutri // 회원의 친구 검색 결과 조회 @Operation(summary = "[주간 랭킹] 회원의 친구 검색 결과 조회", description = "회원의 친구 검색 결과를 조회합니다.") @GetMapping("/search") - public ApiResponse> searchUser(@Valid @RequestBody SearchUserDto searchUserDto) { + public ApiResponse> searchUser(@RequestBody @Valid SearchUserDto searchUserDto) { return ApiResponse.success(userService.searchUser(searchUserDto.getUserId(), searchUserDto.getInputName()), ResponseCode.USER_SEARCH_SUCCESS.getMessage()); } diff --git a/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java b/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java index 4eb97d2..856271e 100644 --- a/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java @@ -3,8 +3,10 @@ import com.diareat.diareat.util.api.ApiResponse; import com.diareat.diareat.util.api.ResponseCode; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.HashMap; @@ -33,6 +35,7 @@ public ApiResponse handleFoodException(FoodException e) { } @ExceptionHandler(MethodArgumentNotValidException.class) // 요청의 유효성 검사 실패 시 + @ResponseStatus(HttpStatus.BAD_REQUEST) public ApiResponse> handleInValidRequestException(MethodArgumentNotValidException e) { // 에러가 발생한 객체 내 필드와 대응하는 에러 메시지를 map에 저장하여 반환 Map errors = new HashMap<>(); From 4fd7d403e3208eafeaadc0a275d46b6d800009f8 Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 2 Nov 2023 13:35:56 +0900 Subject: [PATCH 153/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20Test:=20UserCo?= =?UTF-8?q?ntrollerTest=20=EC=9C=A0=ED=9A=A8=EC=84=B1=EA=B2=80=EC=82=AC=20?= =?UTF-8?q?=EB=B0=98=EC=98=81=20(#47)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/UserControllerTest.java | 80 ++++++++++++++++++- 1 file changed, 77 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java index 9eb7c22..f595f80 100644 --- a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java @@ -4,6 +4,7 @@ import com.diareat.diareat.user.controller.UserController; import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; +import com.diareat.diareat.user.dto.request.SearchUserDto; import com.diareat.diareat.user.dto.request.UpdateUserDto; import com.diareat.diareat.user.dto.request.UpdateUserNutritionDto; import com.diareat.diareat.user.dto.response.ResponseSearchUserDto; @@ -11,6 +12,7 @@ import com.diareat.diareat.user.dto.response.ResponseUserDto; import com.diareat.diareat.user.dto.response.ResponseUserNutritionDto; import com.diareat.diareat.user.service.UserService; +import com.diareat.diareat.util.MessageUtil; import com.diareat.diareat.util.api.ApiResponse; import com.diareat.diareat.util.api.ResponseCode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -20,6 +22,7 @@ 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.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; @@ -31,7 +34,7 @@ import java.util.List; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; @WebMvcTest(controllers = UserController.class) class UserControllerTest { @@ -122,6 +125,29 @@ void updateUser() throws Exception { .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); } + @DisplayName("회원정보 수정 - 유효성 검사 실패") + @Test + @WithMockUser("test") + void updateUserFail() throws Exception { + // Given + UpdateUserDto user = UpdateUserDto.of(testUserId, "", 300, 80, 500, true); + String json = mapper.writeValueAsString(user); + + // When & Then + mockMvc.perform( MockMvcRequestBuilders + .put("/api/user/update") + .contentType(MediaType.APPLICATION_JSON) + .content(json) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isBadRequest()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(HttpStatus.BAD_REQUEST.value())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(ResponseCode.BAD_REQUEST.getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(ResponseCode.BAD_REQUEST.getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.name").value(MessageUtil.NOT_BLANK)) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.height").value(MessageUtil.HEIGHT_RANGE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.age").value(MessageUtil.AGE_RANGE)); + } + @DisplayName("회원 기준섭취량 조회") @Test @WithMockUser("test") @@ -169,6 +195,29 @@ void updateUserNutrition() throws Exception { .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); } + @DisplayName("회원 기준섭취량 직접 수정 - 유효성 검사 실패") + @Test + @WithMockUser("test") + void updateUserNutritionFail() throws Exception { + // Given + UpdateUserNutritionDto nutrition = UpdateUserNutritionDto.of(testUserId, 12000, -1, 5000, -500); + String json = mapper.writeValueAsString(nutrition); + + // When & Then + mockMvc.perform( MockMvcRequestBuilders + .put("/api/user/1/nutrition") + .contentType(MediaType.APPLICATION_JSON) + .content(json) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isBadRequest()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(HttpStatus.BAD_REQUEST.value())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(ResponseCode.BAD_REQUEST.getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(ResponseCode.BAD_REQUEST.getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.calorie").value(MessageUtil.CALORIE_RANGE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.protein").value(MessageUtil.PROTEIN_RANGE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.fat").value(MessageUtil.FAT_RANGE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.carbohydrate").value(MessageUtil.CARBOHYDRATE_RANGE)); + } @DisplayName("회원의 친구 검색 결과 조회") @Test @WithMockUser("test") @@ -177,10 +226,14 @@ void searchUser() throws Exception { when(userService.searchUser(testUserId, "test")).thenReturn(List.of(ResponseSearchUserDto.of(2L, "test2", "test2", true))); ApiResponse> expectedResponse = ApiResponse.success( List.of(ResponseSearchUserDto.of(2L, "test2", "test2", true)), ResponseCode.USER_SEARCH_SUCCESS.getMessage()); + SearchUserDto searchDto = SearchUserDto.of(testUserId, "test"); + String json = mapper.writeValueAsString(searchDto); // When & Then mockMvc.perform( MockMvcRequestBuilders - .get("/api/user/1/search/test").param("name", "test") + .get("/api/user/search") + .contentType(MediaType.APPLICATION_JSON) + .content(json) .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) @@ -191,12 +244,33 @@ void searchUser() throws Exception { .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].follow").value(expectedResponse.getData().get(0).isFollow())); } + @DisplayName("회원의 친구 검색 결과 조회 - 유효성 검사 실패") + @Test + @WithMockUser("test") + void searchUserFail() throws Exception { + // Given + SearchUserDto searchDto = SearchUserDto.of(testUserId, ""); + String json = mapper.writeValueAsString(searchDto); + + // When & Then + mockMvc.perform( MockMvcRequestBuilders + .get("/api/user/search") + .contentType(MediaType.APPLICATION_JSON) + .content(json) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isBadRequest()) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(HttpStatus.BAD_REQUEST.value())) + .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(ResponseCode.BAD_REQUEST.getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(ResponseCode.BAD_REQUEST.getMessage())) + .andExpect(MockMvcResultMatchers.jsonPath("$.data.inputName").value(MessageUtil.NOT_BLANK)); + } + @DisplayName("회원이 특정 회원 팔로우 및 팔로우 취소") @Test @WithMockUser("test") void followUser() throws Exception { // Given - ApiResponse expectedResponse = ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); + ApiResponse expectedResponse = ApiResponse.success(null, ResponseCode.USER_FOLLOW_SUCCESS.getMessage()); // When & Then mockMvc.perform( MockMvcRequestBuilders From 8c325f0fc5093cae37e1bef9852f6e8ddf661990 Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 2 Nov 2023 17:46:26 +0900 Subject: [PATCH 154/371] =?UTF-8?q?:safety=5Fvest:=20Refactor:=20FoodContr?= =?UTF-8?q?oller=20@Valid=20=EC=B6=94=EA=B0=80=20(#47)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/controller/FoodController.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 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 7f60221..5e7d6cc 100644 --- a/src/main/java/com/diareat/diareat/food/controller/FoodController.java +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -9,6 +9,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; +import javax.validation.Valid; import java.time.LocalDate; import java.util.List; @@ -23,7 +24,7 @@ public class FoodController { //음식 정보 저장 @Operation(summary = "[음식] 음식 정보 저장", description = "촬영한 음식 정보를 저장합니다.") @PostMapping("/save") - public ApiResponse saveFood(CreateFoodDto createFoodDto){ + public ApiResponse saveFood(@RequestBody @Valid CreateFoodDto createFoodDto){ return ApiResponse.success(foodService.saveFood(createFoodDto),ResponseCode.FOOD_CREATE_SUCCESS.getMessage()); } @@ -42,7 +43,7 @@ public ApiResponse> getFoodListByDate(@PathVariable Long u //음식 정보 수정 @Operation(summary = "[음식] 음식 정보 수정",description = "음식에 대한 정보를 수정합니다.") @PostMapping("/update") - public ApiResponse updateFood(UpdateFoodDto updateFoodDto){ + public ApiResponse updateFood(@RequestBody @Valid UpdateFoodDto updateFoodDto){ foodService.updateFood(updateFoodDto); return ApiResponse.success(null,ResponseCode.FOOD_UPDATE_SUCCESS.getMessage()); } @@ -57,7 +58,7 @@ public ApiResponse deleteFood(@PathVariable Long foodId, @RequestHeader Lo //즐겨찾기에 음식 저장 @Operation(summary = "[즐겨찾기] 즐겨찾기에 저장",description = "유저의 즐겨찾기에 음식을 저장합니다.") @PostMapping("/favorite") - public ApiResponse saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto){ + public ApiResponse saveFavoriteFood(@RequestBody @Valid CreateFavoriteFoodDto createFavoriteFoodDto){ return ApiResponse.success(foodService.saveFavoriteFood(createFavoriteFoodDto),ResponseCode.FOOD_FAVORITE_CREATE_SUCCESS.getMessage()); } @@ -71,7 +72,7 @@ public ApiResponse> getFavoriteFoodList(@PathVaria //즐겨찾기 음식 수정 @Operation(summary = "[즐겨찾기] 즐겨찾기 수정",description = "유저의 즐겨찾기에 등록된 음식의 정보를 수정합니다.") @PostMapping("/favorite/update") - public ApiResponse updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto){ + public ApiResponse updateFavoriteFood(@RequestBody @Valid UpdateFavoriteFoodDto updateFavoriteFoodDto){ foodService.updateFavoriteFood(updateFavoriteFoodDto); return ApiResponse.success(null, ResponseCode.FOOD_FAVORITE_UPDATE_SUCCESS.getMessage()); } From 969aadfdf8c6db80cb96ff5e84a05b000fe715fd Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 3 Nov 2023 00:45:28 +0900 Subject: [PATCH 155/371] =?UTF-8?q?:construction=5Fworker:=20feat:=20k8s?= =?UTF-8?q?=20yaml=20=EC=83=9D=EC=84=B1=20(#39)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- k8s/manifest.yaml | 58 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 k8s/manifest.yaml diff --git a/k8s/manifest.yaml b/k8s/manifest.yaml new file mode 100644 index 0000000..9746636 --- /dev/null +++ b/k8s/manifest.yaml @@ -0,0 +1,58 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: diareat-deployment + namespace: diareat +spec: + replicas: 1 + selector: + matchLabels: + app: diareat + template: + metadata: + labels: + app: diareat + spec: + containers: + - name: diareat + image: synoti21/diareat-backend:latest + imagePullPolicy: IfNotPresent + envFrom: + - secretRef: + name: diareat-secret + resources: + limits: + memory: "256Mi" + cpu: 1 + ports: + - containerPort: 8719 +--- +apiVersion: v1 +kind: Service +metadata: + name: diareat-svc + namespace: diareat +spec: + selector: + app: diareat + ports: + - protocol: TCP + port: 2938 + targetPort: 8719 +--- +apiVersion: traefik.containo.us/v1alpha1 +kind: IngressRoute +metadata: + name: diareat-route + namespace: diareat +spec: + entryPoints: + - websecure + routes: + - match: Host(`diareat.${DDNS}`) + kind: Rule + services: + - name: diareat-svc + port: 2938 + tls: + certResolver: myresolver From 32d87276be175015779c25c27e90bf00175e9e6e Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 3 Nov 2023 00:47:25 +0900 Subject: [PATCH 156/371] =?UTF-8?q?:construction=5Fworker:=20feat:=20kusto?= =?UTF-8?q?mization.yaml=20=EC=83=9D=EC=84=B1=20(#39)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- k8s/kustomization.yaml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 k8s/kustomization.yaml diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml new file mode 100644 index 0000000..97c8d3c --- /dev/null +++ b/k8s/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: +- manifest.yaml +images: +- name: synoti21/diareat-backend From 706358a7c4b9a0db83d34e87ce9fb9d96444bccc Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 3 Nov 2023 00:52:02 +0900 Subject: [PATCH 157/371] =?UTF-8?q?:construction=5Fworker:=20feat:=20argoc?= =?UTF-8?q?d=EC=9A=A9=20yaml=20=EC=83=9D=EC=84=B1=20(#39)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/Diareat-CICD.yml | 74 +++++++++++++++++++----------- 1 file changed, 46 insertions(+), 28 deletions(-) diff --git a/.github/workflows/Diareat-CICD.yml b/.github/workflows/Diareat-CICD.yml index 4a11ca1..b7a92c8 100644 --- a/.github/workflows/Diareat-CICD.yml +++ b/.github/workflows/Diareat-CICD.yml @@ -3,6 +3,8 @@ name: Diareat CI/CD on: push: branches: [ "master" ] + paths-ignore: + - 'k8s/**' permissions: contents: read @@ -36,36 +38,52 @@ jobs: password: ${{ secrets.DOCKERHUB_TOKEN }} logout: true - - name: Build and push to DockerHub + - name: Get version + id: image run: | - docker build -t ${{ secrets.PROJECT_NAME }} . - docker tag ${{ secrets.PROJECT_NAME }}:latest ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest - docker push ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest - - CD: - needs: CI - runs-on: ubuntu-latest + VERSION=$(echo ${{ github.sha }} | cut -c1-8) + echo VERSION=$VERSION + echo "::set-output name=version::$VERSION" - steps: - - name: Deploy to EC2 / Check Server status - uses: appleboy/ssh-action@v1.0.0 - with: - host: ${{ secrets.EC2_HOST }} - username: ${{ secrets.EC2_USERNAME }} - key: ${{ secrets.EC2_KEY }} - - script: | - echo "${{ secrets.DOCKERHUB_TOKEN }}" | sudo docker login -u "${{ secrets.DOCKERHUB_USERNAME }}" --password-stdin - sudo docker rm $(sudo docker stop $(sudo docker ps -a -q --filter ancestor=${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest --format="{{.ID}}")) - sudo docker rmi ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest - sudo docker pull ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest + - name: Build and push to DockerHub + run: | + docker build -t synoti21/${{ secrets.PROJECT_NAME }}:${{ steps.image.outputs.version }} . + docker push synoti21/${{ secrets.PROJECT_NAME }}:${{ steps.image.outputs.version }} - echo "DB_ENDPOINT=${{ secrets.DB_ENDPOINT }}" > env.list - echo "DB_USERNAME=${{ secrets.DB_USERNAME }}" >> env.list - echo "DB_PASSWORD=${{ secrets.DB_PASSWORD }}" >> env.list - echo "JWT_KEY=${{ secrets.JWT_KEY }}" >> env.list + + update-manifest: + runs-on: ubuntu-latest + needs: CI + steps: + - name: Get version + id: image + run: | + VERSION=$(echo ${{ github.sha }} | cut -c1-8) + echo VERSION=$VERSION + echo "::set-output name=version::$VERSION" + + - name: Setup Kustomize + uses: imranismail/setup-kustomize@v2.1.0-rc + - name: Checkout kustomize repository + uses: actions/checkout@v3 + with: + repository: CAUSOLDOUTMAN/Diareat_backend + ref: master + token: ${{ secrets.ACCESS_TOKEN }} + path: Diareat_backend + - sudo docker run -d -p 8080:8080/tcp --env-file env.list --name Diareat_Backend ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest - sleep 10s - sudo docker ps | grep ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.PROJECT_NAME }}:latest \ No newline at end of file + - name: Update Kubernetes resources + run: | + cd Diareat_backend/k8s/ + kustomize edit set image synoti21/${{ secrets.PROJECT_NAME }}=synoti21/${{ secrets.PROJECT_NAME }}:${{ steps.image.outputs.version }} + kustomize build . + + - name: Commit and push the updated manifest + run: | + cd Diareat_Backend + git config --global user.name 'github-actions' + git config --global user.email 'github-actions@github.com' + git commit -am ":construction_worker: chore: Update deployment to ${{ github.sha }}" + git push From a94e464941fb9af9b060d4ccd3045482387e9798 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 3 Nov 2023 01:07:43 +0900 Subject: [PATCH 158/371] =?UTF-8?q?:recycle:=20Refactor:=20Food=20?= =?UTF-8?q?=ED=8C=A8=ED=82=A4=EC=A7=80=20RequestDto=20=EC=9C=A0=ED=9A=A8?= =?UTF-8?q?=EC=84=B1=EA=B2=80=EC=82=AC=20=EA=B5=AC=ED=98=84=20(#47)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/dto/CreateFavoriteFoodDto.java | 11 +++++++++++ .../com/diareat/diareat/food/dto/CreateFoodDto.java | 11 +++++++++++ .../diareat/food/dto/UpdateFavoriteFoodDto.java | 11 +++++++++++ .../com/diareat/diareat/food/dto/UpdateFoodDto.java | 11 +++++++++++ .../java/com/diareat/diareat/util/MessageUtil.java | 2 ++ 5 files changed, 46 insertions(+) diff --git a/src/main/java/com/diareat/diareat/food/dto/CreateFavoriteFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/CreateFavoriteFoodDto.java index fce25be..761602b 100644 --- a/src/main/java/com/diareat/diareat/food/dto/CreateFavoriteFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/CreateFavoriteFoodDto.java @@ -1,18 +1,29 @@ package com.diareat.diareat.food.dto; import com.diareat.diareat.user.domain.BaseNutrition; +import com.diareat.diareat.util.MessageUtil; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + @Getter @NoArgsConstructor @AllArgsConstructor public class CreateFavoriteFoodDto { + @NotNull(message = MessageUtil.NOT_NULL) private Long foodId; + + @NotNull(message = MessageUtil.NOT_NULL) private Long userId; + + @NotBlank(message = MessageUtil.NOT_BLANK) private String name; + + @NotNull(message = MessageUtil.NOT_NULL) private BaseNutrition baseNutrition; public static CreateFavoriteFoodDto of(Long foodId, Long userId, String name, BaseNutrition baseNutrition) { diff --git a/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java index 0f07e40..b08bf01 100644 --- a/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java @@ -1,10 +1,14 @@ package com.diareat.diareat.food.dto; import com.diareat.diareat.user.domain.BaseNutrition; +import com.diareat.diareat.util.MessageUtil; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.PastOrPresent; import java.time.LocalDate; @Getter @@ -12,9 +16,16 @@ @AllArgsConstructor public class CreateFoodDto { + @NotNull(message = MessageUtil.NOT_NULL) private Long userId; + + @NotBlank(message = MessageUtil.NOT_BLANK) private String name; + + @NotNull(message = MessageUtil.NOT_NULL) private BaseNutrition baseNutrition; + + @PastOrPresent(message = MessageUtil.PAST_OR_PRESENT) private LocalDate date; public static CreateFoodDto of(Long userId, String name, BaseNutrition baseNutrition, LocalDate date) { diff --git a/src/main/java/com/diareat/diareat/food/dto/UpdateFavoriteFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/UpdateFavoriteFoodDto.java index df7ecbf..725b69e 100644 --- a/src/main/java/com/diareat/diareat/food/dto/UpdateFavoriteFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/UpdateFavoriteFoodDto.java @@ -1,18 +1,29 @@ package com.diareat.diareat.food.dto; import com.diareat.diareat.user.domain.BaseNutrition; +import com.diareat.diareat.util.MessageUtil; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + @Getter @NoArgsConstructor @AllArgsConstructor public class UpdateFavoriteFoodDto { + @NotNull(message = MessageUtil.NOT_NULL) private Long favoriteFoodId; + + @NotNull(message = MessageUtil.NOT_NULL) private Long userId; + + @NotBlank(message = MessageUtil.NOT_BLANK) private String name; + + @NotNull(message = MessageUtil.NOT_NULL) private BaseNutrition baseNutrition; public static UpdateFavoriteFoodDto of(Long favoriteFoodId, Long userId, String name, BaseNutrition baseNutrition) { diff --git a/src/main/java/com/diareat/diareat/food/dto/UpdateFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/UpdateFoodDto.java index 55b2dac..b62fb24 100644 --- a/src/main/java/com/diareat/diareat/food/dto/UpdateFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/UpdateFoodDto.java @@ -1,18 +1,29 @@ package com.diareat.diareat.food.dto; import com.diareat.diareat.user.domain.BaseNutrition; +import com.diareat.diareat.util.MessageUtil; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + @Getter @NoArgsConstructor @AllArgsConstructor public class UpdateFoodDto { + @NotNull(message = MessageUtil.NOT_NULL) private Long foodId; + + @NotNull(message = MessageUtil.NOT_NULL) private Long userId; + + @NotBlank(message = MessageUtil.NOT_BLANK) private String name; + + @NotNull(message = MessageUtil.NOT_NULL) private BaseNutrition baseNutrition; public static UpdateFoodDto of(Long foodId, Long userId, String name, BaseNutrition baseNutrition) { diff --git a/src/main/java/com/diareat/diareat/util/MessageUtil.java b/src/main/java/com/diareat/diareat/util/MessageUtil.java index df542a7..b9aca5e 100644 --- a/src/main/java/com/diareat/diareat/util/MessageUtil.java +++ b/src/main/java/com/diareat/diareat/util/MessageUtil.java @@ -18,4 +18,6 @@ public class MessageUtil { // 반복되는 메시지의 형식을 저장하고 public static final String CARBOHYDRATE_RANGE = "탄수화물은 100 이상, 500 이하의 값을 입력해주세요."; public static final String PROTEIN_RANGE = "단백질은 25 이상, 500 이하의 값을 입력해주세요."; public static final String FAT_RANGE = "지방은 25 이상, 500 이하의 값을 입력해주세요."; + + public static final String PAST_OR_PRESENT = "과거 또는 오늘 날짜여야 합니다."; } From c60288341252d9b831d94e21dec0eb2f0c5bbb67 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 3 Nov 2023 01:12:57 +0900 Subject: [PATCH 159/371] :green_heart: fix: Update Diareat-CICD.yml --- .github/workflows/Diareat-CICD.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/Diareat-CICD.yml b/.github/workflows/Diareat-CICD.yml index b7a92c8..12a32df 100644 --- a/.github/workflows/Diareat-CICD.yml +++ b/.github/workflows/Diareat-CICD.yml @@ -64,6 +64,9 @@ jobs: - name: Setup Kustomize uses: imranismail/setup-kustomize@v2.1.0-rc + with: + github-token: ${{ secrets.ACCESS_TOKEN }} + - name: Checkout kustomize repository uses: actions/checkout@v3 From fd376030420df52f196e5e9eec5fffa1ca2b41c4 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 3 Nov 2023 01:42:45 +0900 Subject: [PATCH 160/371] Update Diareat-CICD.yml --- .github/workflows/Diareat-CICD.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/Diareat-CICD.yml b/.github/workflows/Diareat-CICD.yml index 12a32df..84671b1 100644 --- a/.github/workflows/Diareat-CICD.yml +++ b/.github/workflows/Diareat-CICD.yml @@ -64,8 +64,6 @@ jobs: - name: Setup Kustomize uses: imranismail/setup-kustomize@v2.1.0-rc - with: - github-token: ${{ secrets.ACCESS_TOKEN }} - name: Checkout kustomize repository From ea7cce2e22a411c7667a6d86396cc7f3eb8d609a Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Fri, 3 Nov 2023 01:48:31 +0900 Subject: [PATCH 161/371] =?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 e91065dab8af998f36dff6d97ca2a4e53ddc1429 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 3 Nov 2023 01:50:10 +0900 Subject: [PATCH 162/371] Update Diareat-CICD.yml --- .github/workflows/Diareat-CICD.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Diareat-CICD.yml b/.github/workflows/Diareat-CICD.yml index 84671b1..9079b98 100644 --- a/.github/workflows/Diareat-CICD.yml +++ b/.github/workflows/Diareat-CICD.yml @@ -69,7 +69,7 @@ jobs: - name: Checkout kustomize repository uses: actions/checkout@v3 with: - repository: CAUSOLDOUTMAN/Diareat_backend + repository: CAUSOLDOUTMEN/Diareat_backend ref: master token: ${{ secrets.ACCESS_TOKEN }} path: Diareat_backend From c58732416c3027cee68d0bab5692a72efbd4464c Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 3 Nov 2023 01:52:58 +0900 Subject: [PATCH 163/371] Update Diareat-CICD.yml --- .github/workflows/Diareat-CICD.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Diareat-CICD.yml b/.github/workflows/Diareat-CICD.yml index 9079b98..98049a8 100644 --- a/.github/workflows/Diareat-CICD.yml +++ b/.github/workflows/Diareat-CICD.yml @@ -83,7 +83,7 @@ jobs: - name: Commit and push the updated manifest run: | - cd Diareat_Backend + cd Diareat_backend git config --global user.name 'github-actions' git config --global user.email 'github-actions@github.com' git commit -am ":construction_worker: chore: Update deployment to ${{ github.sha }}" From c960f773fedd0e0037b79a61b951a380ab858483 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 2 Nov 2023 16:55:10 +0000 Subject: [PATCH 164/371] :construction_worker: chore: Update deployment to c58732416c3027cee68d0bab5692a72efbd4464c --- k8s/kustomization.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 97c8d3c..e366dfe 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -4,3 +4,5 @@ resources: - manifest.yaml images: - name: synoti21/diareat-backend + newName: synoti21/diareat-backend + newTag: c5873241 From 7f077b79a0b507c1e1f7dd0f94047b36697e66f2 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Fri, 3 Nov 2023 02:40:26 +0900 Subject: [PATCH 165/371] =?UTF-8?q?:construction=5Fworker:=20fix:=20?= =?UTF-8?q?=ED=8F=AC=ED=8A=B8=20=EB=B2=88=ED=98=B8=20=ED=95=AB=ED=94=BD?= =?UTF-8?q?=EC=8A=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- k8s/manifest.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/k8s/manifest.yaml b/k8s/manifest.yaml index 9746636..22b7897 100644 --- a/k8s/manifest.yaml +++ b/k8s/manifest.yaml @@ -25,7 +25,7 @@ spec: memory: "256Mi" cpu: 1 ports: - - containerPort: 8719 + - containerPort: 8080 --- apiVersion: v1 kind: Service @@ -38,7 +38,7 @@ spec: ports: - protocol: TCP port: 2938 - targetPort: 8719 + targetPort: 8080 --- apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute From 9abdedadde1568fd236b330b21c75effdaf5d532 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 3 Nov 2023 05:29:32 +0900 Subject: [PATCH 166/371] =?UTF-8?q?:construction=5Fworker:=20fix:=20Host?= =?UTF-8?q?=20=ED=95=AB=ED=94=BD=EC=8A=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- k8s/manifest.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/manifest.yaml b/k8s/manifest.yaml index 22b7897..4263152 100644 --- a/k8s/manifest.yaml +++ b/k8s/manifest.yaml @@ -49,7 +49,7 @@ spec: entryPoints: - websecure routes: - - match: Host(`diareat.${DDNS}`) + - match: Host(`diareat.thisiswandol.com`) kind: Rule services: - name: diareat-svc From f326d954dca694765cb573e107713265fb0e613a Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 3 Nov 2023 17:09:35 +0900 Subject: [PATCH 167/371] :memo: fix: Update manifest.yaml --- k8s/manifest.yaml | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/k8s/manifest.yaml b/k8s/manifest.yaml index 4263152..575f762 100644 --- a/k8s/manifest.yaml +++ b/k8s/manifest.yaml @@ -23,7 +23,7 @@ spec: resources: limits: memory: "256Mi" - cpu: 1 + cpu: 0.3 ports: - containerPort: 8080 --- @@ -56,3 +56,29 @@ spec: port: 2938 tls: certResolver: myresolver +--- +apiVersion: autoscaling/v2beta2 +kind: HorizontalPodAutoscaler +metadata: + name: diareat-hpa + namespace: diareat +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: diareat-deployment + minReplicas: 1 + maxReplicas: 3 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 50 + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 50 From 172bb19829965b554856bed814ab12c5963989d0 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 3 Nov 2023 17:29:34 +0900 Subject: [PATCH 168/371] Update manifest.yaml --- k8s/manifest.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/k8s/manifest.yaml b/k8s/manifest.yaml index 575f762..6c137ef 100644 --- a/k8s/manifest.yaml +++ b/k8s/manifest.yaml @@ -72,13 +72,13 @@ spec: metrics: - type: Resource resource: - name: cpu + name: memory target: type: Utilization averageUtilization: 50 - type: Resource resource: - name: memory + name: cpu target: type: Utilization averageUtilization: 50 From 9793b2548e6a04c2a30ee4f404195feb3a3c9b27 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 3 Nov 2023 17:37:37 +0900 Subject: [PATCH 169/371] Update manifest.yaml --- k8s/manifest.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/k8s/manifest.yaml b/k8s/manifest.yaml index 6c137ef..6bebbfc 100644 --- a/k8s/manifest.yaml +++ b/k8s/manifest.yaml @@ -22,7 +22,7 @@ spec: name: diareat-secret resources: limits: - memory: "256Mi" + memory: "512Mi" cpu: 0.3 ports: - containerPort: 8080 @@ -67,8 +67,8 @@ spec: apiVersion: apps/v1 kind: Deployment name: diareat-deployment - minReplicas: 1 - maxReplicas: 3 + minReplicas: 2 + maxReplicas: 4 metrics: - type: Resource resource: From b516fdeefbd295eb6771ce527fdd9e388d730731 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 3 Nov 2023 17:38:50 +0900 Subject: [PATCH 170/371] Update manifest.yaml From e61a6485432e4faf61c6f8e227cef7cc30bc975b Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 3 Nov 2023 17:39:58 +0900 Subject: [PATCH 171/371] Update manifest.yaml --- k8s/manifest.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/manifest.yaml b/k8s/manifest.yaml index 6bebbfc..c079fe0 100644 --- a/k8s/manifest.yaml +++ b/k8s/manifest.yaml @@ -4,7 +4,7 @@ metadata: name: diareat-deployment namespace: diareat spec: - replicas: 1 + replicas: 2 selector: matchLabels: app: diareat From c5ccc1e00b28b2aa4a13789e38524f809a5f7373 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sat, 4 Nov 2023 21:47:59 +0900 Subject: [PATCH 172/371] =?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 173/371] =?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 174/371] =?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 175/371] =?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 176/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20foodse?= =?UTF-8?q?rvicetest=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 177/371] =?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 178/371] =?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 179/371] =?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 180/371] =?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 181/371] =?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 182/371] =?UTF-8?q?:sparkles:=20feat:=20ResponseFavoriteFo?= =?UTF-8?q?odDto=EC=97=90=EC=84=9C=20=EB=88=84=EB=9D=BD=EB=90=9C=20User=20?= =?UTF-8?q?Id=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 183/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20FoodCo?= =?UTF-8?q?ntrollerTest=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 7916ed635374008004bae4d1765ddad4e3f51c93 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 6 Nov 2023 23:08:30 +0900 Subject: [PATCH 184/371] =?UTF-8?q?:ambulance:=20Fix:=20=EC=B9=B4=EC=B9=B4?= =?UTF-8?q?=EC=98=A4=EB=A1=9C=EA=B7=B8=EC=9D=B8=20=EC=9D=91=EB=8B=B5=20Dto?= =?UTF-8?q?=20=EB=AF=B8=EC=8A=A4=EB=A7=A4=EC=B9=AD=20=EC=83=81=ED=99=A9=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20(#51)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/auth/dto/KakaoAccount.java | 2 ++ .../com/diareat/diareat/auth/dto/KakaoProfile.java | 6 +++--- .../com/diareat/diareat/auth/dto/KakaoProperties.java | 11 +++++++++++ .../diareat/auth/dto/KakaoUserInfoResponse.java | 5 +++-- 4 files changed, 19 insertions(+), 5 deletions(-) create mode 100644 src/main/java/com/diareat/diareat/auth/dto/KakaoProperties.java diff --git a/src/main/java/com/diareat/diareat/auth/dto/KakaoAccount.java b/src/main/java/com/diareat/diareat/auth/dto/KakaoAccount.java index faf7a48..3f0a804 100644 --- a/src/main/java/com/diareat/diareat/auth/dto/KakaoAccount.java +++ b/src/main/java/com/diareat/diareat/auth/dto/KakaoAccount.java @@ -5,5 +5,7 @@ @Getter public class KakaoAccount { + private Boolean profile_nickname_needs_agreement; + private Boolean profile_image_needs_agreement; private KakaoProfile profile; } diff --git a/src/main/java/com/diareat/diareat/auth/dto/KakaoProfile.java b/src/main/java/com/diareat/diareat/auth/dto/KakaoProfile.java index 1c50d73..ea6e2c8 100644 --- a/src/main/java/com/diareat/diareat/auth/dto/KakaoProfile.java +++ b/src/main/java/com/diareat/diareat/auth/dto/KakaoProfile.java @@ -6,7 +6,7 @@ public class KakaoProfile { private String nickname; - private String profileImageUrl; - private String thumbnailImageUrl; - private boolean isDefaultImage; + private String thumbnail_image_url; + private String profile_image_url; + private Boolean is_default_image; } diff --git a/src/main/java/com/diareat/diareat/auth/dto/KakaoProperties.java b/src/main/java/com/diareat/diareat/auth/dto/KakaoProperties.java new file mode 100644 index 0000000..4b11027 --- /dev/null +++ b/src/main/java/com/diareat/diareat/auth/dto/KakaoProperties.java @@ -0,0 +1,11 @@ +package com.diareat.diareat.auth.dto; + +import lombok.Getter; + +@Getter +public class KakaoProperties { + + private String nickname; + private String profile_image; + private String thumbnail_image; +} diff --git a/src/main/java/com/diareat/diareat/auth/dto/KakaoUserInfoResponse.java b/src/main/java/com/diareat/diareat/auth/dto/KakaoUserInfoResponse.java index a4e4adb..039c62b 100644 --- a/src/main/java/com/diareat/diareat/auth/dto/KakaoUserInfoResponse.java +++ b/src/main/java/com/diareat/diareat/auth/dto/KakaoUserInfoResponse.java @@ -6,6 +6,7 @@ public class KakaoUserInfoResponse { private Long id; - private boolean hasSignedUp; - private KakaoAccount kakaoAccount; + private String connected_at; + private KakaoProperties properties; + private KakaoAccount kakao_account; } From 291ee2c9495e58a3dab04525f617edb0dbf14ad3 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 6 Nov 2023 23:09:32 +0900 Subject: [PATCH 185/371] =?UTF-8?q?:ambulance:=20Fix:=20KakaoAuthService?= =?UTF-8?q?=20Dto=20getter=20=ED=91=9C=ED=98=84=20=EC=88=98=EC=A0=95=20(#5?= =?UTF-8?q?1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/auth/service/KakaoAuthService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java b/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java index c5ce759..fa171d3 100644 --- a/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java +++ b/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java @@ -29,7 +29,7 @@ public Long isSignedUp(String token) { // 클라이언트가 보낸 token을 이 @Transactional(readOnly = true) public CreateUserDto createUserDto(JoinUserDto joinUserDto) { // 카카오로부터 프사 URL, 유저 고유ID를 얻어온 후, 이를 유저가 입력한 정보와 함께 CreateUserDto로 반환 KakaoUserInfoResponse userInfo = kakaoUserInfo.getUserInfo(joinUserDto.getToken()); - return CreateUserDto.of(joinUserDto.getNickName(), userInfo.getKakaoAccount().getProfile().getProfileImageUrl(), + return CreateUserDto.of(joinUserDto.getNickName(), userInfo.getKakao_account().getProfile().getProfile_image_url(), userInfo.getId().toString(), joinUserDto.getGender(), joinUserDto.getHeight(), joinUserDto.getWeight(), joinUserDto.getAge()); } } From 33aa1f42bf24ce66462197416ac2e0fd01abab54 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 6 Nov 2023 23:08:10 +0900 Subject: [PATCH 186/371] =?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 187/371] =?UTF-8?q?:fire:=20feat:=20ResponseFavoriteFoodDt?= =?UTF-8?q?o=EC=97=90=EC=84=9C=20=ED=95=84=EC=9A=94=EC=97=86=EB=8A=94=20Us?= =?UTF-8?q?erId=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 188/371] =?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); } From a5574b589d09d247771c51c48f2bd8c6f845f6ff Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 6 Nov 2023 15:10:02 +0000 Subject: [PATCH 189/371] :construction_worker: chore: Update deployment to 2e47d59e6d21ee71e0f6cc5b7ccbc64a24feb2e7 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index e366dfe..963cac1 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: c5873241 + newTag: 2e47d59e From 7aa791f6b65b451438ed77389a2f663665182441 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Tue, 7 Nov 2023 01:57:30 +0900 Subject: [PATCH 190/371] =?UTF-8?q?:construction=5Fworker:=20chore:=20Swag?= =?UTF-8?q?ger=20=ED=8E=98=EC=9D=B4=EC=A7=80=EB=A1=9C=20healthcheck=20?= =?UTF-8?q?=EC=A7=84=ED=96=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- k8s/manifest.yaml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/k8s/manifest.yaml b/k8s/manifest.yaml index c079fe0..991da41 100644 --- a/k8s/manifest.yaml +++ b/k8s/manifest.yaml @@ -26,6 +26,13 @@ spec: cpu: 0.3 ports: - containerPort: 8080 + readinessProbe: + httpGet: + path: /swagger-ui/index.html + port: 8080 + initialDelaySeconds: 30 + periodSeconds: 5 + failureThreshold: 24 --- apiVersion: v1 kind: Service From b721ea7959009ebbf7fc5ebb10875e59c75c44c6 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Tue, 7 Nov 2023 01:59:23 +0900 Subject: [PATCH 191/371] chore: Update Diareat-CICD.yml --- .github/workflows/Diareat-CICD.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Diareat-CICD.yml b/.github/workflows/Diareat-CICD.yml index 98049a8..56f467f 100644 --- a/.github/workflows/Diareat-CICD.yml +++ b/.github/workflows/Diareat-CICD.yml @@ -51,7 +51,7 @@ jobs: docker push synoti21/${{ secrets.PROJECT_NAME }}:${{ steps.image.outputs.version }} - update-manifest: + CD: runs-on: ubuntu-latest needs: CI steps: From d650e0e7a68e8ea9b31aeb7bfc4ffb473e776d2c Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 6 Nov 2023 17:01:29 +0000 Subject: [PATCH 192/371] :construction_worker: chore: Update deployment to b721ea7959009ebbf7fc5ebb10875e59c75c44c6 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 963cac1..e70e92e 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 2e47d59e + newTag: b721ea79 From bed6e1a15bd68cbd2735d881e241e4c4017c4604 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Tue, 7 Nov 2023 02:13:59 +0900 Subject: [PATCH 193/371] =?UTF-8?q?:construction=5Fworker:=20chore:=20revi?= =?UTF-8?q?sion=20=EA=B8=B0=EB=A1=9D=20=EC=A0=9C=ED=95=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- k8s/manifest.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/k8s/manifest.yaml b/k8s/manifest.yaml index 991da41..090d421 100644 --- a/k8s/manifest.yaml +++ b/k8s/manifest.yaml @@ -4,6 +4,7 @@ metadata: name: diareat-deployment namespace: diareat spec: + revisionHistoryLimit: 3 replicas: 2 selector: matchLabels: From 7d5f567833d4f9eb1360fa30e1f478498b07df9d Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 7 Nov 2023 15:25:38 +0900 Subject: [PATCH 194/371] =?UTF-8?q?:recycle:=20Refactor:=20=EC=B9=B4?= =?UTF-8?q?=EC=B9=B4=EC=98=A4=EB=A1=9C=EA=B7=B8=EC=9D=B8=20ResponseJwtDto?= =?UTF-8?q?=20=EB=8F=84=EC=9E=85=20(#58)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/controller/AuthController.java | 20 +++++++++---------- .../diareat/auth/dto/ResponseJwtDto.java | 16 +++++++++++++++ 2 files changed, 25 insertions(+), 11 deletions(-) create mode 100644 src/main/java/com/diareat/diareat/auth/dto/ResponseJwtDto.java diff --git a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java index 05032eb..d16bf9a 100644 --- a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java +++ b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java @@ -1,6 +1,7 @@ package com.diareat.diareat.auth.controller; import com.diareat.diareat.auth.component.JwtTokenProvider; +import com.diareat.diareat.auth.dto.ResponseJwtDto; import com.diareat.diareat.auth.service.KakaoAuthService; import com.diareat.diareat.user.dto.request.JoinUserDto; import com.diareat.diareat.user.service.UserService; @@ -12,7 +13,6 @@ import org.springframework.web.bind.annotation.*; import javax.validation.Valid; -import java.util.HashMap; @Api(tags = "2. Auth") @RequiredArgsConstructor @@ -25,23 +25,21 @@ public class AuthController { private final JwtTokenProvider jwtTokenProvider; // 카카오 로그인을 위해 회원가입 여부 확인, 이미 회원이면 Jwt 토큰 발급 - @Operation(summary = "[로그인] 카카오로그인 및 토큰 발급", description = "카카오 로그인을 위해 회원가입 여부를 확인하고, 이미 회원이면 Jwt 토큰을 발급합니다.") + @Operation(summary = "[로그인] 카카오로그인 및 토큰 발급", description = "카카오 로그인을 위해 회원가입 여부를 확인하고, 이미 회원이면 id와 Jwt 토큰을 발급합니다.") @PostMapping("/login") - public ApiResponse> authCheck(@RequestHeader String accessToken) { + public ApiResponse authCheck(@RequestHeader String accessToken) { Long userId = kakaoAuthService.isSignedUp(accessToken); // 유저 고유번호 추출 - HashMap map = new HashMap<>(); - map.put(userId, jwtTokenProvider.createToken(userId.toString())); - return ApiResponse.success(map, ResponseCode.USER_LOGIN_SUCCESS.getMessage()); + String jwt = jwtTokenProvider.createToken(userId.toString()); + return ApiResponse.success(ResponseJwtDto.of(userId, jwt), ResponseCode.USER_LOGIN_SUCCESS.getMessage()); } // 회원가입 (성공 시 Jwt 토큰 발급) - @Operation(summary = "[회원가입] 회원가입 및 토큰 발급", description = "신규 회원가입을 처리하고, 회원가입 성공 시 Jwt 토큰을 발급합니다.") + @Operation(summary = "[회원가입] 회원가입 및 토큰 발급", description = "신규 회원가입을 처리하고, 회원가입 성공 시 id와 Jwt 토큰을 발급합니다.") @PostMapping("/join") - public ApiResponse> saveUser(@Valid @RequestBody JoinUserDto joinUserDto) { + public ApiResponse saveUser(@Valid @RequestBody JoinUserDto joinUserDto) { Long userId = userService.saveUser(kakaoAuthService.createUserDto(joinUserDto)); - HashMap map = new HashMap<>(); - map.put(userId, jwtTokenProvider.createToken(userId.toString())); - return ApiResponse.success(map, ResponseCode.USER_CREATE_SUCCESS.getMessage()); + String jwt = jwtTokenProvider.createToken(userId.toString()); + return ApiResponse.success(ResponseJwtDto.of(userId, jwt), ResponseCode.USER_CREATE_SUCCESS.getMessage()); } // 토큰 검증 (Jwt 토큰을 서버에 전송하여, 서버가 유효한 토큰인지 확인하고 True 혹은 예외 반환) diff --git a/src/main/java/com/diareat/diareat/auth/dto/ResponseJwtDto.java b/src/main/java/com/diareat/diareat/auth/dto/ResponseJwtDto.java new file mode 100644 index 0000000..b26e30e --- /dev/null +++ b/src/main/java/com/diareat/diareat/auth/dto/ResponseJwtDto.java @@ -0,0 +1,16 @@ +package com.diareat.diareat.auth.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class ResponseJwtDto { + + private Long id; + private String jwt; + + public static ResponseJwtDto of(Long id, String jwt) { + return new ResponseJwtDto(id, jwt); + } +} From bb76beda1e3a12982cbda966bdc3304af5253c0b Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 7 Nov 2023 15:26:03 +0900 Subject: [PATCH 195/371] =?UTF-8?q?:recycle:=20Refactor:=20Jwt=ED=86=A0?= =?UTF-8?q?=ED=81=B0=20=EC=9C=A0=ED=9A=A8=EC=84=B1=EC=97=90=20=EB=8C=80?= =?UTF-8?q?=ED=95=9C=20Exception=20=EC=B6=94=EA=B0=80=20(#58)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/auth/component/JwtTokenProvider.java | 4 +++- src/main/java/com/diareat/diareat/util/api/ResponseCode.java | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java index eed48e3..fbb9244 100644 --- a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java +++ b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java @@ -1,5 +1,7 @@ package com.diareat.diareat.auth.component; +import com.diareat.diareat.util.api.ResponseCode; +import com.diareat.diareat.util.exception.UserException; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; @@ -61,7 +63,7 @@ public boolean validateToken(String jwtToken) { Jws claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken); return !claims.getBody().getExpiration().before(new Date()); } catch (Exception e) { - return false; + throw new UserException(ResponseCode.TOKEN_VALIDATION_FAILURE); } } 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 e9d88c2..ae34056 100644 --- a/src/main/java/com/diareat/diareat/util/api/ResponseCode.java +++ b/src/main/java/com/diareat/diareat/util/api/ResponseCode.java @@ -12,6 +12,9 @@ public enum ResponseCode { // 400 Bad Request BAD_REQUEST(HttpStatus.BAD_REQUEST, false, "잘못된 요청입니다."), + // 401 Unauthorized + TOKEN_VALIDATION_FAILURE(HttpStatus.UNAUTHORIZED, false, "토큰 검증 실패"), + // 403 Forbidden FORBIDDEN(HttpStatus.FORBIDDEN, false, "권한이 없습니다."), NOT_FOOD_OWNER(HttpStatus.FORBIDDEN, false, "음식의 주인 유저가 아닙니다."), From e3c61a5f3ccd03f5c15a760c00f11160cb83e18b Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 7 Nov 2023 15:27:08 +0900 Subject: [PATCH 196/371] =?UTF-8?q?:recycle:=20Refactor:=20=ED=94=84?= =?UTF-8?q?=EB=A1=9C=ED=95=84=EC=82=AC=EC=A7=84=20Nullable=20=EC=86=8D?= =?UTF-8?q?=EC=84=B1=20=EB=B6=80=EC=97=AC=20(#58)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/user/domain/User.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index 5af69ea..f0d7c9c 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -8,6 +8,7 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.authority.SimpleGrantedAuthority; +import reactor.util.annotation.Nullable; import javax.persistence.*; import java.util.ArrayList; @@ -30,6 +31,7 @@ public class User implements UserDetails { @Column(length = 100, nullable = false, unique = true) private String keyCode; // 로그인 식별키 + @Nullable private String image; // 프로필 사진 경로 private int height; // 키 From ce57fba7e8d13073ab08a76b28a732faeef37a17 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 7 Nov 2023 15:44:14 +0900 Subject: [PATCH 197/371] =?UTF-8?q?:recycle:=20Chore:=20FoodControllerTest?= =?UTF-8?q?=20=EC=9D=BC=EB=B6=80=20=EC=A3=BC=EC=84=9D=20=EC=B2=98=EB=A6=AC?= =?UTF-8?q?=20(#58)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/controller/FoodControllerTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index 100dc7f..c902b01 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -101,7 +101,7 @@ void testGetFoodListByDate() throws Exception { 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());; + ApiResponse> expectedResponse = ApiResponse.success(List.of(food1), ResponseCode.FOOD_READ_SUCCESS.getMessage()); //When & Then mockMvc.perform(MockMvcRequestBuilders @@ -115,7 +115,7 @@ void testGetFoodListByDate() throws Exception { .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].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())) From 4c2e82f6adf33441f30ff90ed3f6f4c54d1fee27 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 7 Nov 2023 15:48:07 +0900 Subject: [PATCH 198/371] =?UTF-8?q?:recycle:=20Refactor:=20=EC=9C=A0?= =?UTF-8?q?=EC=A0=80=20=EC=97=86=EC=9D=84=20=EC=8B=9C=20Exception=EC=9D=B4?= =?UTF-8?q?=20=EC=95=84=EB=8B=8C=20id=20null=EC=9D=84=20=EB=B0=98=ED=99=98?= =?UTF-8?q?=ED=95=98=EB=8F=84=EB=A1=9D=20=EC=88=98=EC=A0=95=20(#58)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/auth/controller/AuthController.java | 2 +- .../diareat/diareat/auth/service/KakaoAuthService.java | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java index d16bf9a..78a5e8c 100644 --- a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java +++ b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java @@ -29,7 +29,7 @@ public class AuthController { @PostMapping("/login") public ApiResponse authCheck(@RequestHeader String accessToken) { Long userId = kakaoAuthService.isSignedUp(accessToken); // 유저 고유번호 추출 - String jwt = jwtTokenProvider.createToken(userId.toString()); + String jwt = (userId == null) ? null : jwtTokenProvider.createToken(userId.toString()); // 고유번호가 null이 아니라면 Jwt 토큰 발급 return ApiResponse.success(ResponseJwtDto.of(userId, jwt), ResponseCode.USER_LOGIN_SUCCESS.getMessage()); } diff --git a/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java b/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java index fa171d3..c1a9bb2 100644 --- a/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java +++ b/src/main/java/com/diareat/diareat/auth/service/KakaoAuthService.java @@ -6,12 +6,12 @@ import com.diareat.diareat.user.dto.request.CreateUserDto; import com.diareat.diareat.user.dto.request.JoinUserDto; import com.diareat.diareat.user.repository.UserRepository; -import com.diareat.diareat.util.api.ResponseCode; -import com.diareat.diareat.util.exception.UserException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.Optional; + @RequiredArgsConstructor @Service public class KakaoAuthService { @@ -20,10 +20,10 @@ public class KakaoAuthService { private final UserRepository userRepository; @Transactional(readOnly = true) - public Long isSignedUp(String token) { // 클라이언트가 보낸 token을 이용해 카카오 API에 유저 정보를 요청, 유저가 존재하지 않으면 예외 발생, 존재하면 회원번호 반환 + public Long isSignedUp(String token) { // 클라이언트가 보낸 token을 이용해 카카오 API에 유저 정보를 요청, 유저가 존재하지 않으면 null, 존재하면 회원번호 반환 KakaoUserInfoResponse userInfo = kakaoUserInfo.getUserInfo(token); - User user = userRepository.findByKeyCode(userInfo.getId().toString()).orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND)); - return user.getId(); + Optional userOptional = userRepository.findByKeyCode(userInfo.getId().toString()); + return userOptional.map(User::getId).orElse(null); } @Transactional(readOnly = true) From 57a624392316a875da6014c8447cb16ed84fd369 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 7 Nov 2023 15:51:35 +0900 Subject: [PATCH 199/371] =?UTF-8?q?:recycle:=20Refactor:=20=ED=86=A0?= =?UTF-8?q?=ED=81=B0=20=EC=9C=A0=ED=9A=A8=EC=84=B1=20=EA=B2=80=EC=82=AC=20?= =?UTF-8?q?=EC=8B=A4=ED=8C=A8=20=EC=8B=9C=20=EB=8B=A8=EC=88=9C=20false?= =?UTF-8?q?=EB=A7=8C=20=EB=B0=98=ED=99=98=ED=95=98=EB=8F=84=EB=A1=9D=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20(#58)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/auth/component/JwtTokenProvider.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java index fbb9244..eed48e3 100644 --- a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java +++ b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java @@ -1,7 +1,5 @@ package com.diareat.diareat.auth.component; -import com.diareat.diareat.util.api.ResponseCode; -import com.diareat.diareat.util.exception.UserException; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; @@ -63,7 +61,7 @@ public boolean validateToken(String jwtToken) { Jws claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken); return !claims.getBody().getExpiration().before(new Date()); } catch (Exception e) { - throw new UserException(ResponseCode.TOKEN_VALIDATION_FAILURE); + return false; } } From 4dffff344f1745ec6268c046f7275ac436427c2f Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 7 Nov 2023 18:26:28 +0900 Subject: [PATCH 200/371] =?UTF-8?q?:ambulance:=20Fix:=20API=20=ED=85=8C?= =?UTF-8?q?=EC=8A=A4=ED=8A=B8=20=EC=9B=90=ED=99=9C=ED=95=A8=EC=9D=84=20?= =?UTF-8?q?=EC=9C=84=ED=95=B4=20=EC=9D=BC=EC=8B=9C=EC=A0=81=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=AA=A8=EB=93=A0=20API=20=EC=A0=91=EA=B7=BC=20?= =?UTF-8?q?=ED=97=88=EC=9A=A9=20(#58)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/config/WebSecurityConfig.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java b/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java index 0bd9f3a..0ef5736 100644 --- a/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java +++ b/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java @@ -28,7 +28,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .and() .authorizeRequests() .antMatchers(AUTH_LIST).permitAll() // swagger 관련 URL은 인증 없이 접근 가능 (테스트용) - .antMatchers("/api/auth/**").permitAll() // 회원가입/로그인 관련 URL은 인증 없이 접근 가능 + .antMatchers("/api/**").permitAll() // 회원가입/로그인 관련 URL은 인증 없이 접근 가능 .anyRequest().authenticated() // 나머지 모든 URL은 Jwt 인증 필요 .and() .addFilterBefore(new JwtAuthFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); From 649a54c7445c92b435103f23063f07b06e579b32 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 7 Nov 2023 12:52:40 +0000 Subject: [PATCH 201/371] :construction_worker: chore: Update deployment to a820efaca3f80243e7091870c8a627e5eddc7f8c --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index e70e92e..981b026 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: b721ea79 + newTag: a820efac From c91a64518052cc66b299d88aaa501ff2e917d161 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 8 Nov 2023 23:36:10 +0900 Subject: [PATCH 202/371] =?UTF-8?q?:bug:=20fix:=20=EB=88=84=EB=9D=BD?= =?UTF-8?q?=EB=90=9C=20=EA=B8=B0=EC=A4=80=20=EC=98=81=EC=96=91=EC=84=AD?= =?UTF-8?q?=EC=B7=A8=EB=9F=89=20=EC=B6=94=EA=B0=80=20(#60)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../food/dto/ResponseNutritionSumByDateDto.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java index 1520eb4..ea6be33 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java @@ -1,5 +1,6 @@ package com.diareat.diareat.food.dto; +import com.diareat.diareat.user.domain.BaseNutrition; import lombok.AllArgsConstructor; import lombok.Getter; @@ -23,7 +24,14 @@ public class ResponseNutritionSumByDateDto { double ratioProtein; double ratioFat; - public static ResponseNutritionSumByDateDto of (Long userId, LocalDate checkDate, int nutritionSumType, int totalKcal, int totalCarbohydrate, int totalProtein, int totalFat, double ratioKcal, double ratioCarbohydrate, double ratioProtein, double ratioFat){ - return new ResponseNutritionSumByDateDto(userId, checkDate, nutritionSumType, totalKcal, totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); + BaseNutrition baseNutrition; + + public static ResponseNutritionSumByDateDto of (Long userId, LocalDate checkDate, int nutritionSumType, int totalKcal, + int totalCarbohydrate, int totalProtein, int totalFat, double ratioKcal, + double ratioCarbohydrate, double ratioProtein, double ratioFat, + BaseNutrition baseNutrition){ + return new ResponseNutritionSumByDateDto(userId, checkDate, nutritionSumType, totalKcal, + totalCarbohydrate, totalProtein, totalFat, ratioKcal, + ratioCarbohydrate, ratioProtein, ratioFat, baseNutrition); } } From 38bd92fb1ed124fbd2c35f6972ccb2384c0daec2 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 8 Nov 2023 23:36:43 +0900 Subject: [PATCH 203/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20?= =?UTF-8?q?=EA=B8=B0=EC=A4=80=20=EC=98=81=EC=96=91=EC=84=AD=EC=B7=A8?= =?UTF-8?q?=EB=9F=89=20=EC=B6=94=EA=B0=80=EB=A1=9C=20=EC=9D=B8=ED=95=9C=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=20=EB=B0=8F=20=EA=B2=80=EC=A6=9D=20=EC=99=84=EB=A3=8C?= =?UTF-8?q?=20(#60)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/service/FoodService.java | 4 +++- .../diareat/controller/FoodControllerTest.java | 12 +++++++++--- 2 files changed, 12 insertions(+), 4 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 824baed..9e9a315 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -368,7 +368,9 @@ private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, double ratioProtein = Math.round((((double) totalProtein / (double) targetUser.getBaseNutrition().getProtein()) * 100.0) * 10.0) / 10.0; double ratioFat = Math.round((((double) totalFat / (double) targetUser.getBaseNutrition().getFat()) * 100.0) * 10.0) / 10.0; - return ResponseNutritionSumByDateDto.of(userId, checkDate, nutritionSumType, totalKcal, totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat); + return ResponseNutritionSumByDateDto.of(userId, checkDate, nutritionSumType, totalKcal, + totalCarbohydrate, totalProtein, totalFat, ratioKcal, + ratioCarbohydrate, ratioProtein, ratioFat, targetUser.getBaseNutrition()); } private void validateUser(Long userId) { diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index c902b01..413d53f 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -254,7 +254,8 @@ 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); + ,500,100,50,50,0.2,0.3,0.4,0.5, + BaseNutrition.createNutrition(500,100,50,50)); ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto,ResponseCode.FOOD_READ_SUCCESS.getMessage()); when(foodService.getNutritionSumByDate(any(Long.class),any(LocalDate.class))).thenReturn(responseNutritionSumByDateDto); @@ -279,6 +280,7 @@ void testGetNutritionSumByDate() throws Exception{ .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("$.data.baseNutrition.carbohydrate").value(expectedResponse.getData().getBaseNutrition().getCarbohydrate())) .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); } @@ -290,7 +292,8 @@ 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); + , 500, 100, 50, 50, 0.2, 0.3, 0.4, 0.5, + BaseNutrition.createNutrition(500, 100, 50, 50)); ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); when(foodService.getNutritionSumByWeek(any(Long.class))).thenReturn(responseNutritionSumByDateDto); @@ -312,6 +315,7 @@ void testGetNutritionSumByWeek() throws Exception { .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("$.data.baseNutrition.carbohydrate").value(expectedResponse.getData().getBaseNutrition().getCarbohydrate())) .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); } @@ -323,7 +327,8 @@ 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); + , 500, 100, 50, 50, 0.2, 0.3, 0.4, 0.5, + BaseNutrition.createNutrition(500, 100, 50, 50)); ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); when(foodService.getNutritionSumByMonth(any(Long.class))).thenReturn(responseNutritionSumByDateDto); @@ -345,6 +350,7 @@ void testGetNutritionSumByMonth() throws Exception { .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("$.data.baseNutrition.carbohydrate").value(expectedResponse.getData().getBaseNutrition().getCarbohydrate())) .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(expectedResponse.getMsg())); } From d8c27fababbcf312bdd051cb8c733189dfcbfe7c Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 8 Nov 2023 23:37:21 +0900 Subject: [PATCH 204/371] =?UTF-8?q?:construction=5Fworker:=20chore:=20?= =?UTF-8?q?=EC=A7=80=EB=82=98=EC=B9=98=EA=B2=8C=20=EB=8A=90=EB=A6=B0=20?= =?UTF-8?q?=EC=86=8D=EB=8F=84=EB=A1=9C=20=EC=9D=B8=ED=95=B4=20CPU=20?= =?UTF-8?q?=EB=A6=AC=EC=86=8C=EC=8A=A4=20=ED=95=A0=EB=8B=B9=EB=9F=89=20?= =?UTF-8?q?=EC=A6=9D=EA=B0=80=20(#60)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- k8s/manifest.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/k8s/manifest.yaml b/k8s/manifest.yaml index 090d421..56a083c 100644 --- a/k8s/manifest.yaml +++ b/k8s/manifest.yaml @@ -24,14 +24,14 @@ spec: resources: limits: memory: "512Mi" - cpu: 0.3 + cpu: 0.5 ports: - containerPort: 8080 readinessProbe: httpGet: path: /swagger-ui/index.html port: 8080 - initialDelaySeconds: 30 + initialDelaySeconds: 40 periodSeconds: 5 failureThreshold: 24 --- From 37b3df67ef67873a2f05c267d47ecd622572d6f8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 8 Nov 2023 14:51:20 +0000 Subject: [PATCH 205/371] :construction_worker: chore: Update deployment to 737e304bc1eb704f47a14cb937562bb904680b30 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 981b026..55d9b59 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: a820efac + newTag: 737e304b From 0d2561ffa7212f3673dae4c36a6737b9e46a3fdf Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Fri, 10 Nov 2023 11:57:29 +0900 Subject: [PATCH 206/371] =?UTF-8?q?:ambulance:=20hotfix:=20date=EB=A5=BC?= =?UTF-8?q?=20string=20type=EC=9C=BC=EB=A1=9C=20=EB=B3=80=EA=B2=BD=20(#62)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/food/service/FoodService.java | 2 +- 1 file changed, 1 insertion(+), 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 9e9a315..04fa086 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -47,7 +47,7 @@ public Long saveFood(CreateFoodDto createFoodDto) { } // 회원이 특정 날짜에 먹은 음식 조회 - @Cacheable(value = "ResponseFoodDto", key = "#userId+#date", cacheManager = "diareatCacheManager") + @Cacheable(value = "ResponseFoodDto", key = "#userId+#date.toString()", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) public List getFoodListByDate(Long userId, LocalDate date){ validateUser(userId); From a32f69411d65b2d079254bdb18c61cb0002d282f Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Fri, 10 Nov 2023 11:57:59 +0900 Subject: [PATCH 207/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20yy,mm,?= =?UTF-8?q?dd=20=ED=8C=8C=EB=9D=BC=EB=AF=B8=ED=84=B0=EC=97=90=EC=84=9C=20L?= =?UTF-8?q?ocalDate=EC=9C=BC=EB=A1=9C=20=ED=98=95=EB=B3=80=ED=99=98=20?= =?UTF-8?q?=EB=90=98=EB=8F=84=EB=A1=9D=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20(#62)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/controller/FoodControllerTest.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index 413d53f..57cbba7 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -96,7 +96,10 @@ void testSaveFood() throws Exception { @WithMockUser("test") void testGetFoodListByDate() throws Exception { //Given - LocalDate date = LocalDate.now(); + int yy = 2023; + int dd = 22; + int mm = 12; + LocalDate date = LocalDate.of(yy, mm, dd); ResponseFoodDto food1 = ResponseFoodDto.of(testFoodId, testUserId,"test", LocalDate.now(), LocalTime.now(),testBaseNutrition,false); From 5594dc2e85e89c28a993af35751ecd411e21a93a Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 10 Nov 2023 03:05:07 +0000 Subject: [PATCH 208/371] :construction_worker: chore: Update deployment to 422cf50017748997149ae2129d698ca98d8584f8 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 55d9b59..5b0c977 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 737e304b + newTag: 422cf500 From 270b53e10ff276e6f8cf6a0196249be9959dbad5 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 10 Nov 2023 12:16:22 +0900 Subject: [PATCH 209/371] :memo: docs: Create LICENSE --- LICENSE | 201 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0b0f16b --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 CAUSOLDOUTMEN + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. From 40a50c72124e1682a8a8a3e9ee68f8b37b820db6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 10 Nov 2023 03:18:44 +0000 Subject: [PATCH 210/371] :construction_worker: chore: Update deployment to 270b53e10ff276e6f8cf6a0196249be9959dbad5 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 5b0c977..91a618c 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 422cf500 + newTag: 270b53e1 From 958b24645f7899fff641e9c9ce633ae6c362b889 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Fri, 10 Nov 2023 12:31:13 +0900 Subject: [PATCH 211/371] =?UTF-8?q?:ambulance:=20hotfix:=20cache=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20(#64)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/food/service/FoodService.java | 2 +- 1 file changed, 1 insertion(+), 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 04fa086..cd6e080 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -112,7 +112,7 @@ public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { favoriteFoodRepository.deleteById(favoriteFoodId); } - @Cacheable(value = "ResponseNutritionSumByDateDto", key = "#userId+#date", cacheManager = "diareatCacheManager") + @Cacheable(value = "ResponseNutritionSumByDateDto", key = "#userId+#date.toString()", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { From 8fe48ad110f3ccb8430246ad93136388f8eddc0a Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 10 Nov 2023 03:33:54 +0000 Subject: [PATCH 212/371] :construction_worker: chore: Update deployment to 9a3040a6681c50ec4fdd0569f6445abd4179c994 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 91a618c..221135c 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 270b53e1 + newTag: 9a3040a6 From 20103b6252dbdeeeb54b1428a4d9cc6b0c666452 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 10 Nov 2023 14:09:15 +0900 Subject: [PATCH 213/371] =?UTF-8?q?:ambulance:=20Fix:=20=EC=98=A4=EB=8A=98?= =?UTF-8?q?=EC=9D=98=EC=98=81=EC=96=91=20=EC=9D=91=EB=8B=B5=EB=8D=B0?= =?UTF-8?q?=EC=9D=B4=ED=84=B0=20LocalDate=20=EC=A3=BC=EC=84=9D=EC=B2=98?= =?UTF-8?q?=EB=A6=AC=20(#66)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/dto/ResponseNutritionSumByDateDto.java | 9 ++++++--- .../com/diareat/diareat/food/service/FoodService.java | 2 +- .../diareat/diareat/controller/FoodControllerTest.java | 6 +++--- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java index ea6be33..09a99cd 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java @@ -3,15 +3,18 @@ import com.diareat.diareat.user.domain.BaseNutrition; import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; +import java.io.Serializable; import java.time.LocalDate; @Getter +@NoArgsConstructor @AllArgsConstructor -public class ResponseNutritionSumByDateDto { +public class ResponseNutritionSumByDateDto implements Serializable { Long userId; - LocalDate checkDate; //조회한 날짜 + // LocalDate checkDate; //조회한 날짜 int nutritionSumType; //조회할 기간을 나타내는 코드. {1: 특정 날짜, 7: 최근 7일간, 30: 최근 한달간} int totalKcal; @@ -30,7 +33,7 @@ public static ResponseNutritionSumByDateDto of (Long userId, LocalDate checkDate int totalCarbohydrate, int totalProtein, int totalFat, double ratioKcal, double ratioCarbohydrate, double ratioProtein, double ratioFat, BaseNutrition baseNutrition){ - return new ResponseNutritionSumByDateDto(userId, checkDate, nutritionSumType, totalKcal, + return new ResponseNutritionSumByDateDto(userId, nutritionSumType, totalKcal, totalCarbohydrate, totalProtein, totalFat, ratioKcal, ratioCarbohydrate, ratioProtein, ratioFat, baseNutrition); } 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 cd6e080..5b09f16 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -112,7 +112,7 @@ public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { favoriteFoodRepository.deleteById(favoriteFoodId); } - @Cacheable(value = "ResponseNutritionSumByDateDto", key = "#userId+#date.toString()", cacheManager = "diareatCacheManager") + @Cacheable(value = "ResponseNutritionSumByDateDto", key = "#userId + #date.toString()", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index 57cbba7..4dc0a76 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -273,7 +273,7 @@ void testGetNutritionSumByDate() throws Exception{ .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.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())) @@ -308,7 +308,7 @@ void testGetNutritionSumByWeek() throws Exception { .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.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())) @@ -343,7 +343,7 @@ void testGetNutritionSumByMonth() throws Exception { .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.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())) From fae066b7946a87843d38aa485aa28d8bb5c1f990 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 10 Nov 2023 05:13:24 +0000 Subject: [PATCH 214/371] :construction_worker: chore: Update deployment to aeb1e83de6e310a9f6b58eb625449d47ad33546b --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 221135c..9256c43 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 9a3040a6 + newTag: aeb1e83d From c352d8d6dc5db434efef339864d0ff433e895ae3 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 10 Nov 2023 15:08:43 +0900 Subject: [PATCH 215/371] =?UTF-8?q?:ambulance:=20Fix:=20Redis=20=ED=8F=AC?= =?UTF-8?q?=ED=8A=B8=EB=B2=88=ED=98=B8=20=EB=AF=B8=EC=A0=95=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=20=EC=88=98=EC=A0=95=20(#66)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/config/RedisCacheConfig.java | 9 +++++++++ src/main/resources/application.properties | 2 ++ 2 files changed, 11 insertions(+) diff --git a/src/main/java/com/diareat/diareat/config/RedisCacheConfig.java b/src/main/java/com/diareat/diareat/config/RedisCacheConfig.java index 9d828ec..b54f050 100644 --- a/src/main/java/com/diareat/diareat/config/RedisCacheConfig.java +++ b/src/main/java/com/diareat/diareat/config/RedisCacheConfig.java @@ -1,6 +1,8 @@ package com.diareat.diareat.config; +import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; @@ -12,9 +14,16 @@ import java.time.Duration; +@EnableCaching @Configuration public class RedisCacheConfig { // Redis Cache 설정 + @Value("${spring.redis.host}") + private String host; + + @Value("${spring.redis.port}") + private int port; + @Bean public CacheManager diareatCacheManager(RedisConnectionFactory cf) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 98fd09d..de6bc9e 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -8,3 +8,5 @@ spring.mvc.pathmatch.matching-strategy=ant_path_matcher spring.redis.serializer=org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer spring.cache.type=redis spring.cache.redis.cache-null-values=true +spring.redis.host=${REDIS_ENDPOINT} +spring.redis.port=6379 From 81f9a8966df7d050ed54326764d0df7555d7eb75 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 10 Nov 2023 06:18:22 +0000 Subject: [PATCH 216/371] :construction_worker: chore: Update deployment to 12bd425321f01edbaa3b4c1340ef7a17bfd2e992 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 9256c43..92e6f5c 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: aeb1e83d + newTag: 12bd4253 From 9dd02f5e55ea71e6e20ce7f934b41de03d0ca270 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Fri, 10 Nov 2023 16:53:32 +0900 Subject: [PATCH 217/371] =?UTF-8?q?:bulb:=20chore:=20=EC=9A=B4=EC=9A=A9=20?= =?UTF-8?q?=EB=8B=A8=EA=B3=84=EC=97=90=EC=84=9C=20create->none=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=B3=80=EA=B2=BD=20(#69)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/application-db.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/application-db.properties b/src/main/resources/application-db.properties index 4843c34..c46d63d 100644 --- a/src/main/resources/application-db.properties +++ b/src/main/resources/application-db.properties @@ -1,5 +1,5 @@ spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver -spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.ddl-auto=none # Remote DB spring.datasource.url=${DB_ENDPOINT} From a5d54cbb2ba7a8c0256f2cdb93ff2f2fe004ece2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 10 Nov 2023 08:00:38 +0000 Subject: [PATCH 218/371] :construction_worker: chore: Update deployment to 9dd02f5e55ea71e6e20ce7f934b41de03d0ca270 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 92e6f5c..60fb5d2 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 12bd4253 + newTag: 9dd02f5e From 7e1643195fd549f4c87741fa5647fb0afb032bd7 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 10 Nov 2023 22:09:22 +0900 Subject: [PATCH 219/371] =?UTF-8?q?:ambulance:=20Fix:=20ResponseFoodDto=20?= =?UTF-8?q?Date/Time=20=ED=83=80=EC=9E=85=20=EC=A3=BC=EC=84=9D=EC=B2=98?= =?UTF-8?q?=EB=A6=AC=20(#66)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/food/dto/ResponseFoodDto.java | 8 ++++---- .../diareat/diareat/controller/FoodControllerTest.java | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java index 1430c32..46d2055 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java @@ -15,16 +15,16 @@ public class ResponseFoodDto { private Long foodId; private Long userId; private String name; - private LocalDate date; - private LocalTime time; + //private LocalDate date; + //private LocalTime time; private BaseNutrition baseNutrition; private boolean isFavorite; public static ResponseFoodDto of(Long foodId, Long userId, String name, LocalDate date, LocalTime time, BaseNutrition baseNutrition, boolean isFavorite) { - return new ResponseFoodDto(foodId, userId, name, date, time, baseNutrition, isFavorite); + return new ResponseFoodDto(foodId, userId, name, baseNutrition, isFavorite); } public static ResponseFoodDto from(Food food) { - return new ResponseFoodDto(food.getId(), food.getUser().getId(), food.getName(), food.getDate(), food.getTime(), food.getBaseNutrition(), food.isFavorite()); + return new ResponseFoodDto(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite()); } } diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index 4dc0a76..0d3c743 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -117,7 +117,7 @@ void testGetFoodListByDate() throws Exception { .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].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())) From 882272638b20c0857e36d146864c1df4e4835d38 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 10 Nov 2023 13:17:19 +0000 Subject: [PATCH 220/371] :construction_worker: chore: Update deployment to 92b7a1859203da8cb562edc6c99bab990b870831 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 60fb5d2..bbf3fab 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 9dd02f5e + newTag: 92b7a185 From 49903ce0559044f86de72aa6fa8153f6c0ef077a Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 01:43:24 +0900 Subject: [PATCH 221/371] =?UTF-8?q?:recycle:=20refactor:=20LocalDate=20?= =?UTF-8?q?=EA=B0=9D=EC=B2=B4=20=EB=8C=80=EC=8B=A0=20year,=20month,=20day?= =?UTF-8?q?=EB=A1=9C=20LocalDate=20=EA=B0=9D=EC=B2=B4=20=EA=B5=AC=ED=98=84?= =?UTF-8?q?=20(#72)?= 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 | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) 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 639ef69..e230619 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -8,6 +8,7 @@ import javax.persistence.*; import java.time.LocalDate; +import java.time.LocalDateTime; import java.time.LocalTime; @Getter @@ -31,17 +32,17 @@ public class Food { private LocalDate date; - private LocalTime time; + private LocalDateTime addedTime; //클라이언트에서 추가하도록 요청 보낸 timestamp private BaseNutrition baseNutrition; // 생성 메서드 - public static Food createFood(String name, User user, BaseNutrition baseNutrition) { + public static Food createFood(String name, User user, BaseNutrition baseNutrition, int year, int month, int day) { Food food = new Food(); food.name = name; food.user = user; - food.date = LocalDate.now(); - food.time = LocalTime.now(); + food.date = LocalDate.of(year, month, day); + food.addedTime = LocalDateTime.now(); food.baseNutrition = baseNutrition; return food; } From b30f6869d91438bf23a1efa62802ddb8f38e1fc7 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 01:44:12 +0900 Subject: [PATCH 222/371] =?UTF-8?q?:recycle:=20refactor:=20Redis=20?= =?UTF-8?q?=EC=BA=90=EC=8B=9C=EB=A5=BC=20=EC=9C=84=ED=95=9C=20getDate()=20?= =?UTF-8?q?=EC=84=A0=EC=96=B8=20(#72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/dto/CreateFoodDto.java | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java index b08bf01..fd982c3 100644 --- a/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/CreateFoodDto.java @@ -25,10 +25,17 @@ public class CreateFoodDto { @NotNull(message = MessageUtil.NOT_NULL) private BaseNutrition baseNutrition; - @PastOrPresent(message = MessageUtil.PAST_OR_PRESENT) - private LocalDate date; + private int year; - public static CreateFoodDto of(Long userId, String name, BaseNutrition baseNutrition, LocalDate date) { - return new CreateFoodDto(userId, name, baseNutrition, date); + private int month; + + private int day; + + public static CreateFoodDto of(Long userId, String name, BaseNutrition baseNutrition, int year, int month, int day) { + return new CreateFoodDto(userId, name, baseNutrition, year, month, day); + } + + public LocalDate getDate() { + return LocalDate.of(year, month, day); } } From e649bd2eb0611cc0711a4cc83093aa2519a3855f Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 01:45:03 +0900 Subject: [PATCH 223/371] =?UTF-8?q?:recycle:=20refactor:=20Food.createFood?= =?UTF-8?q?()=20=EC=9D=B8=EC=9E=90=20=EB=B3=80=EA=B2=BD=EC=9C=BC=EB=A1=9C?= =?UTF-8?q?=20=EC=9D=B8=ED=95=9C=20favoriteFood=20=EB=A9=94=EC=86=8C?= =?UTF-8?q?=EB=93=9C=20=EC=88=98=EC=A0=95=20(#72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/domain/FavoriteFood.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java index 266256a..14138ce 100644 --- a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java +++ b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java @@ -7,6 +7,7 @@ import lombok.NoArgsConstructor; import javax.persistence.*; +import java.time.LocalDate; @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @@ -53,7 +54,8 @@ public void updateFavoriteFood(String name, BaseNutrition baseNutrition) { // 즐겨찾기 음식 정보로 새 음식 정보 생성 public static Food createFoodFromFavoriteFood(FavoriteFood favoriteFood) { favoriteFood.addCount(); - return Food.createFood(favoriteFood.getName(), favoriteFood.getUser(), favoriteFood.getBaseNutrition()); + LocalDate createdDate = LocalDate.now(); + return Food.createFood(favoriteFood.getName(), favoriteFood.getUser(), favoriteFood.getBaseNutrition(), createdDate.getYear(), createdDate.getMonthValue(), createdDate.getDayOfMonth()); } public void setId(Long id) { From a15bb2a7ab0549526b16950ad652d76fabfb8f05 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 01:45:48 +0900 Subject: [PATCH 224/371] =?UTF-8?q?:recycle:=20refactor:=20createFood()=20?= =?UTF-8?q?=EC=9D=B8=EC=9E=90=20=EC=88=98=EC=A0=95=EC=9C=BC=EB=A1=9C=20?= =?UTF-8?q?=EC=9D=B8=ED=95=9C=20=EB=A9=94=EC=86=8C=EB=93=9C=20=EB=B3=80?= =?UTF-8?q?=EA=B2=BD=20(#72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/service/FoodService.java | 4 ++-- 1 file changed, 2 insertions(+), 2 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 5b09f16..a6e1a3f 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -42,7 +42,7 @@ public Long saveFood(CreateFoodDto createFoodDto) { throw new FoodException(ResponseCode.FOOD_NAME_ALREADY_EXIST); } User user = getUserById(createFoodDto.getUserId()); - Food food = Food.createFood(createFoodDto.getName(), user, createFoodDto.getBaseNutrition()); + Food food = Food.createFood(createFoodDto.getName(), user, createFoodDto.getBaseNutrition(), createFoodDto.getYear(), createFoodDto.getMonth(), createFoodDto.getDay()); return foodRepository.save(food).getId(); } @@ -53,7 +53,7 @@ public List getFoodListByDate(Long userId, LocalDate date){ validateUser(userId); List foodList = foodRepository.findAllByUserIdAndDate(userId, date); return foodList.stream() - .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getDate(), food.getTime(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); + .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); } // 음식 정보 수정 From 182df52a9961b0eb3909afae9097f681da753678 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 01:46:03 +0900 Subject: [PATCH 225/371] =?UTF-8?q?:recycle:=20refactor:=20=EC=9D=B8?= =?UTF-8?q?=EC=9E=90=20=EC=88=98=EC=A0=95=EC=9C=BC=EB=A1=9C=20=EC=9D=B8?= =?UTF-8?q?=ED=95=9C=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20(#72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/dto/ResponseFoodDto.java | 4 +- .../controller/FoodControllerTest.java | 6 +- .../diareat/service/FoodServiceTest.java | 58 +++++++++---------- 3 files changed, 33 insertions(+), 35 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java index 46d2055..959e6d6 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java @@ -15,12 +15,10 @@ public class ResponseFoodDto { private Long foodId; private Long userId; private String name; - //private LocalDate date; - //private LocalTime time; private BaseNutrition baseNutrition; private boolean isFavorite; - public static ResponseFoodDto of(Long foodId, Long userId, String name, LocalDate date, LocalTime time, BaseNutrition baseNutrition, boolean isFavorite) { + public static ResponseFoodDto of(Long foodId, Long userId, String name, BaseNutrition baseNutrition, boolean isFavorite) { return new ResponseFoodDto(foodId, userId, name, baseNutrition, isFavorite); } diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index 0d3c743..a3f0096 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -51,7 +51,7 @@ public class FoodControllerTest { 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 Food testFood = Food.createFood("testFood", testUser, BaseNutrition.createNutrition(500, 50, 30, 10), 2021, 10, 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); @@ -69,7 +69,7 @@ void setUp() { @WithMockUser("test") void testSaveFood() throws Exception { //Given - CreateFoodDto createFoodDto = CreateFoodDto.of(testUserId, "test", testBaseNutrition, LocalDate.now()); + CreateFoodDto createFoodDto = CreateFoodDto.of(testUserId, "test", testBaseNutrition, 2021, 10, 10); when(foodService.saveFood(any(CreateFoodDto.class))).thenReturn(testFoodId); ApiResponse expectedResponse = ApiResponse.success(foodService.saveFood(createFoodDto), ResponseCode.FOOD_CREATE_SUCCESS.getMessage()); @@ -101,7 +101,7 @@ void testGetFoodListByDate() throws Exception { int mm = 12; LocalDate date = LocalDate.of(yy, mm, dd); - ResponseFoodDto food1 = ResponseFoodDto.of(testFoodId, testUserId,"test", LocalDate.now(), LocalTime.now(),testBaseNutrition,false); + ResponseFoodDto food1 = ResponseFoodDto.of(testFoodId, testUserId,"test",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()); diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index b011034..8632350 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -59,8 +59,8 @@ void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리 User user = User.createUser("testUser", "testImage","testPassword", 1,180, 80,18, testBaseNutrition); user.setId(1L); - CreateFoodDto createFoodDto = CreateFoodDto.of(user.getId(), "testFood", testBaseNutrition, LocalDate.now()); - Food food = Food.createFood("testFood", user, testBaseNutrition); + CreateFoodDto createFoodDto = CreateFoodDto.of(user.getId(), "testFood", testBaseNutrition, 2010,1,1); + Food food = Food.createFood("testFood", user, testBaseNutrition, 2010,1,1); food.setId(2L); given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); @@ -83,7 +83,7 @@ void testUpdateFood() { //given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); User user = User.createUser("testUser", "testImage","tessPassword", 1, 180, 80, 18, testBaseNutrition); - Food food = Food.createFood("testFood", user, testBaseNutrition); + Food food = Food.createFood("testFood", user, testBaseNutrition, 2010,1,1); food.setId(1L); given(foodRepository.findById(food.getId())).willReturn(Optional.of(food)); @@ -106,7 +106,7 @@ void testDeleteFood() { //given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); User user = User.createUser("testUser", "testImage","tessPassword", 1, 180, 80, 18, testBaseNutrition); - Food food = Food.createFood("testFood", user, testBaseNutrition); + Food food = Food.createFood("testFood", user, testBaseNutrition, 2010,1,1); food.setId(1L); given(foodRepository.existsById(food.getId())).willReturn(true); @@ -187,7 +187,7 @@ void testNutritionSumByDate(){ BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); User user = User.createUser("testUser", "testImage","testPassword",1, 180, 80, 18, BaseNutrition.createNutrition(2000,300,80,80)); user.setId(1L); - Food food = Food.createFood("testFood", user, testFoodNutrition); + Food food = Food.createFood("testFood", user, testFoodNutrition, 2010,1,1); food.setId(2L); given(userRepository.existsById(user.getId())).willReturn(true); @@ -214,7 +214,7 @@ void testNutritionSumByWeek(){ BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); User user = User.createUser("testUser", "testImage","testPassword",1, 180, 80, 18, BaseNutrition.createNutrition(2000,300,80,80)); user.setId(1L); - Food food = Food.createFood("testFood", user, testFoodNutrition); + Food food = Food.createFood("testFood", user, testFoodNutrition, 2010,1,1); food.setId(2L); given(userRepository.existsById(user.getId())).willReturn(true); @@ -243,7 +243,7 @@ void testNutritionSumByMonth(){ BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); User user = User.createUser("testUser", "testImage","testPassword",1, 180, 80, 18, BaseNutrition.createNutrition(2000,300,80,80)); user.setId(1L); - Food food = Food.createFood("testFood", user, testFoodNutrition); + Food food = Food.createFood("testFood", user, testFoodNutrition, 2010,1,1); food.setId(2L); given(userRepository.existsById(user.getId())).willReturn(true); @@ -270,11 +270,11 @@ void testNutritionSumByMonth(){ void getBest3FoodTest() { // given User user = User.createUser("testUser", "testImage","testPassword", 1, 180, 80, 18, BaseNutrition.createNutrition(1,1,1,1)); - 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)); + Food food1 = Food.createFood( "Food1", user, BaseNutrition.createNutrition(100, 100 ,10, 1), 2010,1,1); + Food food2 = Food.createFood( "Food2", user, BaseNutrition.createNutrition(100, 100 ,8, 2), 2010,1,1); + Food food3 = Food.createFood( "Food3", user, BaseNutrition.createNutrition(100, 100 ,6, 3), 2010,1,1); + Food food4 = Food.createFood( "Food4", user, BaseNutrition.createNutrition(100, 100 ,4, 4), 2010,1,1); + Food food5 = Food.createFood( "Food5", user, BaseNutrition.createNutrition(100, 100 ,2, 5), 2010,1,1); user.setId(1L); List foodList = List.of(food1, food2, food3, food4, food5); @@ -297,11 +297,11 @@ void getBest3FoodTest() { void getWorst3FoodsTest() { // given User user = User.createUser("testUser", "testImage","testPassword", 1, 180, 80, 18, BaseNutrition.createNutrition(1,1,1,1)); - Food food1 = Food.createFood( "Food1", user, BaseNutrition.createNutrition(100, 50 ,10, 1)); - Food food2 = Food.createFood( "Food2", user, BaseNutrition.createNutrition(100, 100 ,8, 20)); - Food food3 = Food.createFood( "Food3", user, BaseNutrition.createNutrition(100, 80 ,6, 7)); - Food food4 = Food.createFood( "Food4", user, BaseNutrition.createNutrition(100, 100 ,4, 5)); - Food food5 = Food.createFood( "Food5", user, BaseNutrition.createNutrition(100, 90 ,2, 6)); + Food food1 = Food.createFood( "Food1", user, BaseNutrition.createNutrition(100, 50 ,10, 1), 2010,1,1); + Food food2 = Food.createFood( "Food2", user, BaseNutrition.createNutrition(100, 100 ,8, 20), 2010,1,1); + Food food3 = Food.createFood( "Food3", user, BaseNutrition.createNutrition(100, 80 ,6, 7), 2010,1,1); + Food food4 = Food.createFood( "Food4", user, BaseNutrition.createNutrition(100, 100 ,4, 5), 2010,1,1); + Food food5 = Food.createFood( "Food5", user, BaseNutrition.createNutrition(100, 90 ,2, 6), 2010,1,1); user.setId(1L); List foodList = List.of(food1, food2, food3, food4, food5); @@ -328,8 +328,8 @@ void getUserRankByWeek() { user1.setId(1L); user2.setId(2L); - Food food1 = Food.createFood( "Food1", user1, BaseNutrition.createNutrition(1000, 100 ,100, 100)); - Food food2 = Food.createFood( "Food2", user2, BaseNutrition.createNutrition(2000, 110 ,50, 90)); + Food food1 = Food.createFood( "Food1", user1, BaseNutrition.createNutrition(1000, 100 ,100, 100), 2010,1,1); + Food food2 = Food.createFood( "Food2", user2, BaseNutrition.createNutrition(2000, 110 ,50, 90), 2010,1,1); given(userRepository.findById(user1.getId())).willReturn(Optional.of(user1)); given(followRepository.findAllByFromUser(user1.getId())).willReturn(List.of(user2)); @@ -364,10 +364,10 @@ void getUserRankByWeek() { 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 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 food1 = Food.createFood( "Food1", user, BaseNutrition.createNutrition(100, 100 ,10, 1), 2010,1,1); + Food food1_1 = Food.createFood( "Food1_1", user, BaseNutrition.createNutrition(130, 100 ,8, 2), 2010,1,1); + Food food2 = Food.createFood( "Food2", user, BaseNutrition.createNutrition(150, 100 ,8, 2), 2010,1,1); + Food food3 = Food.createFood( "Food3", user, BaseNutrition.createNutrition(200, 100 ,6, 3), 2010,1,1); user.setId(1L); food1.setDate(LocalDate.now()); @@ -405,12 +405,12 @@ void testGetScoreOfUserWithBestAndWorstFoods(){ 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)); + Food food1 = Food.createFood( "Food1", user, BaseNutrition.createNutrition(100, 100 ,10, 1), 2010,1,1); + Food food1_1 = Food.createFood( "Food1_1", user, BaseNutrition.createNutrition(130, 100 ,8, 2), 2010,1,1); + Food food2 = Food.createFood( "Food2", user, BaseNutrition.createNutrition(150, 100 ,8, 2), 2010,1,1); + Food food3 = Food.createFood( "Food3", user, BaseNutrition.createNutrition(200, 100 ,6, 3), 2010,1,1); + Food food4 = Food.createFood( "Food4", user, BaseNutrition.createNutrition(250, 100 ,4, 4), 2010,1,1); + Food food5 = Food.createFood( "Food5", user, BaseNutrition.createNutrition(300, 100 ,2, 5), 2010,1,1); user.setId(1L); food1.setDate(LocalDate.now()); From 078f9b9fcd77f79071c9a966de71f9fc157b8403 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 02:01:04 +0900 Subject: [PATCH 226/371] =?UTF-8?q?:sparkles:=20feat:=20=EC=83=9D=EC=84=B1?= =?UTF-8?q?=20=EB=82=A0=EC=A7=9C=EB=B3=84=20=EC=A0=95=EB=A0=AC=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20(#72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/food/repository/FoodRepository.java | 5 +++-- 1 file changed, 3 insertions(+), 2 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 ce4dada..d11d496 100644 --- a/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java +++ b/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java @@ -1,6 +1,7 @@ package com.diareat.diareat.food.repository; import com.diareat.diareat.food.domain.Food; +import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.JpaRepository; import java.time.LocalDate; @@ -9,6 +10,6 @@ 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); // 유저가 특정 기간 내에 먹은 음식 반환 + List findAllByUserIdAndDate(Long userId, LocalDate date, Sort sort); //유저가 특정 날짜에 먹은 음식 반환 + List findAllByUserIdAndDateBetween(Long userId, LocalDate startDate, LocalDate endDate, Sort sort); // 유저가 특정 기간 내에 먹은 음식 반환 } From 6fc4776049dea1bbf0b41ea128c34bbb5997fd3b Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 02:01:25 +0900 Subject: [PATCH 227/371] =?UTF-8?q?:sparkles:=20feat:=20=EC=83=9D=EC=84=B1?= =?UTF-8?q?=20=EB=82=A0=EC=A7=9C=EB=B3=84=20=EB=82=B4=EB=A6=BC=EC=B0=A8?= =?UTF-8?q?=EC=88=9C=20=EC=A0=95=EB=A0=AC=20(#72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 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 a6e1a3f..3a5843c 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -16,6 +16,7 @@ import com.diareat.diareat.util.exception.UserException; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheEvict; +import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.cache.annotation.Cacheable; @@ -51,7 +52,8 @@ public Long saveFood(CreateFoodDto createFoodDto) { @Transactional(readOnly = true) public List getFoodListByDate(Long userId, LocalDate date){ validateUser(userId); - List foodList = foodRepository.findAllByUserIdAndDate(userId, date); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + List foodList = foodRepository.findAllByUserIdAndDate(userId, date, sort); return foodList.stream() .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); } @@ -117,7 +119,8 @@ public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { validateUser(userId); - List foodList = foodRepository.findAllByUserIdAndDate(userId, date); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + List foodList = foodRepository.findAllByUserIdAndDate(userId, date, sort); return calculateNutritionSumAndRatio(userId, foodList, date, 1); } @@ -126,7 +129,8 @@ public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDat public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); return calculateNutritionSumAndRatio(userId, foodList, endDate, 7); } @@ -136,7 +140,8 @@ public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusMonths(1), endDate); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusMonths(1), endDate, sort); return calculateNutritionSumAndRatio(userId, foodList, endDate, 30); } @@ -146,7 +151,8 @@ public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { public ResponseFoodRankDto getBestFoodByWeek(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); List top3Foods = foodList.stream() .sorted(Comparator.comparingDouble((Food food) -> @@ -168,7 +174,8 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId) { public ResponseFoodRankDto getWorstFoodByWeek(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); List worst3Foods = foodList.stream() .sorted(Comparator.comparingDouble((Food food) -> @@ -395,7 +402,8 @@ private void validateFavoriteFood(Long favoriteFoodId, Long userId) { // 1주일동안 먹은 음식들의 영양성분 총합을 요일을 Key로 한 Map을 통해 반환 private HashMap> getNutritionSumByDateMap(Long userId, LocalDate startDate, LocalDate endDate) { HashMap> maps = new HashMap<>(); - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, endDate); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, endDate, sort); for (Food food : foodList) { if (maps.containsKey(food.getDate())) { maps.get(food.getDate()).add(food.getBaseNutrition()); From de863e18ba136cd6b9d0b32fb3551bcb75d76ce5 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 02:01:49 +0900 Subject: [PATCH 228/371] =?UTF-8?q?:recycle:=20refactor:=20=EC=A0=95?= =?UTF-8?q?=EB=A0=AC=20=EC=B6=94=EA=B0=80=EC=97=90=20=EB=94=B0=EB=A5=B8=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=20(#72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/FoodServiceTest.java | 37 ++++++++++--------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 8632350..f1a6d0d 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -18,6 +18,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Sort; import java.time.DayOfWeek; @@ -66,7 +67,7 @@ void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리 given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); given(userRepository.existsById(user.getId())).willReturn(true); given(foodRepository.save(any(Food.class))).willReturn(food); - given(foodRepository.findAllByUserIdAndDate(any(Long.class), any(LocalDate.class))).willReturn(List.of(food)); + given(foodRepository.findAllByUserIdAndDate(any(Long.class), any(LocalDate.class), any(Sort.class))).willReturn(List.of(food)); //when Long foodId = foodService.saveFood(createFoodDto); @@ -192,7 +193,7 @@ void testNutritionSumByDate(){ given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); - given(foodRepository.findAllByUserIdAndDate(any(Long.class), any(LocalDate.class))).willReturn(List.of(food)); + given(foodRepository.findAllByUserIdAndDate(any(Long.class), any(LocalDate.class), any(Sort.class))).willReturn(List.of(food)); //when @@ -219,7 +220,7 @@ void testNutritionSumByWeek(){ given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); - given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(List.of(food)); + given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class), any(Sort.class))).willReturn(List.of(food)); @@ -248,7 +249,7 @@ void testNutritionSumByMonth(){ given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); - given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(List.of(food)); + given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class),any(Sort.class))).willReturn(List.of(food)); @@ -279,7 +280,7 @@ void getBest3FoodTest() { List foodList = List.of(food1, food2, food3, food4, food5); - given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(foodList); + given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class),any(Sort.class))).willReturn(foodList); given(userRepository.existsById(user.getId())).willReturn(true); // when @@ -306,7 +307,7 @@ void getWorst3FoodsTest() { List foodList = List.of(food1, food2, food3, food4, food5); - given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(foodList); + given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class),any(Sort.class))).willReturn(foodList); given(userRepository.existsById(user.getId())).willReturn(true); // when @@ -333,8 +334,8 @@ void getUserRankByWeek() { given(userRepository.findById(user1.getId())).willReturn(Optional.of(user1)); given(followRepository.findAllByFromUser(user1.getId())).willReturn(List.of(user2)); - given(foodRepository.findAllByUserIdAndDateBetween(eq(1L), any(LocalDate.class), any(LocalDate.class))).willReturn(List.of(food1)); - given(foodRepository.findAllByUserIdAndDateBetween(eq(2L), any(LocalDate.class), any(LocalDate.class))).willReturn(List.of(food2)); + given(foodRepository.findAllByUserIdAndDateBetween(eq(1L), any(LocalDate.class), any(LocalDate.class),any(Sort.class))).willReturn(List.of(food1)); + given(foodRepository.findAllByUserIdAndDateBetween(eq(2L), any(LocalDate.class), any(LocalDate.class),any(Sort.class))).willReturn(List.of(food2)); // when List response = foodService.getUserRankByWeek(user1.getId()); @@ -356,8 +357,8 @@ void getUserRankByWeek() { assertEquals(250, response.get(1).getTotalScore()); verify(userRepository, times(1)).findById(user1.getId()); verify(followRepository, times(1)).findAllByFromUser(user1.getId()); - 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)); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(eq(1L), any(LocalDate.class), any(LocalDate.class),any(Sort.class)); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(eq(2L), any(LocalDate.class), any(LocalDate.class),any(Sort.class)); } @Test @@ -379,7 +380,7 @@ void testGetScoreOfUserWithBestAndWorstFoods(){ 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); + given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class),any(Sort.class))).willReturn(foodList); // when ResponseScoreBestWorstDto response = foodService.getScoreOfUserWithBestAndWorstFoods(user.getId()); @@ -424,14 +425,16 @@ void testGetAnalysisOfUser(){ List foodListOfWeek = List.of(food1,food1_1, food2, food3); List foodListOfMonth = List.of(food1, food1_1,food2, food3, food4, food5); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + 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); + given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().minusWeeks(1), LocalDate.now(),sort)).willReturn(foodListOfWeek); + given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().minusWeeks(3).with(DayOfWeek.MONDAY), LocalDate.now(),sort)).willReturn(foodListOfMonth); + given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now(),sort)).willReturn(foodListOfWeek); // when @@ -479,9 +482,9 @@ void testGetAnalysisOfUser(){ 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()); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().minusWeeks(1), LocalDate.now(),sort); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().minusWeeks(3).with(DayOfWeek.MONDAY), LocalDate.now(),sort); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now(),sort); } } From 0c6001342643f9e223fef07fef52b50454c0ed25 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 12 Nov 2023 03:30:57 +0000 Subject: [PATCH 229/371] :construction_worker: chore: Update deployment to bb2f9ec6aec08db291ff7f2ef245f9d5487824a3 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index bbf3fab..0a51d8d 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 92b7a185 + newTag: bb2f9ec6 From 7a3f003d1db92482e7ba037755eeb0cc2388107a Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 14:10:04 +0900 Subject: [PATCH 230/371] =?UTF-8?q?:bug:=20fix:=20=ED=85=8C=EC=9D=B4?= =?UTF-8?q?=EB=B8=94=EC=9D=98=20=EC=B9=BC=EB=9F=BC=20=EB=AA=85=EA=B3=BC=20?= =?UTF-8?q?=EC=A7=81=EC=A0=91=20=EB=A7=A4=ED=95=91=20(#74)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/domain/Food.java | 1 + .../diareat/diareat/food/service/FoodService.java | 14 +++++++------- 2 files changed, 8 insertions(+), 7 deletions(-) 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 e230619..a8166c6 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -32,6 +32,7 @@ public class Food { private LocalDate date; + @Column(name = "added_time") //테이블과 매핑 private LocalDateTime addedTime; //클라이언트에서 추가하도록 요청 보낸 timestamp private BaseNutrition baseNutrition; 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 3a5843c..9f8961b 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -52,7 +52,7 @@ public Long saveFood(CreateFoodDto createFoodDto) { @Transactional(readOnly = true) public List getFoodListByDate(Long userId, LocalDate date){ validateUser(userId); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); List foodList = foodRepository.findAllByUserIdAndDate(userId, date, sort); return foodList.stream() .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); @@ -119,7 +119,7 @@ public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { validateUser(userId); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); List foodList = foodRepository.findAllByUserIdAndDate(userId, date, sort); return calculateNutritionSumAndRatio(userId, foodList, date, 1); } @@ -129,7 +129,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDat public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); return calculateNutritionSumAndRatio(userId, foodList, endDate, 7); @@ -140,7 +140,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusMonths(1), endDate, sort); return calculateNutritionSumAndRatio(userId, foodList, endDate, 30); @@ -151,7 +151,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { public ResponseFoodRankDto getBestFoodByWeek(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); List top3Foods = foodList.stream() @@ -174,7 +174,7 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId) { public ResponseFoodRankDto getWorstFoodByWeek(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); List worst3Foods = foodList.stream() @@ -402,7 +402,7 @@ private void validateFavoriteFood(Long favoriteFoodId, Long userId) { // 1주일동안 먹은 음식들의 영양성분 총합을 요일을 Key로 한 Map을 통해 반환 private HashMap> getNutritionSumByDateMap(Long userId, LocalDate startDate, LocalDate endDate) { HashMap> maps = new HashMap<>(); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, endDate, sort); for (Food food : foodList) { if (maps.containsKey(food.getDate())) { From 25d7bddbb20d36f766ea274540342c2d91e9025e Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 14:14:45 +0900 Subject: [PATCH 231/371] =?UTF-8?q?:bug:=20fix:=20test=EC=9D=98=20Sort=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20(#74)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/com/diareat/diareat/service/FoodServiceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index f1a6d0d..9316536 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -425,7 +425,7 @@ void testGetAnalysisOfUser(){ List foodListOfWeek = List.of(food1,food1_1, food2, food3); List foodListOfMonth = List.of(food1, food1_1,food2, food3, food4, food5); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); From e8297a1dc0edeab5fe3eff66a408b68b90f494ed Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 12 Nov 2023 05:20:14 +0000 Subject: [PATCH 232/371] :construction_worker: chore: Update deployment to 3159469eaebe227e4a484d3b69fa5d7daf8587ff --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 0a51d8d..8e03580 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: bb2f9ec6 + newTag: 3159469e From 45cc8c7712be6d33ddcde07df74a224dc3e2233c Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Sun, 12 Nov 2023 14:23:31 +0900 Subject: [PATCH 233/371] :green_heart: fix: Update manifest.yaml --- k8s/manifest.yaml | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/k8s/manifest.yaml b/k8s/manifest.yaml index 56a083c..25d53de 100644 --- a/k8s/manifest.yaml +++ b/k8s/manifest.yaml @@ -5,7 +5,6 @@ metadata: namespace: diareat spec: revisionHistoryLimit: 3 - replicas: 2 selector: matchLabels: app: diareat @@ -23,8 +22,8 @@ spec: name: diareat-secret resources: limits: - memory: "512Mi" - cpu: 0.5 + memory: "4G" + cpu: 1 ports: - containerPort: 8080 readinessProbe: @@ -75,8 +74,8 @@ spec: apiVersion: apps/v1 kind: Deployment name: diareat-deployment - minReplicas: 2 - maxReplicas: 4 + minReplicas: 1 + maxReplicas: 3 metrics: - type: Resource resource: From da6f4b8da9b7bcc3409f10735c8324ccad970eac Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Sun, 12 Nov 2023 14:41:10 +0900 Subject: [PATCH 234/371] :green_heart: fix: Update manifest.yaml --- k8s/manifest.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/k8s/manifest.yaml b/k8s/manifest.yaml index 25d53de..ec3458e 100644 --- a/k8s/manifest.yaml +++ b/k8s/manifest.yaml @@ -21,6 +21,9 @@ spec: - secretRef: name: diareat-secret resources: + requests: + memory: "2G" + cpu: 0.4 limits: memory: "4G" cpu: 1 From a05b19fd9d4afde5cebe24f0920c92bc600b401e Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 15:28:22 +0900 Subject: [PATCH 235/371] =?UTF-8?q?:ambulance:=20hotfix:=20sort=20by=20?= =?UTF-8?q?=EC=9D=B8=EC=9E=90=20=EC=88=98=EC=A0=95=20(#76)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/service/FoodService.java | 14 +++++++------- .../diareat/diareat/service/FoodServiceTest.java | 2 +- 2 files changed, 8 insertions(+), 8 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 9f8961b..3a5843c 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -52,7 +52,7 @@ public Long saveFood(CreateFoodDto createFoodDto) { @Transactional(readOnly = true) public List getFoodListByDate(Long userId, LocalDate date){ validateUser(userId); - Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); List foodList = foodRepository.findAllByUserIdAndDate(userId, date, sort); return foodList.stream() .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); @@ -119,7 +119,7 @@ public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { validateUser(userId); - Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); List foodList = foodRepository.findAllByUserIdAndDate(userId, date, sort); return calculateNutritionSumAndRatio(userId, foodList, date, 1); } @@ -129,7 +129,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDat public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); return calculateNutritionSumAndRatio(userId, foodList, endDate, 7); @@ -140,7 +140,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusMonths(1), endDate, sort); return calculateNutritionSumAndRatio(userId, foodList, endDate, 30); @@ -151,7 +151,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { public ResponseFoodRankDto getBestFoodByWeek(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); List top3Foods = foodList.stream() @@ -174,7 +174,7 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId) { public ResponseFoodRankDto getWorstFoodByWeek(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); List worst3Foods = foodList.stream() @@ -402,7 +402,7 @@ private void validateFavoriteFood(Long favoriteFoodId, Long userId) { // 1주일동안 먹은 음식들의 영양성분 총합을 요일을 Key로 한 Map을 통해 반환 private HashMap> getNutritionSumByDateMap(Long userId, LocalDate startDate, LocalDate endDate) { HashMap> maps = new HashMap<>(); - Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, endDate, sort); for (Food food : foodList) { if (maps.containsKey(food.getDate())) { diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 9316536..f1a6d0d 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -425,7 +425,7 @@ void testGetAnalysisOfUser(){ List foodListOfWeek = List.of(food1,food1_1, food2, food3); List foodListOfMonth = List.of(food1, food1_1,food2, food3, food4, food5); - Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); + Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); From 3552758987ba96300b34205ec5eb03b47dc6b283 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 12 Nov 2023 06:31:11 +0000 Subject: [PATCH 236/371] :construction_worker: chore: Update deployment to 743e9ff780f964571c8b256d2f4345cb4d2b25ac --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 8e03580..7bdf6da 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 3159469e + newTag: 743e9ff7 From 85b3db44fe19ca70b9c3af2e5c7905585335a4d4 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 15:49:49 +0900 Subject: [PATCH 237/371] =?UTF-8?q?:ambulance:=20hotfix:=20key=EA=B0=92?= =?UTF-8?q?=EC=9D=98=20date=20string=EC=9C=BC=EB=A1=9C=20=EB=B3=80?= =?UTF-8?q?=ED=99=98=20(#78)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/food/service/FoodService.java | 2 +- 1 file changed, 1 insertion(+), 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 3a5843c..8098430 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -36,7 +36,7 @@ public class FoodService { private final UserRepository userRepository; // 촬영 후, 음식 정보 저장 - @CacheEvict(value = "ResponseFoodDto", key = "#createFoodDto.getUserId()+#createFoodDto.getDate()", cacheManager = "diareatCacheManager") + @CacheEvict(value = "ResponseFoodDto", key = "#createFoodDto.getUserId()+#createFoodDto.getDate().toString()", cacheManager = "diareatCacheManager") @Transactional public Long saveFood(CreateFoodDto createFoodDto) { if (foodRepository.existsByName(createFoodDto.getName())){ From ec17ee1ca3a3d54fdcc77bf9fa7015f6657dca58 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 12 Nov 2023 06:52:13 +0000 Subject: [PATCH 238/371] :construction_worker: chore: Update deployment to 4f9b7ef9368781248e05aa4299ff90778985be36 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 7bdf6da..6d0e5c2 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 743e9ff7 + newTag: 4f9b7ef9 From 4cf032468cb7318d1c090809a73b8f7cd4289c91 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 16:16:17 +0900 Subject: [PATCH 239/371] =?UTF-8?q?:ambulance:=20hotfix:=20noargsconstruct?= =?UTF-8?q?or=20=EC=B6=94=EA=B0=80=20(#80)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java index 959e6d6..90099a3 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java @@ -4,12 +4,14 @@ import com.diareat.diareat.user.domain.BaseNutrition; import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; import java.time.LocalDate; import java.time.LocalTime; @Getter @AllArgsConstructor +@NoArgsConstructor public class ResponseFoodDto { private Long foodId; From 54083beb283635a1f46450410c62dd18da5d8509 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 12 Nov 2023 07:18:37 +0000 Subject: [PATCH 240/371] :construction_worker: chore: Update deployment to 2f8d06783872f88ce5ccc29011b122447fb66b63 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 6d0e5c2..24969ac 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 4f9b7ef9 + newTag: 2f8d0678 From 70bf6a7e536aa509921b3b67f2c9e9c58857d8c5 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 12 Nov 2023 16:45:25 +0900 Subject: [PATCH 241/371] =?UTF-8?q?:ambulance:=20hotfix:=20responsefooddto?= =?UTF-8?q?=EC=9D=98=20=ED=95=84=EB=93=9C=EB=AA=85=20=EB=B3=80=EA=B2=BD=20?= =?UTF-8?q?(#82)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/dto/ResponseFoodDto.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java index 90099a3..af7e268 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java @@ -18,10 +18,10 @@ public class ResponseFoodDto { private Long userId; private String name; private BaseNutrition baseNutrition; - private boolean isFavorite; + private boolean favoriteChecked; - public static ResponseFoodDto of(Long foodId, Long userId, String name, BaseNutrition baseNutrition, boolean isFavorite) { - return new ResponseFoodDto(foodId, userId, name, baseNutrition, isFavorite); + public static ResponseFoodDto of(Long foodId, Long userId, String name, BaseNutrition baseNutrition, boolean favoriteChecked) { + return new ResponseFoodDto(foodId, userId, name, baseNutrition, favoriteChecked); } public static ResponseFoodDto from(Food food) { From 889369df70930fc0f454c3c78188d19b3b6920af Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 12 Nov 2023 07:47:39 +0000 Subject: [PATCH 242/371] :construction_worker: chore: Update deployment to 9b60352cf57b2fd7f8df2c998ed69c803657d20f --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 24969ac..84c280f 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 2f8d0678 + newTag: 9b60352c From 7a0b366719293426eb87d0b27fdb18bcdf60efe1 Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 12 Nov 2023 22:36:20 +0900 Subject: [PATCH 243/371] =?UTF-8?q?:ambulance:=20Fix:=20UserDto=20?= =?UTF-8?q?=EC=BA=90=EC=8B=B1=20Key=20getter=20=EB=88=84=EB=9D=BD=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20(#84)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/user/service/UserService.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 894bed9..0780844 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -65,7 +65,7 @@ public ResponseUserDto getUserInfo(Long userId) { } // 회원정보 수정 - @CacheEvict(value = {"ResponseSimpleUserDto", "ResponseUserDto"}, key = "#updateUserDto.userId", cacheManager = "diareatCacheManager") + @CacheEvict(value = {"ResponseSimpleUserDto", "ResponseUserDto"}, key = "#updateUserDto.getUserId()", cacheManager = "diareatCacheManager") @Transactional public void updateUserInfo(UpdateUserDto updateUserDto) { User user = getUserById(updateUserDto.getUserId()); @@ -83,7 +83,7 @@ public ResponseUserNutritionDto getUserNutrition(Long userId) { } // 회원 기준섭취량 직접 수정 - @CacheEvict(value = "ResponseUserNutritionDto", key = "#updateUserNutritionDto.userId", cacheManager = "diareatCacheManager") + @CacheEvict(value = "ResponseUserNutritionDto", key = "#updateUserNutritionDto.getUserId()", cacheManager = "diareatCacheManager") @Transactional public void updateBaseNutrition(UpdateUserNutritionDto updateUserNutritionDto) { User user = getUserById(updateUserNutritionDto.getUserId()); From 532344d9015d82cf67fe7526588299f9e8b2bf17 Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 12 Nov 2023 22:37:29 +0900 Subject: [PATCH 244/371] =?UTF-8?q?:ambulance:=20Fix:=20ResponseSimpleUser?= =?UTF-8?q?Dto=20=EB=8D=94=EB=AF=B8=20=EC=98=81=EC=96=91=EC=A0=90=EC=88=98?= =?UTF-8?q?=20=EC=82=AD=EC=A0=9C=20(#84)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/dto/response/ResponseSimpleUserDto.java | 5 ++--- .../java/com/diareat/diareat/user/service/UserService.java | 3 +-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java index 650b9cb..5a707ef 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java @@ -9,9 +9,8 @@ public class ResponseSimpleUserDto { private String name; private String image; - private double nutritionScore; - public static ResponseSimpleUserDto of(String name, String image, double nutritionScore) { - return new ResponseSimpleUserDto(name, image, nutritionScore); + public static ResponseSimpleUserDto of(String name, String image) { + return new ResponseSimpleUserDto(name, image); } } diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 0780844..da3f1ac 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -52,8 +52,7 @@ public Long saveUser(CreateUserDto createUserDto) { @Transactional(readOnly = true) public ResponseSimpleUserDto getSimpleUserInfo(Long userId) { User user = getUserById(userId); - double nutritionScore = 100; // 점수 계산 로직 확정 전 기본값 -> 추후 수정 필요 - return ResponseSimpleUserDto.of(user.getName(), user.getImage(), nutritionScore); + return ResponseSimpleUserDto.of(user.getName(), user.getImage()); } // 회원정보 조회 From d95a931d5b4da3f65917dda40496cfba063fe361 Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 12 Nov 2023 23:38:13 +0900 Subject: [PATCH 245/371] =?UTF-8?q?:ambulance:=20Fix:=20FoodController=20?= =?UTF-8?q?=EC=9D=8C=EC=8B=9D=20=EC=88=98=EC=A0=95/=EC=82=AD=EC=A0=9C=20?= =?UTF-8?q?=EB=A9=94=EC=84=9C=EB=93=9C=20=EC=97=B0=EC=9B=94=EC=9D=BC=20?= =?UTF-8?q?=EB=A7=A4=EA=B0=9C=EB=B3=80=EC=88=98=20=EC=B6=94=EA=B0=80=20(#8?= =?UTF-8?q?4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/controller/FoodController.java | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 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 c86a418..50863a2 100644 --- a/src/main/java/com/diareat/diareat/food/controller/FoodController.java +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -7,7 +7,6 @@ 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.*; @@ -45,15 +44,23 @@ public ApiResponse> getFoodListByDate(@PathVariable Long u //음식 정보 수정 @Operation(summary = "[음식] 음식 정보 수정",description = "음식에 대한 정보를 수정합니다.") @PostMapping("/update") - public ApiResponse updateFood(@RequestBody @Valid UpdateFoodDto updateFoodDto){ - foodService.updateFood(updateFoodDto); + public ApiResponse updateFood(@RequestBody @Valid UpdateFoodDto updateFoodDto, + @RequestParam int yy, + @RequestParam int mm, + @RequestParam int dd){ + LocalDate date = LocalDate.of(yy,mm,dd); + foodService.updateFood(updateFoodDto, date); return ApiResponse.success(null,ResponseCode.FOOD_UPDATE_SUCCESS.getMessage()); } //음식 삭제 @Operation(summary = "[음식] 음식 정보 삭제",description = "음식에 대한 정보를 삭제합니다.") @DeleteMapping("/{foodId}/delete") - public ApiResponse deleteFood(@PathVariable Long foodId, @RequestHeader Long userId){ - foodService.deleteFood(foodId, userId); + public ApiResponse deleteFood(@PathVariable Long foodId, @RequestHeader Long userId, + @RequestParam int yy, + @RequestParam int mm, + @RequestParam int dd){ + LocalDate date = LocalDate.of(yy,mm,dd); + foodService.deleteFood(foodId, userId, date); return ApiResponse.success(null, ResponseCode.FOOD_DELETE_SUCCESS.getMessage()); } From e554b1c1cf592065030839417194f0fb21108dae Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 12 Nov 2023 23:39:15 +0900 Subject: [PATCH 246/371] =?UTF-8?q?:ambulance:=20Fix:=20=EC=BA=90=EC=8B=B1?= =?UTF-8?q?=20=EB=8F=99=EA=B8=B0=ED=99=94=20=EC=A0=81=EC=9A=A9=20=EB=B0=8F?= =?UTF-8?q?=20TimeStamp=20=ED=95=84=EB=93=9C=EB=AA=85=20MessageUtil?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=ED=86=B5=ED=95=A9=20=EA=B4=80=EB=A6=AC=20?= =?UTF-8?q?(#84)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 25 ++++++++++--------- .../com/diareat/diareat/util/MessageUtil.java | 1 + 2 files changed, 14 insertions(+), 12 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 8098430..f9e6baa 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -10,6 +10,7 @@ import com.diareat.diareat.user.dto.response.ResponseRankUserDto; import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; +import com.diareat.diareat.util.MessageUtil; import com.diareat.diareat.util.api.ResponseCode; import com.diareat.diareat.util.exception.FavoriteException; import com.diareat.diareat.util.exception.FoodException; @@ -36,7 +37,7 @@ public class FoodService { private final UserRepository userRepository; // 촬영 후, 음식 정보 저장 - @CacheEvict(value = "ResponseFoodDto", key = "#createFoodDto.getUserId()+#createFoodDto.getDate().toString()", cacheManager = "diareatCacheManager") + @CacheEvict(value = "ResponseFoodDto, ResponseNutritionSumByDateDto", key = "#createFoodDto.getUserId()+#createFoodDto.getDate().toString()", cacheManager = "diareatCacheManager") @Transactional public Long saveFood(CreateFoodDto createFoodDto) { if (foodRepository.existsByName(createFoodDto.getName())){ @@ -52,25 +53,25 @@ public Long saveFood(CreateFoodDto createFoodDto) { @Transactional(readOnly = true) public List getFoodListByDate(Long userId, LocalDate date){ validateUser(userId); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); List foodList = foodRepository.findAllByUserIdAndDate(userId, date, sort); return foodList.stream() .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); } // 음식 정보 수정 - @CacheEvict(value = "ResponseFoodDto", key = "#updateFoodDto.getUserId()", cacheManager = "diareatCacheManager") + @CacheEvict(value = "ResponseFoodDto, ResponseNutritionSumByDateDto", key = "#updateFoodDto.getUserId()+date.toString()", cacheManager = "diareatCacheManager") @Transactional - public void updateFood(UpdateFoodDto updateFoodDto) { + public void updateFood(UpdateFoodDto updateFoodDto, LocalDate date) { Food food = getFoodById(updateFoodDto.getFoodId()); food.updateFood(updateFoodDto.getName(), updateFoodDto.getBaseNutrition()); foodRepository.save(food); } // 음식 삭제 - @CacheEvict(value = "ResponseFoodDto", key = "#userId", cacheManager = "diareatCacheManager") + @CacheEvict(value = "ResponseFoodDto, ResponseNutritionSumByDateDto", key = "#userId+date.toString()", cacheManager = "diareatCacheManager") @Transactional - public void deleteFood(Long foodId, Long userId) { + public void deleteFood(Long foodId, Long userId, LocalDate date) { validateFood(foodId, userId); foodRepository.deleteById(foodId); } @@ -119,7 +120,7 @@ public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { validateUser(userId); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); List foodList = foodRepository.findAllByUserIdAndDate(userId, date, sort); return calculateNutritionSumAndRatio(userId, foodList, date, 1); } @@ -129,7 +130,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDat public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); return calculateNutritionSumAndRatio(userId, foodList, endDate, 7); @@ -140,7 +141,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusMonths(1), endDate, sort); return calculateNutritionSumAndRatio(userId, foodList, endDate, 30); @@ -151,7 +152,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { public ResponseFoodRankDto getBestFoodByWeek(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); List top3Foods = foodList.stream() @@ -174,7 +175,7 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId) { public ResponseFoodRankDto getWorstFoodByWeek(Long userId) { validateUser(userId); LocalDate endDate = LocalDate.now(); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); List worst3Foods = foodList.stream() @@ -402,7 +403,7 @@ private void validateFavoriteFood(Long favoriteFoodId, Long userId) { // 1주일동안 먹은 음식들의 영양성분 총합을 요일을 Key로 한 Map을 통해 반환 private HashMap> getNutritionSumByDateMap(Long userId, LocalDate startDate, LocalDate endDate) { HashMap> maps = new HashMap<>(); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, endDate, sort); for (Food food : foodList) { if (maps.containsKey(food.getDate())) { diff --git a/src/main/java/com/diareat/diareat/util/MessageUtil.java b/src/main/java/com/diareat/diareat/util/MessageUtil.java index b9aca5e..aba71cd 100644 --- a/src/main/java/com/diareat/diareat/util/MessageUtil.java +++ b/src/main/java/com/diareat/diareat/util/MessageUtil.java @@ -20,4 +20,5 @@ public class MessageUtil { // 반복되는 메시지의 형식을 저장하고 public static final String FAT_RANGE = "지방은 25 이상, 500 이하의 값을 입력해주세요."; public static final String PAST_OR_PRESENT = "과거 또는 오늘 날짜여야 합니다."; + public static final String TIME_STAMP = "addedTime"; } From 9cc4ddbe59b7d14fd0c48c3463ac2d54860c14ec Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 12 Nov 2023 23:40:20 +0900 Subject: [PATCH 247/371] =?UTF-8?q?:ambulance:=20Fix:=20=EC=BD=94=EB=93=9C?= =?UTF-8?q?=20=EB=B3=80=EB=8F=99=EC=97=90=20=EB=94=B0=EB=A5=B8=20=ED=85=8C?= =?UTF-8?q?=EC=8A=A4=ED=8A=B8=EC=BD=94=EB=93=9C=20=EC=88=98=EC=A0=95=20?= =?UTF-8?q?=EB=B0=8F=20=EB=B6=88=ED=95=84=EC=9A=94=ED=95=9C=20import=20?= =?UTF-8?q?=EC=A0=95=EB=A6=AC=20(#84)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/FoodControllerTest.java | 19 +++++++++++++++++-- .../controller/UserControllerTest.java | 7 +++---- .../diareat/service/FoodServiceTest.java | 5 ++--- 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index a3f0096..d33e366 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -27,14 +27,13 @@ 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 { +class FoodControllerTest { @Autowired private MockMvc mockMvc; @@ -131,12 +130,20 @@ void testGetFoodListByDate() throws Exception { @WithMockUser("test") void testUpdateFood() throws Exception { //Given + int yy = 2023; + int dd = 22; + int mm = 12; + LocalDate date = LocalDate.of(yy, mm, dd); + 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") + .param("yy", String.valueOf(date.getYear())) + .param("mm", String.valueOf(date.getMonthValue())) + .param("dd", String.valueOf(date.getDayOfMonth())) .contentType(MediaType.APPLICATION_JSON) .content(json) .accept(MediaType.APPLICATION_JSON)) @@ -152,10 +159,18 @@ void testUpdateFood() throws Exception { @WithMockUser("test") void testDeleteFood() throws Exception { //Given + int yy = 2023; + int dd = 22; + int mm = 12; + LocalDate date = LocalDate.of(yy, mm, dd); + ApiResponse expectedResponse = ApiResponse.success(null, ResponseCode.FOOD_DELETE_SUCCESS.getMessage()); mockMvc.perform(MockMvcRequestBuilders .delete("/api/food/{foodId}/delete", testFoodId) + .param("yy", String.valueOf(date.getYear())) + .param("mm", String.valueOf(date.getMonthValue())) + .param("dd", String.valueOf(date.getDayOfMonth())) .header("userId", testUserId) .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) diff --git a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java index f595f80..d7ed8fd 100644 --- a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java @@ -59,7 +59,7 @@ class UserControllerTest { void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); testUser.setId(testUserId); - when(userService.getSimpleUserInfo(testUserId)).thenReturn(ResponseSimpleUserDto.of(testUser.getName(), testUser.getImage(), 100.0)); + when(userService.getSimpleUserInfo(testUserId)).thenReturn(ResponseSimpleUserDto.of(testUser.getName(), testUser.getImage())); when(userService.getUserInfo(testUserId)).thenReturn(ResponseUserDto.from(testUser)); } @@ -69,7 +69,7 @@ void setUp() { void testGetSimpleUserInfo() throws Exception { // Given ApiResponse expectedResponse = ApiResponse.success( - ResponseSimpleUserDto.of(testUser.getName(), testUser.getImage(), 100.0), ResponseCode.USER_CREATE_SUCCESS.getMessage()); + ResponseSimpleUserDto.of(testUser.getName(), testUser.getImage()), ResponseCode.USER_CREATE_SUCCESS.getMessage()); // When & Then mockMvc.perform( MockMvcRequestBuilders @@ -79,8 +79,7 @@ void testGetSimpleUserInfo() throws Exception { .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) .andExpect(MockMvcResultMatchers.jsonPath("$.data.name").value(expectedResponse.getData().getName())) - .andExpect(MockMvcResultMatchers.jsonPath("$.data.image").value(expectedResponse.getData().getImage())) - .andExpect(MockMvcResultMatchers.jsonPath("$.data.nutritionScore").value(expectedResponse.getData().getNutritionScore())); + .andExpect(MockMvcResultMatchers.jsonPath("$.data.image").value(expectedResponse.getData().getImage())); } @DisplayName("회원정보 조회") diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index f1a6d0d..febdcec 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -9,7 +9,6 @@ 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; @@ -92,7 +91,7 @@ void testUpdateFood() { //when BaseNutrition testChangedBaseNutrition = BaseNutrition.createNutrition(2,3,4,5); - foodService.updateFood(UpdateFoodDto.of(food.getId(), 1L,"testChangedFood", testChangedBaseNutrition)); + foodService.updateFood(UpdateFoodDto.of(food.getId(), 1L,"testChangedFood", testChangedBaseNutrition), LocalDate.of(2010, 1, 1)); assertEquals("testChangedFood", food.getName()); @@ -114,7 +113,7 @@ void testDeleteFood() { given(foodRepository.existsByIdAndUserId(food.getId(), 1L)).willReturn(true); //when - foodService.deleteFood(food.getId(), 1L); + foodService.deleteFood(food.getId(), 1L, LocalDate.of(2010, 1, 1)); verify(foodRepository, times(1)).deleteById(food.getId()); } From 854766cdd7ac1f40545fa861d370ccd0f6c05cda Mon Sep 17 00:00:00 2001 From: CHAE Date: Sun, 12 Nov 2023 23:41:39 +0900 Subject: [PATCH 248/371] =?UTF-8?q?:ambulance:=20Chore:=20user=20=ED=8C=A8?= =?UTF-8?q?=ED=82=A4=EC=A7=80=20ResponseDto=EC=97=90=20=EA=B8=B0=EB=B3=B8?= =?UTF-8?q?=EC=83=9D=EC=84=B1=EC=9E=90=20=EC=B6=94=EA=B0=80=20=EB=B0=8F=20?= =?UTF-8?q?=EB=B6=88=ED=95=84=EC=9A=94=ED=95=9C=20import=20=EC=A0=95?= =?UTF-8?q?=EB=A6=AC=20(#84)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/food/dto/ResponseAnalysisDto.java | 2 ++ .../diareat/diareat/food/dto/ResponseFavoriteFoodDto.java | 2 ++ .../com/diareat/diareat/food/dto/ResponseFoodRankDto.java | 5 ++--- .../diareat/diareat/food/dto/ResponseScoreBestWorstDto.java | 2 ++ .../com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java | 2 ++ 5 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java index 071206b..0d50559 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java @@ -2,10 +2,12 @@ import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; import java.util.List; @Getter +@NoArgsConstructor @AllArgsConstructor public class ResponseAnalysisDto { // 그래프 + 점수에 사용되는 DTO 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..5e4c41f 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java @@ -4,8 +4,10 @@ import com.diareat.diareat.user.domain.BaseNutrition; import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; @Getter +@NoArgsConstructor @AllArgsConstructor public class ResponseFavoriteFoodDto { 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 32101a3..d54b8d0 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java @@ -1,15 +1,14 @@ package com.diareat.diareat.food.dto; -import com.diareat.diareat.food.domain.Food; -import com.diareat.diareat.user.domain.BaseNutrition; import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; import java.time.LocalDate; -import java.time.LocalTime; import java.util.List; @Getter +@NoArgsConstructor @AllArgsConstructor public class ResponseFoodRankDto { diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java index 0e00c9d..7f12af0 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java @@ -2,10 +2,12 @@ import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; import java.util.List; @Getter +@NoArgsConstructor @AllArgsConstructor public class ResponseScoreBestWorstDto { // 일기 분석 자세히보기에 사용되는 DTO diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java index 7238afa..2160e67 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java @@ -3,10 +3,12 @@ import com.diareat.diareat.food.domain.Food; import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; import java.time.LocalDate; @Getter +@NoArgsConstructor @AllArgsConstructor public class ResponseSimpleFoodDto { // Best 3 and Worst 3에 사용될 객체 From 19bbb3ea63197e72edd83c933a6591f802a9966f Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 13 Nov 2023 05:25:47 +0000 Subject: [PATCH 249/371] :construction_worker: chore: Update deployment to ad81bcb9a0f135bae7c3f6f0ee68e5a60bbf2940 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 84c280f..114f34f 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 9b60352c + newTag: ad81bcb9 From bb886f22e2b9fbe4010182c363cd951bbc39b868 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 13 Nov 2023 19:33:06 +0900 Subject: [PATCH 250/371] =?UTF-8?q?:sparkles:=20feat:=20=EC=9D=8C=EC=8B=9D?= =?UTF-8?q?=20=EC=83=9D=EC=84=B1=EB=90=A0=20=EB=95=8C=20=EC=97=B0=EA=B2=B0?= =?UTF-8?q?=20=EC=83=9D=EC=84=B1=20(#86)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/domain/FavoriteFood.java | 3 ++- .../java/com/diareat/diareat/food/service/FoodService.java | 6 +++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java index 14138ce..ea5053a 100644 --- a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java +++ b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java @@ -37,9 +37,10 @@ public void addCount(){ } // 생성 메서드 - public static FavoriteFood createFavoriteFood(String name, User user, BaseNutrition baseNutrition) { + public static FavoriteFood createFavoriteFood(String name, User user, Food food, BaseNutrition baseNutrition) { FavoriteFood favoriteFood = new FavoriteFood(); favoriteFood.name = name; + favoriteFood.food = food; favoriteFood.user = user; favoriteFood.baseNutrition = baseNutrition; return favoriteFood; 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 f9e6baa..e6c25cd 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -80,10 +80,14 @@ public void deleteFood(Long foodId, Long userId, LocalDate date) { @CacheEvict(value = "ResponseFavoriteFoodDto", key = "#createFavoriteFoodDto.getUserId()", cacheManager = "diareatCacheManager") @Transactional public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { + validateFood(createFavoriteFoodDto.getFoodId(), createFavoriteFoodDto.getUserId()); User user = getUserById(createFavoriteFoodDto.getUserId()); + Food food = getFoodById(createFavoriteFoodDto.getFoodId()); + if (favoriteFoodRepository.existsByFoodId(createFavoriteFoodDto.getFoodId())) throw new FavoriteException(ResponseCode.FAVORITE_ALREADY_EXIST); - FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood(createFavoriteFoodDto.getName(), user, createFavoriteFoodDto.getBaseNutrition()); + + FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood(createFavoriteFoodDto.getName(), user, food, createFavoriteFoodDto.getBaseNutrition()); return favoriteFoodRepository.save(favoriteFood).getId(); } From 8ae45ad54ea96fbdad193cffe8a0915f0a02c17a Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 13 Nov 2023 19:33:25 +0900 Subject: [PATCH 251/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20?= =?UTF-8?q?=EB=B3=80=EA=B2=BD=EB=90=9C=20=EB=A9=94=EC=86=8C=EB=93=9C?= =?UTF-8?q?=EC=97=90=20=EB=A7=9E=EC=B6=B0=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20(#86)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/FoodControllerTest.java | 2 +- .../diareat/service/FoodServiceTest.java | 19 +++++++++++++------ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index d33e366..270d35c 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -51,7 +51,7 @@ class FoodControllerTest { 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), 2021, 10, 10); - private final FavoriteFood testFavoriteFood = FavoriteFood.createFavoriteFood("testFavoriteFood", testUser, BaseNutrition.createNutrition(500, 50, 30, 10)); + private final FavoriteFood testFavoriteFood = FavoriteFood.createFavoriteFood("testFavoriteFood", testUser, testFood, BaseNutrition.createNutrition(500, 50, 30, 10)); private final BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(500, 50, 30, 10); @BeforeEach diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index febdcec..df16cdf 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -122,23 +122,28 @@ void testDeleteFood() { void testSaveAndGetFavoriteFood() { BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); User user = User.createUser("testUser", "testImage","testPassword", 1,180, 80,18, testBaseNutrition); - FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("testFavoriteFood", user, testBaseNutrition); + Food food = Food.createFood("testFood", user, testBaseNutrition, 2010,1,1); + FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("testFavoriteFood", user,food, testBaseNutrition); user.setId(1L); + food.setId(2L); favoriteFood.setId(3L); - CreateFavoriteFoodDto createFavoriteFoodDto = CreateFavoriteFoodDto.of(favoriteFood.getId(), user.getId(),"testFood", testBaseNutrition); + CreateFavoriteFoodDto createFavoriteFoodDto = CreateFavoriteFoodDto.of(food.getId(), user.getId(),"testFood", testBaseNutrition); given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); given(userRepository.existsById(user.getId())).willReturn(true); + given(foodRepository.existsById(food.getId())).willReturn(true); + given(foodRepository.existsByIdAndUserId(food.getId(), user.getId())).willReturn(true); + given(foodRepository.findById(food.getId())).willReturn(Optional.of(food)); given(favoriteFoodRepository.save(any(FavoriteFood.class))).willReturn(favoriteFood); given(favoriteFoodRepository.findAllByUserId(any(Long.class))).willReturn(List.of(favoriteFood)); //when - Long foodId = foodService.saveFavoriteFood(createFavoriteFoodDto); + Long favoriteFoodId = foodService.saveFavoriteFood(createFavoriteFoodDto); List responseFavoriteFoodDtoList = foodService.getFavoriteFoodList(user.getId()); - assertEquals(3L, foodId); + assertEquals(3L, favoriteFoodId); assertEquals("testFavoriteFood",responseFavoriteFoodDtoList.get(0).getName()); verify(favoriteFoodRepository, times(1)).save(any(FavoriteFood.class)); } @@ -147,7 +152,8 @@ void testUpdateFavoriteFood() { //given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); User user = User.createUser("testUser", "testImage","tessPassword", 1, 180, 80, 18, testBaseNutrition); - FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("testFavoriteFood", user, testBaseNutrition); + Food food = Food.createFood("testFood", user, testBaseNutrition, 2010,1,1); + FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("testFavoriteFood", user, food,testBaseNutrition); favoriteFood.setId(1L); given(favoriteFoodRepository.findById(favoriteFood.getId())).willReturn(Optional.of(favoriteFood)); @@ -169,7 +175,8 @@ void testDeleteFavoriteFood() { //given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); User user = User.createUser("testUser", "testImage","tessPassword", 1, 180, 80, 18, testBaseNutrition); - FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("testFood", user, testBaseNutrition); + Food food = Food.createFood("testFood", user, testBaseNutrition, 2010,1,1); + FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("testFood", user, food, testBaseNutrition); favoriteFood.setId(1L); given(favoriteFoodRepository.existsById(favoriteFood.getId())).willReturn(true); From 737ee7ed5e3dfcfc414c3470aaa59ae00805304b Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 13 Nov 2023 10:36:41 +0000 Subject: [PATCH 252/371] :construction_worker: chore: Update deployment to 0b13c413b198b7175cdc4e79dd2c81a7224dc331 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 114f34f..348efeb 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: ad81bcb9 + newTag: 0b13c413 From 8719b0983fc0550189dd950ca02fd6ac7f7c6c5b Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 13 Nov 2023 19:53:11 +0900 Subject: [PATCH 253/371] =?UTF-8?q?:bug:=20fix:=20food=EC=99=80=20favorite?= =?UTF-8?q?food=EA=B0=84=20=EC=97=B0=EB=8F=99=20(#88)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/domain/FavoriteFood.java | 3 ++- src/main/java/com/diareat/diareat/food/domain/Food.java | 7 ++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java index ea5053a..a4db401 100644 --- a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java +++ b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java @@ -20,7 +20,7 @@ public class FavoriteFood { private String name; - @OneToOne(fetch = FetchType.LAZY, orphanRemoval = false) // 즐찾음식이 삭제되어도 음식은 삭제되지 않음 + @OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST}, orphanRemoval = false) // 즐찾음식이 삭제되어도 음식은 삭제되지 않음 @JoinColumn(name = "food_id") private Food food; @@ -43,6 +43,7 @@ public static FavoriteFood createFavoriteFood(String name, User user, Food food, favoriteFood.food = food; favoriteFood.user = user; favoriteFood.baseNutrition = baseNutrition; + food.setFavoriteFood(favoriteFood); return favoriteFood; } 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 a8166c6..78d7175 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -26,7 +26,7 @@ public class Food { @JoinColumn(name = "user_id") private User user; - @OneToOne(fetch = FetchType.LAZY, orphanRemoval = false) // 음식이 삭제되어도 즐찾음식은 삭제되지 않음 + @OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST}, orphanRemoval = false) // 음식이 삭제되어도 즐찾음식은 삭제되지 않음 @JoinColumn(name = "favorite_food_id") private FavoriteFood favoriteFood; @@ -45,6 +45,7 @@ public static Food createFood(String name, User user, BaseNutrition baseNutritio food.date = LocalDate.of(year, month, day); food.addedTime = LocalDateTime.now(); food.baseNutrition = baseNutrition; + return food; } @@ -61,4 +62,8 @@ public boolean isFavorite() { public void setId(long id) {this.id = id;} public void setDate(LocalDate date) {this.date = date;} //food test를 위한 date + + public void setFavoriteFood(FavoriteFood favoriteFood){ + this.favoriteFood = favoriteFood; + } } From 5d6066d21a962c1b0470ac75738893da8a360c0e Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 13 Nov 2023 10:55:58 +0000 Subject: [PATCH 254/371] :construction_worker: chore: Update deployment to 7a347adc0416639f36330988b20ae7ad21aa749c --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 348efeb..a640ba1 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 0b13c413 + newTag: 7a347adc From 6930736d79d767c81bae4808e2a2ac7810f7aa67 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 13 Nov 2023 20:46:38 +0900 Subject: [PATCH 255/371] =?UTF-8?q?:poop:=20chore:=20cache=20=EC=97=86?= =?UTF-8?q?=EC=95=A0=EB=B3=B4=EA=B8=B0=20(#90)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/food/service/FoodService.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 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 e6c25cd..da4426b 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -37,7 +37,6 @@ public class FoodService { private final UserRepository userRepository; // 촬영 후, 음식 정보 저장 - @CacheEvict(value = "ResponseFoodDto, ResponseNutritionSumByDateDto", key = "#createFoodDto.getUserId()+#createFoodDto.getDate().toString()", cacheManager = "diareatCacheManager") @Transactional public Long saveFood(CreateFoodDto createFoodDto) { if (foodRepository.existsByName(createFoodDto.getName())){ @@ -49,7 +48,6 @@ public Long saveFood(CreateFoodDto createFoodDto) { } // 회원이 특정 날짜에 먹은 음식 조회 - @Cacheable(value = "ResponseFoodDto", key = "#userId+#date.toString()", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) public List getFoodListByDate(Long userId, LocalDate date){ validateUser(userId); @@ -319,6 +317,12 @@ public List getUserRankByWeek(Long userId) { return rankUserDtos; } + @Transactional() + public Long createFoodFromFavoriteFood(Long favoriteFoodId) { + FavoriteFood favoriteFood = getFavoriteFoodById(favoriteFoodId); + Food food = FavoriteFood.createFoodFromFavoriteFood(favoriteFood); + return foodRepository.save(food).getId(); + } private User getUserById(Long userId) { return userRepository.findById(userId) From 0bbbf0a2e9a8d3a3bd682acdd60f7e5442603d5c Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 13 Nov 2023 11:49:51 +0000 Subject: [PATCH 256/371] :construction_worker: chore: Update deployment to 64b4868ce76f9e1f9f20170f1af359ab2d97c5a6 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index a640ba1..1c8f4dd 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 7a347adc + newTag: 64b4868c From 1c1d4e8102fda498abf217b7f953736e3e9879ea Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 13 Nov 2023 21:29:51 +0900 Subject: [PATCH 257/371] =?UTF-8?q?:ambulance:=20Fix:=20=EC=BA=90=EC=8B=B1?= =?UTF-8?q?=20value=20=EC=9D=BC=EB=B6=80=20=EC=88=98=EC=A0=95=20(#92)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/service/FoodService.java | 7 ++++--- 1 file changed, 4 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 da4426b..aca5f68 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -37,6 +37,7 @@ public class FoodService { private final UserRepository userRepository; // 촬영 후, 음식 정보 저장 + @CacheEvict(value = {"ResponseNutritionSumByDateDto"}, key = "#userId+date.toString()", cacheManager = "diareatCacheManager") @Transactional public Long saveFood(CreateFoodDto createFoodDto) { if (foodRepository.existsByName(createFoodDto.getName())){ @@ -47,7 +48,7 @@ public Long saveFood(CreateFoodDto createFoodDto) { return foodRepository.save(food).getId(); } - // 회원이 특정 날짜에 먹은 음식 조회 + // 회원이 특정 날짜에 먹은 음식 조회 -> 돌발적인 행동이 많아 캐시 일관성 유지의 가치가 낮아서 캐싱 배제 @Transactional(readOnly = true) public List getFoodListByDate(Long userId, LocalDate date){ validateUser(userId); @@ -58,7 +59,7 @@ public List getFoodListByDate(Long userId, LocalDate date){ } // 음식 정보 수정 - @CacheEvict(value = "ResponseFoodDto, ResponseNutritionSumByDateDto", key = "#updateFoodDto.getUserId()+date.toString()", cacheManager = "diareatCacheManager") + @CacheEvict(value = {"ResponseNutritionSumByDateDto"}, key = "#updateFoodDto.getUserId()+date.toString()", cacheManager = "diareatCacheManager") @Transactional public void updateFood(UpdateFoodDto updateFoodDto, LocalDate date) { Food food = getFoodById(updateFoodDto.getFoodId()); @@ -67,7 +68,7 @@ public void updateFood(UpdateFoodDto updateFoodDto, LocalDate date) { } // 음식 삭제 - @CacheEvict(value = "ResponseFoodDto, ResponseNutritionSumByDateDto", key = "#userId+date.toString()", cacheManager = "diareatCacheManager") + @CacheEvict(value = {"ResponseNutritionSumByDateDto"}, key = "#userId+date.toString()", cacheManager = "diareatCacheManager") @Transactional public void deleteFood(Long foodId, Long userId, LocalDate date) { validateFood(foodId, userId); From a1f2a125a9934a45bc7e1d3bd2ca403738942b6d Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 13 Nov 2023 21:32:54 +0900 Subject: [PATCH 258/371] =?UTF-8?q?:ambulance:=20Fix:=20createFoodDto=20ge?= =?UTF-8?q?tDate=20=EB=88=84=EB=9D=BD=EB=90=9C=20=EC=98=A4=EB=A5=98=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20(#92)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/food/service/FoodService.java | 2 +- 1 file changed, 1 insertion(+), 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 aca5f68..fd73eb2 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -37,7 +37,7 @@ public class FoodService { private final UserRepository userRepository; // 촬영 후, 음식 정보 저장 - @CacheEvict(value = {"ResponseNutritionSumByDateDto"}, key = "#userId+date.toString()", cacheManager = "diareatCacheManager") + @CacheEvict(value = {"ResponseNutritionSumByDateDto"}, key = "#userId+createFoodDto.getDate()", cacheManager = "diareatCacheManager") @Transactional public Long saveFood(CreateFoodDto createFoodDto) { if (foodRepository.existsByName(createFoodDto.getName())){ From 31243ad2ff59052017fc1288cae19f73832f664d Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 13 Nov 2023 13:30:28 +0000 Subject: [PATCH 259/371] :construction_worker: chore: Update deployment to d0534e672666a28b7b133fb55f9cf5e653430de3 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 1c8f4dd..a5595c9 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 64b4868c + newTag: d0534e67 From fbe2a7846cf4264248528219383efdcee02d5ba8 Mon Sep 17 00:00:00 2001 From: CHAE Date: Wed, 15 Nov 2023 00:23:48 +0900 Subject: [PATCH 260/371] =?UTF-8?q?:ambulance:=20Fix:=20=EC=98=A4=EB=8A=98?= =?UTF-8?q?=EC=9D=98=EC=98=81=EC=96=91=20key=20=EA=B3=B5=EB=B0=B1=20?= =?UTF-8?q?=EB=81=BC=EC=96=B4=EC=9E=88=EB=8A=94=20=EC=83=81=ED=99=A9=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20(#94)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/food/service/FoodService.java | 2 +- 1 file changed, 1 insertion(+), 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 fd73eb2..9addcce 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -118,7 +118,7 @@ public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { favoriteFoodRepository.deleteById(favoriteFoodId); } - @Cacheable(value = "ResponseNutritionSumByDateDto", key = "#userId + #date.toString()", cacheManager = "diareatCacheManager") + @Cacheable(value = "ResponseNutritionSumByDateDto", key = "#userId+#date.toString()", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { From f91ad5e9e303265122a54a9cead6d5207a691dee Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 14 Nov 2023 15:27:25 +0000 Subject: [PATCH 261/371] :construction_worker: chore: Update deployment to ac6989b0db5363009e0d44f7954cf565b163e302 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index a5595c9..bad682a 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: d0534e67 + newTag: ac6989b0 From 30d3ed4ac5e755dea149deea11d18e9b2dae2a1d Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 15 Nov 2023 02:25:11 +0900 Subject: [PATCH 262/371] =?UTF-8?q?:sparkles:=20feat:=20=EC=A6=90=EC=B0=BE?= =?UTF-8?q?=20=EC=9D=8C=EC=8B=9D=EC=9C=BC=EB=A1=9C=20=EC=9D=8C=EC=8B=9D=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1=20=EA=B5=AC=ED=98=84=20(#96)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/food/controller/FoodController.java | 6 ++++++ .../java/com/diareat/diareat/food/service/FoodService.java | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) 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 50863a2..6a78ed6 100644 --- a/src/main/java/com/diareat/diareat/food/controller/FoodController.java +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -140,4 +140,10 @@ public ApiResponse getAnalysisOfUser(@PathVariable Long use public ApiResponse> getUserRankByWeek(@PathVariable Long userId){ return ApiResponse.success(foodService.getUserRankByWeek(userId),ResponseCode.FOOD_RANK_READ_SUCCESS.getMessage()); } + + @Operation(summary = "[음식] 즐겨찾기 음식으로 음식 생성",description = "즐겨찾기 음식으로 음식을 생성합니다.") + @PostMapping("/{userId}/from/{favoriteFoodId}") + public ApiResponse createFoodFromFavoriteFood(@PathVariable Long userId, @PathVariable Long favoriteFoodId){ + return ApiResponse.success(foodService.createFoodFromFavoriteFood(userId, favoriteFoodId),ResponseCode.FOOD_CREATE_SUCCESS.getMessage()); + } } 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 9addcce..59f2f80 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -319,7 +319,8 @@ public List getUserRankByWeek(Long userId) { } @Transactional() - public Long createFoodFromFavoriteFood(Long favoriteFoodId) { + public Long createFoodFromFavoriteFood(Long userId, Long favoriteFoodId) { + validateFavoriteFood(userId, favoriteFoodId); FavoriteFood favoriteFood = getFavoriteFoodById(favoriteFoodId); Food food = FavoriteFood.createFoodFromFavoriteFood(favoriteFood); return foodRepository.save(food).getId(); From 7b33ec4ab6bb411c6a7fe170df3050cfa4b9c758 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 15 Nov 2023 02:53:21 +0900 Subject: [PATCH 263/371] =?UTF-8?q?:sparkles:=20feat:=20=EC=A6=90=EC=B0=BE?= =?UTF-8?q?=20=EC=9D=8C=EC=8B=9D=EC=9C=BC=EB=A1=9C=EB=B6=80=ED=84=B0=20?= =?UTF-8?q?=EC=9D=8C=EC=8B=9D=20=EC=83=9D=EC=84=B1=20=EC=9C=84=ED=95=9C=20?= =?UTF-8?q?dto=20=EC=B6=94=EA=B0=80=20(#96)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dto/CreateFoodFromFavoriteFoodDto.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 src/main/java/com/diareat/diareat/food/dto/CreateFoodFromFavoriteFoodDto.java diff --git a/src/main/java/com/diareat/diareat/food/dto/CreateFoodFromFavoriteFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/CreateFoodFromFavoriteFoodDto.java new file mode 100644 index 0000000..28011b9 --- /dev/null +++ b/src/main/java/com/diareat/diareat/food/dto/CreateFoodFromFavoriteFoodDto.java @@ -0,0 +1,23 @@ +package com.diareat.diareat.food.dto; + +import com.diareat.diareat.util.MessageUtil; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotNull; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class CreateFoodFromFavoriteFoodDto { + @NotNull(message = MessageUtil.NOT_NULL) + private Long userId; + + @NotNull(message = MessageUtil.NOT_NULL) + private Long favoriteFoodId; + + public static CreateFoodFromFavoriteFoodDto of(Long userId, Long favoriteFoodId) { + return new CreateFoodFromFavoriteFoodDto(userId, favoriteFoodId); + } +} From e08d1698b3e6d3647bc532e3c106cecd0806f7d7 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 15 Nov 2023 02:53:42 +0900 Subject: [PATCH 264/371] =?UTF-8?q?:sparkles:=20feat:=20=EC=A6=90=EC=B0=BE?= =?UTF-8?q?=20=EC=9D=8C=EC=8B=9D=EC=9C=BC=EB=A1=9C=EB=B6=80=ED=84=B0=20?= =?UTF-8?q?=EC=9D=8C=EC=8B=9D=20=EC=83=9D=EC=84=B1=20=EB=A9=94=EC=86=8C?= =?UTF-8?q?=EB=93=9C=20=EA=B5=AC=ED=98=84=20(#96)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/food/controller/FoodController.java | 6 +++--- .../java/com/diareat/diareat/food/service/FoodService.java | 6 +++--- 2 files changed, 6 insertions(+), 6 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 6a78ed6..bc13c50 100644 --- a/src/main/java/com/diareat/diareat/food/controller/FoodController.java +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -142,8 +142,8 @@ public ApiResponse> getUserRankByWeek(@PathVariable Lo } @Operation(summary = "[음식] 즐겨찾기 음식으로 음식 생성",description = "즐겨찾기 음식으로 음식을 생성합니다.") - @PostMapping("/{userId}/from/{favoriteFoodId}") - public ApiResponse createFoodFromFavoriteFood(@PathVariable Long userId, @PathVariable Long favoriteFoodId){ - return ApiResponse.success(foodService.createFoodFromFavoriteFood(userId, favoriteFoodId),ResponseCode.FOOD_CREATE_SUCCESS.getMessage()); + @PostMapping("/favorite/createfrom") + public ApiResponse createFoodFromFavoriteFood(@RequestBody @Valid CreateFoodFromFavoriteFoodDto createFoodFromFavoriteFoodDto){ + return ApiResponse.success(foodService.createFoodFromFavoriteFood(createFoodFromFavoriteFoodDto),ResponseCode.FOOD_CREATE_SUCCESS.getMessage()); } } 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 59f2f80..95509b8 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -319,9 +319,9 @@ public List getUserRankByWeek(Long userId) { } @Transactional() - public Long createFoodFromFavoriteFood(Long userId, Long favoriteFoodId) { - validateFavoriteFood(userId, favoriteFoodId); - FavoriteFood favoriteFood = getFavoriteFoodById(favoriteFoodId); + public Long createFoodFromFavoriteFood(CreateFoodFromFavoriteFoodDto createFoodFromFavoriteFoodDto) { + validateFavoriteFood(createFoodFromFavoriteFoodDto.getFavoriteFoodId(), createFoodFromFavoriteFoodDto.getUserId()); + FavoriteFood favoriteFood = getFavoriteFoodById(createFoodFromFavoriteFoodDto.getFavoriteFoodId()); Food food = FavoriteFood.createFoodFromFavoriteFood(favoriteFood); return foodRepository.save(food).getId(); } From 6f111596e729fc9ea2ec52e098e2c3ab689a6639 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 15 Nov 2023 02:54:03 +0900 Subject: [PATCH 265/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20?= =?UTF-8?q?=EC=9D=8C=EC=8B=9D=20=EC=83=9D=EC=84=B1=20=EB=A9=94=EC=86=8C?= =?UTF-8?q?=EB=93=9C=20=EA=B5=AC=ED=98=84=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=EC=BD=94=EB=93=9C=20=EC=9E=91=EC=84=B1=20(#96)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/FoodControllerTest.java | 25 +++++++++++++++++ .../diareat/service/FoodServiceTest.java | 27 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index 270d35c..1110177 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -466,4 +466,29 @@ void testGetUserRankByWeek() throws Exception{ .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].proteinScore").value(expectedResponse.getData().get(0).getProteinScore())) .andExpect(MockMvcResultMatchers.jsonPath("$.data[0].fatScore").value(expectedResponse.getData().get(0).getFatScore())); } + + @DisplayName("즐겨찾기 음식으로 음식 생성") + @Test + @WithMockUser("test") + void testCreateFoodFromFavoriteFood() throws Exception{ + //Given + Long testNewFoodId = 1L; + CreateFoodFromFavoriteFoodDto createFoodFromFavoriteFoodDto = CreateFoodFromFavoriteFoodDto.of(testUserId, testFavoriteFoodId); + when(foodService.createFoodFromFavoriteFood(any(CreateFoodFromFavoriteFoodDto.class))).thenReturn(testNewFoodId); + ApiResponse expectedResponse = ApiResponse.success(foodService.createFoodFromFavoriteFood(createFoodFromFavoriteFoodDto), ResponseCode.FOOD_CREATE_SUCCESS.getMessage()); + String json = mapper.writeValueAsString(createFoodFromFavoriteFoodDto); + + + //When + mockMvc.perform(MockMvcRequestBuilders + .post("/api/food/favorite/createfrom") + .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())); + } } diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index df16cdf..28741e3 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -493,4 +493,31 @@ void testGetAnalysisOfUser(){ verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now(),sort); } + + @Test + void testCreateFoodFromFavoriteFood() { + // given + User user = User.createUser("testUser", "testImage","testPassword", 1, 180, 80, 18, BaseNutrition.createNutrition(2000,400,100,50)); + Food food = Food.createFood( "Food", user, BaseNutrition.createNutrition(100, 100 ,10, 1), 2010,1,1); + FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("FavoriteFood", user, food, BaseNutrition.createNutrition(100, 100 ,10, 1)); + Food newFood = Food.createFood("FoodFromFavorite", user, BaseNutrition.createNutrition(100, 100 ,10, 1), 2010,1,1); + user.setId(1L); + food.setId(2L); + favoriteFood.setId(3L); + newFood.setId(4L); + CreateFoodFromFavoriteFoodDto createFoodFromFavoriteFoodDto = CreateFoodFromFavoriteFoodDto.of(user.getId(), favoriteFood.getId()); + + + given(favoriteFoodRepository.existsById(favoriteFood.getId())).willReturn(true); + given(favoriteFoodRepository.existsByIdAndUserId(favoriteFood.getId(),user.getId())).willReturn(true); + given(favoriteFoodRepository.findById(favoriteFood.getId())).willReturn(Optional.of(favoriteFood)); + given(foodRepository.save(any(Food.class))).willReturn(newFood); + + // when + Long foodId = foodService.createFoodFromFavoriteFood(createFoodFromFavoriteFoodDto); + + // then + assertEquals(4L, foodId); + verify(foodRepository, times(1)).save(any(Food.class)); + } } From f655b43e0d8427391a44c27d680b8fb99fbf58eb Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 15 Nov 2023 13:14:09 +0900 Subject: [PATCH 266/371] =?UTF-8?q?:sparkles:=20feat:=20favoriteFood?= =?UTF-8?q?=EC=99=80=20Food=20=EC=97=B0=EA=B4=80=EA=B4=80=EA=B3=84=20?= =?UTF-8?q?=EC=84=A4=EC=A0=95=20(#96)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/food/service/FoodService.java | 1 + 1 file changed, 1 insertion(+) 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 95509b8..8987fee 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -323,6 +323,7 @@ public Long createFoodFromFavoriteFood(CreateFoodFromFavoriteFoodDto createFoodF validateFavoriteFood(createFoodFromFavoriteFoodDto.getFavoriteFoodId(), createFoodFromFavoriteFoodDto.getUserId()); FavoriteFood favoriteFood = getFavoriteFoodById(createFoodFromFavoriteFoodDto.getFavoriteFoodId()); Food food = FavoriteFood.createFoodFromFavoriteFood(favoriteFood); + food.setFavoriteFood(favoriteFood); return foodRepository.save(food).getId(); } From 0f021d8da16387797a13b5b652d8a2847170d679 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 15 Nov 2023 04:17:18 +0000 Subject: [PATCH 267/371] :construction_worker: chore: Update deployment to d227a3cdaead41141fdf5a58d0cb8478218e7058 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index bad682a..4291271 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: ac6989b0 + newTag: d227a3cd From 562720be2b9a87f8642352a4e49f8dd86687712d Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 16 Nov 2023 17:02:29 +0900 Subject: [PATCH 268/371] =?UTF-8?q?:ambulance:=20Fix:=20user=20=ED=8C=A8?= =?UTF-8?q?=ED=82=A4=EC=A7=80=20ResponseDto=EC=97=90=20=EA=B8=B0=EB=B3=B8?= =?UTF-8?q?=EC=83=9D=EC=84=B1=EC=9E=90=20=EC=B6=94=EA=B0=80=20(#98)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/user/dto/response/ResponseRankUserDto.java | 2 ++ .../diareat/user/dto/response/ResponseSearchUserDto.java | 2 ++ .../diareat/user/dto/response/ResponseSimpleUserDto.java | 2 ++ .../com/diareat/diareat/user/dto/response/ResponseUserDto.java | 2 ++ .../diareat/user/dto/response/ResponseUserNutritionDto.java | 2 ++ 5 files changed, 10 insertions(+) diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java index 5e1829d..5edd03c 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java @@ -2,8 +2,10 @@ import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; @Getter +@NoArgsConstructor @AllArgsConstructor public class ResponseRankUserDto { diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java index 247e548..d760e2f 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java @@ -2,8 +2,10 @@ import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; @Getter +@NoArgsConstructor @AllArgsConstructor public class ResponseSearchUserDto { diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java index 5a707ef..b38eb28 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java @@ -2,8 +2,10 @@ import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; @Getter +@NoArgsConstructor @AllArgsConstructor public class ResponseSimpleUserDto { diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java index 495c975..0534a7d 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java @@ -3,8 +3,10 @@ import com.diareat.diareat.user.domain.User; import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; @Getter +@NoArgsConstructor @AllArgsConstructor public class ResponseUserDto { diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java index 1fece0d..fc0edcf 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java @@ -3,8 +3,10 @@ import com.diareat.diareat.user.domain.User; import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; @Getter +@NoArgsConstructor @AllArgsConstructor public class ResponseUserNutritionDto { From c15b5e88be0b2d8ccdb658155621a666545c822e Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 16 Nov 2023 18:42:00 +0900 Subject: [PATCH 269/371] =?UTF-8?q?:ambulance:=20Fix:=20user=20=ED=8C=A8?= =?UTF-8?q?=ED=82=A4=EC=A7=80=20ResponseDto=EC=97=90=20Serialize=20?= =?UTF-8?q?=EC=96=B4=EB=85=B8=ED=85=8C=EC=9D=B4=EC=85=98=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20(#98)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/dto/response/ResponseRankUserDto.java | 8 +++++++- .../diareat/user/dto/response/ResponseSearchUserDto.java | 8 +++++++- .../diareat/user/dto/response/ResponseSimpleUserDto.java | 8 +++++++- .../diareat/user/dto/response/ResponseUserDto.java | 8 +++++++- .../user/dto/response/ResponseUserNutritionDto.java | 8 +++++++- 5 files changed, 35 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java index 5edd03c..cc657a4 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java @@ -1,13 +1,19 @@ package com.diareat.diareat.user.dto.response; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import java.io.Serializable; + @Getter @NoArgsConstructor @AllArgsConstructor -public class ResponseRankUserDto { +@JsonSerialize +@JsonDeserialize +public class ResponseRankUserDto implements Serializable { private Long userId; private String name; diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java index d760e2f..919c27b 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java @@ -1,13 +1,19 @@ package com.diareat.diareat.user.dto.response; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import java.io.Serializable; + @Getter @NoArgsConstructor @AllArgsConstructor -public class ResponseSearchUserDto { +@JsonSerialize +@JsonDeserialize +public class ResponseSearchUserDto implements Serializable { private Long userId; private String name; diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java index b38eb28..d550575 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java @@ -1,13 +1,19 @@ package com.diareat.diareat.user.dto.response; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import java.io.Serializable; + @Getter @NoArgsConstructor @AllArgsConstructor -public class ResponseSimpleUserDto { +@JsonSerialize +@JsonDeserialize +public class ResponseSimpleUserDto implements Serializable { private String name; private String image; diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java index 0534a7d..2625df2 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java @@ -1,14 +1,20 @@ package com.diareat.diareat.user.dto.response; import com.diareat.diareat.user.domain.User; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import java.io.Serializable; + @Getter @NoArgsConstructor @AllArgsConstructor -public class ResponseUserDto { +@JsonSerialize +@JsonDeserialize +public class ResponseUserDto implements Serializable { private String name; private int height; diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java index fc0edcf..6661313 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java @@ -1,14 +1,20 @@ package com.diareat.diareat.user.dto.response; import com.diareat.diareat.user.domain.User; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import java.io.Serializable; + @Getter @NoArgsConstructor @AllArgsConstructor -public class ResponseUserNutritionDto { +@JsonSerialize +@JsonDeserialize +public class ResponseUserNutritionDto implements Serializable { private int calorie; // 유저가 설정한(할 수 있는) 현재 영양소 기준섭취량 private int carbohydrate; From 231c431c5d25a7cb51b38dda364423682101798d Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 16 Nov 2023 20:16:20 +0900 Subject: [PATCH 270/371] =?UTF-8?q?:ambulance:=20Fix:=20Service=20?= =?UTF-8?q?=EA=B3=84=EC=B8=B5=20=EC=BA=90=EC=8B=B1=20=EC=A4=91=EB=8B=A8=20?= =?UTF-8?q?(#98)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 20 +++++++++---------- .../diareat/user/service/UserService.java | 12 +++++------ 2 files changed, 16 insertions(+), 16 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 8987fee..7ef1038 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -37,7 +37,7 @@ public class FoodService { private final UserRepository userRepository; // 촬영 후, 음식 정보 저장 - @CacheEvict(value = {"ResponseNutritionSumByDateDto"}, key = "#userId+createFoodDto.getDate()", cacheManager = "diareatCacheManager") + // @CacheEvict(value = {"ResponseNutritionSumByDateDto"}, key = "#userId+createFoodDto.getDate()", cacheManager = "diareatCacheManager") @Transactional public Long saveFood(CreateFoodDto createFoodDto) { if (foodRepository.existsByName(createFoodDto.getName())){ @@ -59,7 +59,7 @@ public List getFoodListByDate(Long userId, LocalDate date){ } // 음식 정보 수정 - @CacheEvict(value = {"ResponseNutritionSumByDateDto"}, key = "#updateFoodDto.getUserId()+date.toString()", cacheManager = "diareatCacheManager") + // @CacheEvict(value = {"ResponseNutritionSumByDateDto"}, key = "#updateFoodDto.getUserId()+date.toString()", cacheManager = "diareatCacheManager") @Transactional public void updateFood(UpdateFoodDto updateFoodDto, LocalDate date) { Food food = getFoodById(updateFoodDto.getFoodId()); @@ -68,7 +68,7 @@ public void updateFood(UpdateFoodDto updateFoodDto, LocalDate date) { } // 음식 삭제 - @CacheEvict(value = {"ResponseNutritionSumByDateDto"}, key = "#userId+date.toString()", cacheManager = "diareatCacheManager") + // @CacheEvict(value = {"ResponseNutritionSumByDateDto"}, key = "#userId+date.toString()", cacheManager = "diareatCacheManager") @Transactional public void deleteFood(Long foodId, Long userId, LocalDate date) { validateFood(foodId, userId); @@ -76,7 +76,7 @@ public void deleteFood(Long foodId, Long userId, LocalDate date) { } // 즐겨찾기에 음식 저장 - @CacheEvict(value = "ResponseFavoriteFoodDto", key = "#createFavoriteFoodDto.getUserId()", cacheManager = "diareatCacheManager") + // @CacheEvict(value = "ResponseFavoriteFoodDto", key = "#createFavoriteFoodDto.getUserId()", cacheManager = "diareatCacheManager") @Transactional public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { validateFood(createFavoriteFoodDto.getFoodId(), createFavoriteFoodDto.getUserId()); @@ -91,7 +91,7 @@ public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { } //즐겨찾기 음식 리스트 반환 - @Cacheable(value = "ResponseFavoriteFoodDto", key = "#userId", cacheManager = "diareatCacheManager") + // @Cacheable(value = "ResponseFavoriteFoodDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) public List getFavoriteFoodList(Long userId){ validateUser(userId); @@ -102,7 +102,7 @@ public List getFavoriteFoodList(Long userId){ } // 즐겨찾기 음식 수정 - @CacheEvict(value = "ResponseFavoriteFoodDto", key = "updateFavoriteFoodDto.getUserId()", cacheManager = "diareatCacheManager") + // @CacheEvict(value = "ResponseFavoriteFoodDto", key = "updateFavoriteFoodDto.getUserId()", cacheManager = "diareatCacheManager") @Transactional public void updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto) { FavoriteFood food = getFavoriteFoodById(updateFavoriteFoodDto.getFavoriteFoodId()); @@ -111,14 +111,14 @@ public void updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto) { } // 즐겨찾기 해제 - @CacheEvict(value = "ResponseFavoriteFoodDto", key = "#userId", cacheManager = "diareatCacheManager") + // @CacheEvict(value = "ResponseFavoriteFoodDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { validateFavoriteFood(favoriteFoodId, userId); favoriteFoodRepository.deleteById(favoriteFoodId); } - @Cacheable(value = "ResponseNutritionSumByDateDto", key = "#userId+#date.toString()", cacheManager = "diareatCacheManager") + // @Cacheable(value = "ResponseNutritionSumByDateDto", key = "#userId+#date.toString()", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { @@ -296,7 +296,7 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId){ - @Cacheable(value = "ResponseRankUserDto", key = "#userId", cacheManager = "diareatCacheManager") + // @Cacheable(value = "ResponseRankUserDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) // 유저의 식습관 점수를 기반으로 한 주간 랭킹 조회 public List getUserRankByWeek(Long userId) { @@ -318,7 +318,7 @@ public List getUserRankByWeek(Long userId) { return rankUserDtos; } - @Transactional() + @Transactional public Long createFoodFromFavoriteFood(CreateFoodFromFavoriteFoodDto createFoodFromFavoriteFoodDto) { validateFavoriteFood(createFoodFromFavoriteFoodDto.getFavoriteFoodId(), createFoodFromFavoriteFoodDto.getUserId()); FavoriteFood favoriteFood = getFavoriteFoodById(createFoodFromFavoriteFoodDto.getFavoriteFoodId()); diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index da3f1ac..46aa5d7 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -48,7 +48,7 @@ public Long saveUser(CreateUserDto createUserDto) { } // 회원 기본정보 조회 - @Cacheable(value = "ResponseSimpleUserDto", key = "#userId", cacheManager = "diareatCacheManager") + // @Cacheable(value = "ResponseSimpleUserDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) public ResponseSimpleUserDto getSimpleUserInfo(Long userId) { User user = getUserById(userId); @@ -56,7 +56,7 @@ public ResponseSimpleUserDto getSimpleUserInfo(Long userId) { } // 회원정보 조회 - @Cacheable(value = "ResponseUserDto", key = "#userId", cacheManager = "diareatCacheManager") + // @Cacheable(value = "ResponseUserDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) public ResponseUserDto getUserInfo(Long userId) { User user = getUserById(userId); @@ -64,7 +64,7 @@ public ResponseUserDto getUserInfo(Long userId) { } // 회원정보 수정 - @CacheEvict(value = {"ResponseSimpleUserDto", "ResponseUserDto"}, key = "#updateUserDto.getUserId()", cacheManager = "diareatCacheManager") + // @CacheEvict(value = {"ResponseSimpleUserDto", "ResponseUserDto"}, key = "#updateUserDto.getUserId()", cacheManager = "diareatCacheManager") @Transactional public void updateUserInfo(UpdateUserDto updateUserDto) { User user = getUserById(updateUserDto.getUserId()); @@ -73,7 +73,7 @@ public void updateUserInfo(UpdateUserDto updateUserDto) { } // 회원 기준섭취량 조회 - @Cacheable(value = "ResponseUserNutritionDto", key = "#userId", cacheManager = "diareatCacheManager") + // @Cacheable(value = "ResponseUserNutritionDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) public ResponseUserNutritionDto getUserNutrition(Long userId) { User user = getUserById(userId); @@ -82,7 +82,7 @@ public ResponseUserNutritionDto getUserNutrition(Long userId) { } // 회원 기준섭취량 직접 수정 - @CacheEvict(value = "ResponseUserNutritionDto", key = "#updateUserNutritionDto.getUserId()", cacheManager = "diareatCacheManager") + // @CacheEvict(value = "ResponseUserNutritionDto", key = "#updateUserNutritionDto.getUserId()", cacheManager = "diareatCacheManager") @Transactional public void updateBaseNutrition(UpdateUserNutritionDto updateUserNutritionDto) { User user = getUserById(updateUserNutritionDto.getUserId()); @@ -92,7 +92,7 @@ public void updateBaseNutrition(UpdateUserNutritionDto updateUserNutritionDto) { } // 회원 탈퇴 - @CacheEvict(value = {"ResponseSimpleUserDto", "ResponseUserDto", "ResponseUserNutritionDto"}, key = "#userId", cacheManager = "diareatCacheManager") + // @CacheEvict(value = {"ResponseSimpleUserDto", "ResponseUserDto", "ResponseUserNutritionDto"}, key = "#userId", cacheManager = "diareatCacheManager") @Transactional public void deleteUser(Long userId) { validateUser(userId); From 2997000feb8d29999900a477c2eec5b38c22928f Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 16 Nov 2023 21:20:50 +0900 Subject: [PATCH 271/371] =?UTF-8?q?:bug:=20fix:=20=ED=98=84=EC=9E=AC=20?= =?UTF-8?q?=EC=8B=9C=EA=B0=84=20=EC=9D=98=EC=A1=B4=EC=84=B1=20=EC=82=AD?= =?UTF-8?q?=EC=A0=9C=20(#102)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 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 7ef1038..61d5c58 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -130,9 +130,9 @@ public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDat @Transactional(readOnly = true) // 유저의 최근 7일간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) - public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { + public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId, int year, int month, int day) { validateUser(userId); - LocalDate endDate = LocalDate.now(); + LocalDate endDate = LocalDate.of(year, month, day); Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); @@ -141,9 +141,9 @@ public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId) { @Transactional(readOnly = true) // 유저의 최근 1개월간의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) - public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { + public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId, int year, int month, int day) { validateUser(userId); - LocalDate endDate = LocalDate.now(); + LocalDate endDate = LocalDate.of(year, month, day); Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusMonths(1), endDate, sort); @@ -152,9 +152,9 @@ public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId) { @Transactional(readOnly = true) // 유저의 최근 7일간의 Best 3 음식 조회 (dto 구체적 협의 필요) - public ResponseFoodRankDto getBestFoodByWeek(Long userId) { + public ResponseFoodRankDto getBestFoodByWeek(Long userId, int year, int month, int day) { validateUser(userId); - LocalDate endDate = LocalDate.now(); + LocalDate endDate = LocalDate.of(year, month, day); Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); @@ -175,9 +175,9 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId) { @Transactional(readOnly = true) // 유저의 최근 7일간의 Worst 3 음식 조회 (dto 구체적 협의 필요) - public ResponseFoodRankDto getWorstFoodByWeek(Long userId) { + public ResponseFoodRankDto getWorstFoodByWeek(Long userId, int year, int month, int day) { validateUser(userId); - LocalDate endDate = LocalDate.now(); + LocalDate endDate = LocalDate.of(year, month, day); Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); @@ -202,7 +202,7 @@ public ResponseFoodRankDto getWorstFoodByWeek(Long userId) { //유저의 식습관 점수 및 Best 3와 Worst 3 계산 @Transactional(readOnly = true) - public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId){ + public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId, int year, int month, int day){ validateUser(userId); //유저 객체 검증 double totalScore = 0.0; double kcalScore = 0.0; @@ -212,7 +212,7 @@ public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId User targetUser = userRepository.getReferenceById(userId); //검증된 id로 유저 객체 불러오기 - ResponseRankUserDto scoresOfUser = calculateUserScoreThisWeek(targetUser, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()); + ResponseRankUserDto scoresOfUser = calculateUserScoreThisWeek(targetUser, LocalDate.of(year, month, day).with(DayOfWeek.MONDAY), LocalDate.of(year, month, day)); totalScore = Math.round((scoresOfUser.getTotalScore() * 100.0))/ 100.0; kcalScore = Math.round((scoresOfUser.getCalorieScore() * 100.0)) / 100.0; @@ -222,8 +222,8 @@ public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId //Dto의 형식에 맞게 Best3와 Worst3 음식 계산 - List simpleBestFoodList = getBestFoodByWeek(userId).getRankFoodList(); - List simpleWorstFoodList = getWorstFoodByWeek(userId).getRankFoodList(); + List simpleBestFoodList = getBestFoodByWeek(userId, year, month, day).getRankFoodList(); + List simpleWorstFoodList = getWorstFoodByWeek(userId, year, month, day).getRankFoodList(); return ResponseScoreBestWorstDto.of(kcalScore, carbohydrateScore, proteinScore, fatScore, totalScore, simpleBestFoodList, simpleWorstFoodList); } @@ -232,15 +232,15 @@ public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId // 유저의 일기 분석 그래프 데이터 및 식습관 totalScore 조회 @Transactional(readOnly = true) - public ResponseAnalysisDto getAnalysisOfUser(Long userId){ + public ResponseAnalysisDto getAnalysisOfUser(Long userId, int year, int month, int day){ 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().minusWeeks(3).with(DayOfWeek.MONDAY), LocalDate.now()); + HashMap> nutritionSumOfUserByWeek = getNutritionSumByDateMap(userId, LocalDate.of(year,month,day).minusWeeks(1), LocalDate.of(year, month, day)); + HashMap> nutritionSumOfUserByMonth = getNutritionSumByDateMap(userId, LocalDate.of(year,month,day).minusWeeks(3).with(DayOfWeek.MONDAY), LocalDate.of(year, month ,day)); - double totalWeekScore = calculateUserScoreThisWeek(user, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()).getTotalScore(); + double totalWeekScore = calculateUserScoreThisWeek(user, LocalDate.of(year, month, day).with(DayOfWeek.MONDAY), LocalDate.of(year, month, day)).getTotalScore(); //날짜 기준으로 정렬 (가장 최근 날짜가 맨 앞으로 오도록) @@ -299,17 +299,17 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId){ // @Cacheable(value = "ResponseRankUserDto", key = "#userId", cacheManager = "diareatCacheManager") @Transactional(readOnly = true) // 유저의 식습관 점수를 기반으로 한 주간 랭킹 조회 - public List getUserRankByWeek(Long userId) { + public List getUserRankByWeek(Long userId, int year, int month, int day) { List rankUserDtos = new ArrayList<>(); List users = followRepository.findAllByFromUser(userId); // 유저의 팔로우 유저 명단 - rankUserDtos.add(calculateUserScoreThisWeek(getUserById(userId), LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now())); + rankUserDtos.add(calculateUserScoreThisWeek(getUserById(userId), LocalDate.of(year, month, day).with(DayOfWeek.MONDAY), LocalDate.of(year, month ,day))); if (users.isEmpty()) { // 팔로우한 유저가 없는 경우 본인의 점수 및 정보만 반환함 return rankUserDtos; } // 팔로우한 유저들의 점수를 계산하여 rankUserDtos에 추가 for (User user : users) { - ResponseRankUserDto userDto = calculateUserScoreThisWeek(user, LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now()); + ResponseRankUserDto userDto = calculateUserScoreThisWeek(user, LocalDate.of(year, month, day).with(DayOfWeek.MONDAY), LocalDate.of(year, month, day)); rankUserDtos.add(userDto); } From 999c70b66a862a6bdd40539ecf3cce8c11bf157d Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 16 Nov 2023 21:22:51 +0900 Subject: [PATCH 272/371] =?UTF-8?q?:recycle:=20refactor:=20api=20=ED=8C=8C?= =?UTF-8?q?=EB=9D=BC=EB=AF=B8=ED=84=B0=20=EB=B6=80=EB=B6=84=20yy,=20mm,=20?= =?UTF-8?q?dd=20=EC=B6=94=EA=B0=80=20(#102)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../food/controller/FoodController.java | 36 +++++++++++++------ 1 file changed, 26 insertions(+), 10 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 bc13c50..2d36b9e 100644 --- a/src/main/java/com/diareat/diareat/food/controller/FoodController.java +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -108,37 +108,53 @@ public ApiResponse getNutritionSumByDate(@PathVar //"" 7일간 총합 조회 @Operation(summary = "[음식] 최근 7일간 먹은 음식들의 영양성분 총합 조회",description = "최근 7일 간 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") @GetMapping("/{userId}/nutrition/recentWeek") - public ApiResponse getNutritionSumByWeek(@PathVariable Long userId){ - return ApiResponse.success(foodService.getNutritionSumByWeek(userId),ResponseCode.FOOD_READ_SUCCESS.getMessage()); + public ApiResponse getNutritionSumByWeek(@PathVariable Long userId, + @RequestParam int yy, + @RequestParam int mm, + @RequestParam int dd){ + return ApiResponse.success(foodService.getNutritionSumByWeek(userId, yy, mm, dd),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_READ_SUCCESS.getMessage()); + public ApiResponse getNutritionSumByMonth(@PathVariable Long userId, + @RequestParam int yy, + @RequestParam int mm, + @RequestParam int dd){ + return ApiResponse.success(foodService.getNutritionSumByMonth(userId, yy, mm, dd),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()); + public ApiResponse getScoreOfUserWithBestAndWorstFoods(@PathVariable Long userId, + @RequestParam int yy, + @RequestParam int mm, + @RequestParam int dd + ){ + return ApiResponse.success(foodService.getScoreOfUserWithBestAndWorstFoods(userId, yy, mm, dd),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()); + public ApiResponse getAnalysisOfUser(@PathVariable Long userId, + @RequestParam int yy, + @RequestParam int mm, + @RequestParam int dd){ + return ApiResponse.success(foodService.getAnalysisOfUser(userId, yy, mm, dd),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()); + public ApiResponse> getUserRankByWeek(@PathVariable Long userId, + @RequestParam int yy, + @RequestParam int mm, + @RequestParam int dd){ + return ApiResponse.success(foodService.getUserRankByWeek(userId, yy, mm, dd),ResponseCode.FOOD_RANK_READ_SUCCESS.getMessage()); } @Operation(summary = "[음식] 즐겨찾기 음식으로 음식 생성",description = "즐겨찾기 음식으로 음식을 생성합니다.") From da35321de7bc396cd0268dc358d19a702584d827 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 16 Nov 2023 22:42:08 +0900 Subject: [PATCH 273/371] =?UTF-8?q?:recycle:=20refactor:=20LocalDate.now()?= =?UTF-8?q?=20=EC=82=AD=EC=A0=9C=EC=97=90=20=EB=94=B0=EB=A5=B8=20=EC=9D=B8?= =?UTF-8?q?=EC=9E=90=20=EB=B3=80=EA=B2=BD=20(#102)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/FoodControllerTest.java | 10 ++-- .../diareat/service/FoodServiceTest.java | 53 ++++++++++--------- 2 files changed, 34 insertions(+), 29 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index 1110177..110e582 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -313,7 +313,7 @@ void testGetNutritionSumByWeek() throws Exception { , 500, 100, 50, 50, 0.2, 0.3, 0.4, 0.5, BaseNutrition.createNutrition(500, 100, 50, 50)); ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); - when(foodService.getNutritionSumByWeek(any(Long.class))).thenReturn(responseNutritionSumByDateDto); + when(foodService.getNutritionSumByWeek(any(Long.class), any(int.class), any(int.class), any(int.class))).thenReturn(responseNutritionSumByDateDto); //When @@ -348,7 +348,7 @@ void testGetNutritionSumByMonth() throws Exception { , 500, 100, 50, 50, 0.2, 0.3, 0.4, 0.5, BaseNutrition.createNutrition(500, 100, 50, 50)); ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); - when(foodService.getNutritionSumByMonth(any(Long.class))).thenReturn(responseNutritionSumByDateDto); + when(foodService.getNutritionSumByMonth(any(Long.class), any(int.class), any(int.class), any(int.class))).thenReturn(responseNutritionSumByDateDto); //When @@ -388,7 +388,7 @@ void testGetScoreOfUserWithBestAndWorstFoods() throws Exception{ 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); + when(foodService.getScoreOfUserWithBestAndWorstFoods(any(Long.class), any(int.class), any(int.class), any(int.class))).thenReturn(responseScoreBestWorstDto); //When @@ -418,7 +418,7 @@ void testGetAnalysisOfUser() throws Exception { 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); + when(foodService.getAnalysisOfUser(any(Long.class), any(int.class), any(int.class), any(int.class))).thenReturn(responseAnalysisDto); //When mockMvc.perform(MockMvcRequestBuilders @@ -450,7 +450,7 @@ void testGetUserRankByWeek() throws Exception{ List responseRankUserDtoList = List.of(responseRankUserDto1, responseRankUserDto2); ApiResponse> expectedResponse = ApiResponse.success(responseRankUserDtoList, ResponseCode.FOOD_READ_SUCCESS.getMessage()); - when(foodService.getUserRankByWeek(testUserId)).thenReturn(responseRankUserDtoList); + when(foodService.getUserRankByWeek(any(Long.class), any(int.class), any(int.class), any(int.class))).thenReturn(responseRankUserDtoList); //When mockMvc.perform(MockMvcRequestBuilders diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 28741e3..3643ed3 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -231,7 +231,7 @@ void testNutritionSumByWeek(){ //when - ResponseNutritionSumByDateDto responseNutritionSumByDateDto = foodService.getNutritionSumByWeek(user.getId()); + ResponseNutritionSumByDateDto responseNutritionSumByDateDto = foodService.getNutritionSumByWeek(user.getId(), 2010,1,1); assertEquals(1400, responseNutritionSumByDateDto.getTotalKcal()); assertEquals(150, responseNutritionSumByDateDto.getTotalCarbohydrate()); assertEquals(200, responseNutritionSumByDateDto.getTotalProtein()); @@ -260,7 +260,7 @@ void testNutritionSumByMonth(){ //when - ResponseNutritionSumByDateDto responseNutritionSumByDateDto = foodService.getNutritionSumByMonth(user.getId()); + ResponseNutritionSumByDateDto responseNutritionSumByDateDto = foodService.getNutritionSumByMonth(user.getId(), 2010,1,1); assertEquals(1400, responseNutritionSumByDateDto.getTotalKcal()); assertEquals(150, responseNutritionSumByDateDto.getTotalCarbohydrate()); assertEquals(200, responseNutritionSumByDateDto.getTotalProtein()); @@ -290,7 +290,7 @@ void getBest3FoodTest() { given(userRepository.existsById(user.getId())).willReturn(true); // when - ResponseFoodRankDto response = foodService.getBestFoodByWeek(user.getId()); + ResponseFoodRankDto response = foodService.getBestFoodByWeek(user.getId(), 2010,1,1); List top3Foods = response.getRankFoodList(); // then @@ -317,7 +317,7 @@ void getWorst3FoodsTest() { given(userRepository.existsById(user.getId())).willReturn(true); // when - ResponseFoodRankDto response = foodService.getWorstFoodByWeek(user.getId()); + ResponseFoodRankDto response = foodService.getWorstFoodByWeek(user.getId(), 2010,1,1); List top3Foods = response.getRankFoodList(); // then @@ -344,7 +344,7 @@ void getUserRankByWeek() { given(foodRepository.findAllByUserIdAndDateBetween(eq(2L), any(LocalDate.class), any(LocalDate.class),any(Sort.class))).willReturn(List.of(food2)); // when - List response = foodService.getUserRankByWeek(user1.getId()); + List response = foodService.getUserRankByWeek(user1.getId(), 2010,1,1); // then assertEquals(2, response.size()); @@ -377,10 +377,12 @@ void testGetScoreOfUserWithBestAndWorstFoods(){ Food food3 = Food.createFood( "Food3", user, BaseNutrition.createNutrition(200, 100 ,6, 3), 2010,1,1); user.setId(1L); - food1.setDate(LocalDate.now()); - food1_1.setDate(LocalDate.now()); - food2.setDate(LocalDate.now().minusDays(2)); - food3.setDate(LocalDate.now().minusDays(3)); + LocalDate fixedDate = LocalDate.of(2010, 1, 1); + + food1.setDate(fixedDate); + food1_1.setDate(fixedDate); + food2.setDate(fixedDate.minusDays(2)); + food3.setDate(fixedDate.minusDays(3)); List foodList = List.of(food1, food1_1, food2, food3); @@ -389,7 +391,7 @@ void testGetScoreOfUserWithBestAndWorstFoods(){ given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class),any(Sort.class))).willReturn(foodList); // when - ResponseScoreBestWorstDto response = foodService.getScoreOfUserWithBestAndWorstFoods(user.getId()); + ResponseScoreBestWorstDto response = foodService.getScoreOfUserWithBestAndWorstFoods(user.getId(), 2010, 1, 1); List top3Foods = response.getBest(); List worst3Foods = response.getWorst(); double totalScore = response.getTotalScore(); @@ -420,31 +422,33 @@ void testGetAnalysisOfUser(){ Food food5 = Food.createFood( "Food5", user, BaseNutrition.createNutrition(300, 100 ,2, 5), 2010,1,1); 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)); + LocalDate fixedDate = LocalDate.of(2010, 5, 1); + + food1.setDate(fixedDate); + food1_1.setDate(fixedDate); + food2.setDate(fixedDate.minusDays(2)); + food3.setDate(fixedDate.minusDays(3)); + food4.setDate(fixedDate.minusWeeks(1)); + food5.setDate(fixedDate.minusWeeks(2)); List foodListOfWeek = List.of(food1,food1_1, food2, food3); List foodListOfMonth = List.of(food1, food1_1,food2, food3, food4, food5); - Sort sort = Sort.by(Sort.Direction.DESC, "addedTime"); + Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); 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(),sort)).willReturn(foodListOfWeek); - given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().minusWeeks(3).with(DayOfWeek.MONDAY), LocalDate.now(),sort)).willReturn(foodListOfMonth); - given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now(),sort)).willReturn(foodListOfWeek); + given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), fixedDate.minusWeeks(1), fixedDate,sort)).willReturn(foodListOfWeek); + given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY), fixedDate,sort)).willReturn(foodListOfMonth); + given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), fixedDate.with(DayOfWeek.MONDAY), fixedDate,sort)).willReturn(foodListOfWeek); // when - ResponseAnalysisDto response = foodService.getAnalysisOfUser(user.getId()); + ResponseAnalysisDto response = foodService.getAnalysisOfUser(user.getId(), fixedDate.getYear(), fixedDate.getMonthValue(), fixedDate.getDayOfMonth()); double totalScore = response.getTotalScore(); List calorieLastSevenDays = response.getCalorieLastSevenDays(); @@ -461,6 +465,7 @@ void testGetAnalysisOfUser(){ assertEquals(5, calorieLastFourWeeks.size()); //한달동안의 음식 -> 5개 + //날짜 정렬 확인 (1주) assertEquals(230, calorieLastSevenDays.get(0)); assertEquals(18, proteinLastSevenDays.get(0)); @@ -488,9 +493,9 @@ void testGetAnalysisOfUser(){ assertEquals(2, proteinLastFourWeeks.get(4)); - verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().minusWeeks(1), LocalDate.now(),sort); - verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().minusWeeks(3).with(DayOfWeek.MONDAY), LocalDate.now(),sort); - verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), LocalDate.now().with(DayOfWeek.MONDAY), LocalDate.now(),sort); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), fixedDate.minusWeeks(1), fixedDate,sort); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY), fixedDate,sort); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), fixedDate.with(DayOfWeek.MONDAY), fixedDate,sort); } From 46924684a51902b79b19fc03541672621134863c Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 16 Nov 2023 22:47:51 +0900 Subject: [PATCH 274/371] =?UTF-8?q?:recycle:=20refactor:=20JPA=EC=97=90?= =?UTF-8?q?=EC=84=9C=20addedTime=20=EA=B8=B0=EC=A4=80=EC=9C=BC=EB=A1=9C=20?= =?UTF-8?q?=EC=A0=95=EB=A0=AC=20(#102)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../food/repository/FoodRepository.java | 4 ++-- .../diareat/food/service/FoodService.java | 21 +++++++------------ 2 files changed, 9 insertions(+), 16 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 d11d496..db42ed6 100644 --- a/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java +++ b/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java @@ -10,6 +10,6 @@ public interface FoodRepository extends JpaRepository { boolean existsByIdAndUserId(Long id, Long userId); // 유저가 먹은 음식인지 확인 boolean existsByName(String name); - List findAllByUserIdAndDate(Long userId, LocalDate date, Sort sort); //유저가 특정 날짜에 먹은 음식 반환 - List findAllByUserIdAndDateBetween(Long userId, LocalDate startDate, LocalDate endDate, Sort sort); // 유저가 특정 기간 내에 먹은 음식 반환 + List findAllByUserIdAndDateOrderByAddedTimeAsc(Long userId, LocalDate date); //유저가 특정 날짜에 먹은 음식 반환 + List findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(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 61d5c58..63a6395 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -52,8 +52,7 @@ public Long saveFood(CreateFoodDto createFoodDto) { @Transactional(readOnly = true) public List getFoodListByDate(Long userId, LocalDate date){ validateUser(userId); - Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); - List foodList = foodRepository.findAllByUserIdAndDate(userId, date, sort); + List foodList = foodRepository.findAllByUserIdAndDateOrderByAddedTimeAsc(userId, date); return foodList.stream() .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); } @@ -123,8 +122,7 @@ public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { // 유저의 특정 날짜에 먹은 음식들의 영양성분별 총합 조회 (섭취영양소/기준영양소 및 비율까지 계산해서 반환, dto 구체적 협의 필요) public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { validateUser(userId); - Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); - List foodList = foodRepository.findAllByUserIdAndDate(userId, date, sort); + List foodList = foodRepository.findAllByUserIdAndDateOrderByAddedTimeAsc(userId, date); return calculateNutritionSumAndRatio(userId, foodList, date, 1); } @@ -133,8 +131,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDat public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId, int year, int month, int day) { validateUser(userId); LocalDate endDate = LocalDate.of(year, month, day); - Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); + List foodList = foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(userId, endDate.minusWeeks(1), endDate); return calculateNutritionSumAndRatio(userId, foodList, endDate, 7); } @@ -144,8 +141,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId, int year public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId, int year, int month, int day) { validateUser(userId); LocalDate endDate = LocalDate.of(year, month, day); - Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusMonths(1), endDate, sort); + List foodList = foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(userId, endDate.minusMonths(1), endDate); return calculateNutritionSumAndRatio(userId, foodList, endDate, 30); } @@ -155,8 +151,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId, int yea public ResponseFoodRankDto getBestFoodByWeek(Long userId, int year, int month, int day) { validateUser(userId); LocalDate endDate = LocalDate.of(year, month, day); - Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); + List foodList = foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(userId, endDate.minusWeeks(1), endDate); List top3Foods = foodList.stream() .sorted(Comparator.comparingDouble((Food food) -> @@ -178,8 +173,7 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId, int year, int month, i public ResponseFoodRankDto getWorstFoodByWeek(Long userId, int year, int month, int day) { validateUser(userId); LocalDate endDate = LocalDate.of(year, month, day); - Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, endDate.minusWeeks(1), endDate, sort); + List foodList = foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(userId, endDate.minusWeeks(1), endDate); List worst3Foods = foodList.stream() .sorted(Comparator.comparingDouble((Food food) -> @@ -414,8 +408,7 @@ private void validateFavoriteFood(Long favoriteFoodId, Long userId) { // 1주일동안 먹은 음식들의 영양성분 총합을 요일을 Key로 한 Map을 통해 반환 private HashMap> getNutritionSumByDateMap(Long userId, LocalDate startDate, LocalDate endDate) { HashMap> maps = new HashMap<>(); - Sort sort = Sort.by(Sort.Direction.DESC, MessageUtil.TIME_STAMP); - List foodList = foodRepository.findAllByUserIdAndDateBetween(userId, startDate, endDate, sort); + List foodList = foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(userId, startDate, endDate); for (Food food : foodList) { if (maps.containsKey(food.getDate())) { maps.get(food.getDate()).add(food.getBaseNutrition()); From d269a24bd6f7918349606b400be9bd02845e9e2f Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 16 Nov 2023 22:55:34 +0900 Subject: [PATCH 275/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20?= =?UTF-8?q?=ED=98=84=EC=9E=AC=20=EC=8B=9C=EA=B0=84=20=EC=9D=98=EC=A1=B4?= =?UTF-8?q?=EC=84=B1=20=EC=A0=9C=EA=B1=B0=ED=95=9C=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=20=EC=BD=94=EB=93=9C=20=EC=9E=91=EC=84=B1=20(#102)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/service/FoodServiceTest.java | 64 +++++-------------- 1 file changed, 17 insertions(+), 47 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 3643ed3..761f022 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -66,7 +66,7 @@ void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리 given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); given(userRepository.existsById(user.getId())).willReturn(true); given(foodRepository.save(any(Food.class))).willReturn(food); - given(foodRepository.findAllByUserIdAndDate(any(Long.class), any(LocalDate.class), any(Sort.class))).willReturn(List.of(food)); + given(foodRepository.findAllByUserIdAndDateOrderByAddedTimeAsc(any(Long.class), any(LocalDate.class))).willReturn(List.of(food)); //when Long foodId = foodService.saveFood(createFoodDto); @@ -199,7 +199,7 @@ void testNutritionSumByDate(){ given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); - given(foodRepository.findAllByUserIdAndDate(any(Long.class), any(LocalDate.class), any(Sort.class))).willReturn(List.of(food)); + given(foodRepository.findAllByUserIdAndDateOrderByAddedTimeAsc(any(Long.class), any(LocalDate.class))).willReturn(List.of(food)); //when @@ -226,7 +226,7 @@ void testNutritionSumByWeek(){ given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); - given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class), any(Sort.class))).willReturn(List.of(food)); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(List.of(food)); @@ -255,7 +255,7 @@ void testNutritionSumByMonth(){ given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); - given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class),any(Sort.class))).willReturn(List.of(food)); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(List.of(food)); @@ -286,7 +286,7 @@ void getBest3FoodTest() { List foodList = List.of(food1, food2, food3, food4, food5); - given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class),any(Sort.class))).willReturn(foodList); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(foodList); given(userRepository.existsById(user.getId())).willReturn(true); // when @@ -313,7 +313,7 @@ void getWorst3FoodsTest() { List foodList = List.of(food1, food2, food3, food4, food5); - given(foodRepository.findAllByUserIdAndDateBetween(any(Long.class), any(LocalDate.class), any(LocalDate.class),any(Sort.class))).willReturn(foodList); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(foodList); given(userRepository.existsById(user.getId())).willReturn(true); // when @@ -340,8 +340,8 @@ void getUserRankByWeek() { given(userRepository.findById(user1.getId())).willReturn(Optional.of(user1)); given(followRepository.findAllByFromUser(user1.getId())).willReturn(List.of(user2)); - given(foodRepository.findAllByUserIdAndDateBetween(eq(1L), any(LocalDate.class), any(LocalDate.class),any(Sort.class))).willReturn(List.of(food1)); - given(foodRepository.findAllByUserIdAndDateBetween(eq(2L), any(LocalDate.class), any(LocalDate.class),any(Sort.class))).willReturn(List.of(food2)); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(eq(1L), any(LocalDate.class), any(LocalDate.class))).willReturn(List.of(food1)); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(eq(2L), any(LocalDate.class), any(LocalDate.class))).willReturn(List.of(food2)); // when List response = foodService.getUserRankByWeek(user1.getId(), 2010,1,1); @@ -363,8 +363,8 @@ void getUserRankByWeek() { assertEquals(250, response.get(1).getTotalScore()); verify(userRepository, times(1)).findById(user1.getId()); verify(followRepository, times(1)).findAllByFromUser(user1.getId()); - verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(eq(1L), any(LocalDate.class), any(LocalDate.class),any(Sort.class)); - verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(eq(2L), any(LocalDate.class), any(LocalDate.class),any(Sort.class)); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(eq(1L), any(LocalDate.class), any(LocalDate.class)); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(eq(2L), any(LocalDate.class), any(LocalDate.class)); } @Test @@ -388,7 +388,7 @@ void testGetScoreOfUserWithBestAndWorstFoods(){ 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),any(Sort.class))).willReturn(foodList); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(any(Long.class), any(LocalDate.class), any(LocalDate.class))).willReturn(foodList); // when ResponseScoreBestWorstDto response = foodService.getScoreOfUserWithBestAndWorstFoods(user.getId(), 2010, 1, 1); @@ -442,9 +442,9 @@ void testGetAnalysisOfUser(){ given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.getReferenceById(any(Long.class))).willReturn(user); - given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), fixedDate.minusWeeks(1), fixedDate,sort)).willReturn(foodListOfWeek); - given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY), fixedDate,sort)).willReturn(foodListOfMonth); - given(foodRepository.findAllByUserIdAndDateBetween(user.getId(), fixedDate.with(DayOfWeek.MONDAY), fixedDate,sort)).willReturn(foodListOfWeek); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(1), fixedDate)).willReturn(foodListOfWeek); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY), fixedDate)).willReturn(foodListOfMonth); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.with(DayOfWeek.MONDAY), fixedDate)).willReturn(foodListOfWeek); // when @@ -452,9 +452,7 @@ void testGetAnalysisOfUser(){ double totalScore = response.getTotalScore(); List calorieLastSevenDays = response.getCalorieLastSevenDays(); - List proteinLastSevenDays = response.getProteinLastSevenDays(); List calorieLastFourWeeks = response.getCalorieLastFourWeek(); - List proteinLastFourWeeks = response.getProteinLastFourWeek(); // then @@ -465,37 +463,9 @@ void testGetAnalysisOfUser(){ 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(), fixedDate.minusWeeks(1), fixedDate,sort); - verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY), fixedDate,sort); - verify(foodRepository, times(1)).findAllByUserIdAndDateBetween(user.getId(), fixedDate.with(DayOfWeek.MONDAY), fixedDate,sort); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(1), fixedDate); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY), fixedDate); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.with(DayOfWeek.MONDAY), fixedDate); } From 6d6e59db08ccaa743c6c9c104af6f2cbd69632be Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Thu, 16 Nov 2023 23:01:52 +0900 Subject: [PATCH 276/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20parame?= =?UTF-8?q?ter=20=EB=B3=80=EA=B2=BD=EC=97=90=20=EB=94=B0=EB=A5=B8=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=20(#102)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/FoodControllerTest.java | 45 +++++++++++++------ 1 file changed, 31 insertions(+), 14 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index 110e582..0b7d88a 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -18,6 +18,7 @@ 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.cglib.core.Local; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; @@ -270,7 +271,7 @@ void testDeleteFavoriteFood() throws Exception { @WithMockUser("test") void testGetNutritionSumByDate() throws Exception{ //Given - LocalDate date = LocalDate.now(); + LocalDate date = LocalDate.of(2021,10,10); ResponseNutritionSumByDateDto responseNutritionSumByDateDto = ResponseNutritionSumByDateDto.of(testUserId,date,1 ,500,100,50,50,0.2,0.3,0.4,0.5, BaseNutrition.createNutrition(500,100,50,50)); @@ -308,7 +309,7 @@ void testGetNutritionSumByDate() throws Exception{ @WithMockUser("test") void testGetNutritionSumByWeek() throws Exception { //Given - LocalDate date = LocalDate.now(); + LocalDate date = LocalDate.of(2021, 10, 10); ResponseNutritionSumByDateDto responseNutritionSumByDateDto = ResponseNutritionSumByDateDto.of(testUserId, date, 7 , 500, 100, 50, 50, 0.2, 0.3, 0.4, 0.5, BaseNutrition.createNutrition(500, 100, 50, 50)); @@ -318,7 +319,10 @@ void testGetNutritionSumByWeek() throws Exception { //When mockMvc.perform(MockMvcRequestBuilders - .get("/api/food/{userId}/nutrition/recentWeek", testUserId)) + .get("/api/food/{userId}/nutrition/recentWeek", 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())) @@ -343,7 +347,7 @@ void testGetNutritionSumByWeek() throws Exception { @WithMockUser("test") void testGetNutritionSumByMonth() throws Exception { //Given - LocalDate date = LocalDate.now(); + LocalDate date = LocalDate.of(2021, 10, 10); ResponseNutritionSumByDateDto responseNutritionSumByDateDto = ResponseNutritionSumByDateDto.of(testUserId, date, 30 , 500, 100, 50, 50, 0.2, 0.3, 0.4, 0.5, BaseNutrition.createNutrition(500, 100, 50, 50)); @@ -353,7 +357,10 @@ void testGetNutritionSumByMonth() throws Exception { //When mockMvc.perform(MockMvcRequestBuilders - .get("/api/food/{userId}/nutrition/recentMonth", testUserId)) + .get("/api/food/{userId}/nutrition/recentMonth", 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())) @@ -378,12 +385,13 @@ void testGetNutritionSumByMonth() throws Exception { @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()); + LocalDate date = LocalDate.of(2021, 10, 10); + ResponseSimpleFoodDto food1 = ResponseSimpleFoodDto.of("test1", 100, 100, 100, 100, date); + ResponseSimpleFoodDto food2 = ResponseSimpleFoodDto.of("test", 100, 100, 100, 100, date); + ResponseSimpleFoodDto food3 = ResponseSimpleFoodDto.of("test", 100, 100, 100, 100, date); + ResponseSimpleFoodDto food4 = ResponseSimpleFoodDto.of("test4", 100, 100, 100, 100, date); + ResponseSimpleFoodDto food5 = ResponseSimpleFoodDto.of("test", 100, 100, 100, 100, date); + ResponseSimpleFoodDto food6 = ResponseSimpleFoodDto.of("test", 100, 100, 100, 100, date); ResponseScoreBestWorstDto responseScoreBestWorstDto = ResponseScoreBestWorstDto.of(testUserId, 100, 80 , 60, 240, List.of(food1, food2,food3), List.of(food4, food5, food6)); @@ -393,7 +401,10 @@ void testGetScoreOfUserWithBestAndWorstFoods() throws Exception{ //When mockMvc.perform(MockMvcRequestBuilders - .get("/api/food/{userId}/score", testUserId)) + .get("/api/food/{userId}/score", testUserId, date.getYear(), date.getMonthValue(), date.getDayOfMonth()) + .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())) @@ -422,7 +433,10 @@ void testGetAnalysisOfUser() throws Exception { //When mockMvc.perform(MockMvcRequestBuilders - .get("/api/food/{userId}/analysis", testUserId)) + .get("/api/food/{userId}/analysis", testUserId) + .param("yy", String.valueOf(2021)) + .param("mm", String.valueOf(10)) + .param("dd", String.valueOf(10))) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) @@ -454,7 +468,10 @@ void testGetUserRankByWeek() throws Exception{ //When mockMvc.perform(MockMvcRequestBuilders - .get("/api/food/{userId}/rank", testUserId)) + .get("/api/food/{userId}/rank", testUserId) + .param("yy", String.valueOf(2021)) + .param("mm", String.valueOf(10)) + .param("dd", String.valueOf(10))) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) From 4f2b729310dfe35602c25deba3c5288ce8ffcc80 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 16 Nov 2023 14:09:24 +0000 Subject: [PATCH 277/371] :construction_worker: chore: Update deployment to 361426e78736b96f73ec13f0046f5cf9269b0ea4 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 4291271..5636cc7 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: d227a3cd + newTag: "361426e7" From 94b4f66a0fa845687aacf9af60ff3f96d4897a32 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 17 Nov 2023 20:52:43 +0900 Subject: [PATCH 278/371] =?UTF-8?q?:ambulance:=20Fix:=20=EC=9C=A0=EC=A0=80?= =?UTF-8?q?=20=EA=B2=80=EC=83=89=20API=20GET=20->=20POST=EB=A1=9C=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20(#104)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/user/controller/UserController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/user/controller/UserController.java b/src/main/java/com/diareat/diareat/user/controller/UserController.java index ff9f0fe..51623bb 100644 --- a/src/main/java/com/diareat/diareat/user/controller/UserController.java +++ b/src/main/java/com/diareat/diareat/user/controller/UserController.java @@ -65,7 +65,7 @@ public ApiResponse updateUserNutrition(@RequestBody @Valid UpdateUserNutri // 회원의 친구 검색 결과 조회 @Operation(summary = "[주간 랭킹] 회원의 친구 검색 결과 조회", description = "회원의 친구 검색 결과를 조회합니다.") - @GetMapping("/search") + @PostMapping("/search") public ApiResponse> searchUser(@RequestBody @Valid SearchUserDto searchUserDto) { return ApiResponse.success(userService.searchUser(searchUserDto.getUserId(), searchUserDto.getInputName()), ResponseCode.USER_SEARCH_SUCCESS.getMessage()); } From 3556c378246b8b445461ac187e7c5b3e037dfa24 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 17 Nov 2023 20:56:07 +0900 Subject: [PATCH 279/371] =?UTF-8?q?:ambulance:=20Fix:=20=EA=B4=80=EB=A0=A8?= =?UTF-8?q?=20=ED=85=8C=EC=8A=A4=ED=8A=B8=EC=BD=94=EB=93=9C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=20(#104)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/controller/UserControllerTest.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java index d7ed8fd..8ec9171 100644 --- a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java @@ -1,6 +1,5 @@ package com.diareat.diareat.controller; -import com.diareat.diareat.auth.service.KakaoAuthService; import com.diareat.diareat.user.controller.UserController; import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; @@ -48,9 +47,6 @@ class UserControllerTest { @MockBean private UserService userService; - @MockBean - private KakaoAuthService kakaoAuthService; - private final Long testUserId = 1L; 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)); @@ -230,7 +226,7 @@ void searchUser() throws Exception { // When & Then mockMvc.perform( MockMvcRequestBuilders - .get("/api/user/search") + .post("/api/user/search") .contentType(MediaType.APPLICATION_JSON) .content(json) .accept(MediaType.APPLICATION_JSON)) @@ -253,7 +249,7 @@ void searchUserFail() throws Exception { // When & Then mockMvc.perform( MockMvcRequestBuilders - .get("/api/user/search") + .post("/api/user/search") .contentType(MediaType.APPLICATION_JSON) .content(json) .accept(MediaType.APPLICATION_JSON)) From de42febd63a83592ed661edea4ef422d137d8203 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 17 Nov 2023 11:58:53 +0000 Subject: [PATCH 280/371] :construction_worker: chore: Update deployment to 5d4bc1fbcef6067a069bac9e3a65e50d97b9ce8f --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 5636cc7..9635149 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: "361426e7" + newTag: 5d4bc1fb From 470d8f3404bcb0d1392dc8d211eb090effb05136 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 17 Nov 2023 21:48:43 +0900 Subject: [PATCH 281/371] =?UTF-8?q?:ambulance:=20Fix:=20=EC=84=9C=EB=B9=84?= =?UTF-8?q?=EC=8A=A4=20=EC=A3=BC=EC=9A=94=20=EC=8B=9C=EC=A0=90=20=EB=A1=9C?= =?UTF-8?q?=EA=B7=B8=20=EC=B6=94=EA=B0=80=20=EB=B0=8F=20=ED=8C=94=EB=A1=9C?= =?UTF-8?q?=EC=9A=B0=20=EA=B4=80=EB=A0=A8=20=EB=B2=84=EA=B7=B8=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=20(#106)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/repository/FollowRepository.java | 1 + .../diareat/user/service/UserService.java | 50 ++++++++++++++----- 2 files changed, 39 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/repository/FollowRepository.java b/src/main/java/com/diareat/diareat/user/repository/FollowRepository.java index cfd4843..46e04bc 100644 --- a/src/main/java/com/diareat/diareat/user/repository/FollowRepository.java +++ b/src/main/java/com/diareat/diareat/user/repository/FollowRepository.java @@ -13,4 +13,5 @@ public interface FollowRepository extends JpaRepository { List findAllByFromUser(@Param("userId") Long userId); boolean existsByFromUserAndToUser(Long fromUser, Long toUser); // 팔로우 여부 확인 + void deleteByFromUserAndToUser(Long fromUser, Long toUser); // 팔로우 취소 } diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 46aa5d7..66468fa 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -16,6 +16,7 @@ import com.diareat.diareat.util.api.ResponseCode; import com.diareat.diareat.util.exception.UserException; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @@ -25,6 +26,7 @@ import java.util.List; import java.util.stream.Collectors; +@Slf4j @RequiredArgsConstructor @Service public class UserService { @@ -35,12 +37,17 @@ public class UserService { // 회원정보 저장 @Transactional public Long saveUser(CreateUserDto createUserDto) { - if (userRepository.existsByName(createUserDto.getName())) + if (userRepository.existsByName(createUserDto.getName())) { + log.info("이미 존재하는 닉네임입니다 by {}", createUserDto.getName()); throw new UserException(ResponseCode.USER_NAME_ALREADY_EXIST); - if(userRepository.existsByKeyCode(createUserDto.getKeyCode())) + } + if(userRepository.existsByKeyCode(createUserDto.getKeyCode())) { + log.info("이미 존재하는 키코드입니다 by {}", createUserDto.getKeyCode()); throw new UserException(ResponseCode.USER_ALREADY_EXIST); + } int type = UserTypeUtil.decideUserType(createUserDto.getGender(), createUserDto.getAge()); + log.info("회원 타입: {}", type); List standard = UserTypeUtil.getStanardByUserType(type); // 유저 타입에 따른 기본 기준섭취량 조회 BaseNutrition baseNutrition = BaseNutrition.createNutrition(standard.get(0), standard.get(2), createUserDto.getWeight(), standard.get(1)); // 단백질은 자신 체중 기준으로 계산 User user = User.createUser(createUserDto.getName(), createUserDto.getImage(), createUserDto.getKeyCode(), createUserDto.getHeight(), createUserDto.getWeight(), createUserDto.getGender(), createUserDto.getAge(), baseNutrition); @@ -52,6 +59,7 @@ public Long saveUser(CreateUserDto createUserDto) { @Transactional(readOnly = true) public ResponseSimpleUserDto getSimpleUserInfo(Long userId) { User user = getUserById(userId); + log.info("{} 회원 기본정보 조회 완료: ", user.getName()); return ResponseSimpleUserDto.of(user.getName(), user.getImage()); } @@ -60,6 +68,7 @@ public ResponseSimpleUserDto getSimpleUserInfo(Long userId) { @Transactional(readOnly = true) public ResponseUserDto getUserInfo(Long userId) { User user = getUserById(userId); + log.info("{} 회원정보 조회 완료: ", user.getName()); return ResponseUserDto.from(user); } @@ -68,8 +77,10 @@ public ResponseUserDto getUserInfo(Long userId) { @Transactional public void updateUserInfo(UpdateUserDto updateUserDto) { User user = getUserById(updateUserDto.getUserId()); + log.info("{} 회원정보 조회 완료: ", user.getName()); user.updateUser(updateUserDto.getName(), updateUserDto.getHeight(), updateUserDto.getWeight(), updateUserDto.getAge(), updateUserDto.isAutoUpdateNutrition()); userRepository.save(user); + log.info("{} 회원정보 수정 완료: ", user.getName()); } // 회원 기준섭취량 조회 @@ -77,7 +88,9 @@ public void updateUserInfo(UpdateUserDto updateUserDto) { @Transactional(readOnly = true) public ResponseUserNutritionDto getUserNutrition(Long userId) { User user = getUserById(userId); + log.info("{} user 객체 조회 완료: ", user.getName()); List standard = UserTypeUtil.getStanardByUserType(user.getType()); // 유저 타입에 따른 기본 기준섭취량 조회 + log.info("{} 회원 기준섭취량 조회 완료: ", user.getName()); return ResponseUserNutritionDto.from(user, standard.get(0), standard.get(2), user.getWeight(), standard.get(1)); // 단백질은 자신 체중 기준으로 계산 } @@ -86,9 +99,11 @@ public ResponseUserNutritionDto getUserNutrition(Long userId) { @Transactional public void updateBaseNutrition(UpdateUserNutritionDto updateUserNutritionDto) { User user = getUserById(updateUserNutritionDto.getUserId()); + log.info("{} user 객체 조회 완료: ", user.getName()); BaseNutrition baseNutrition = BaseNutrition.createNutrition(updateUserNutritionDto.getCalorie(), updateUserNutritionDto.getCarbohydrate(), updateUserNutritionDto.getProtein(), updateUserNutritionDto.getFat()); user.updateBaseNutrition(baseNutrition); userRepository.save(user); + log.info("{} 회원 기준섭취량 수정 완료: ", user.getName()); } // 회원 탈퇴 @@ -97,13 +112,16 @@ public void updateBaseNutrition(UpdateUserNutritionDto updateUserNutritionDto) { public void deleteUser(Long userId) { validateUser(userId); userRepository.deleteById(userId); + log.info("PK {} 회원 탈퇴 완료: ", userId); } // 회원의 친구 검색 결과 조회 -> 검색 및 팔로우는 굉장히 돌발적으로 이루어질 가능성이 높아 캐시 적용 X @Transactional(readOnly = true) public List searchUser(Long hostId, String name) { validateUser(hostId); + log.info("{} 회원 검증 완료", hostId); List users = new ArrayList<>(userRepository.findAllByNameContaining(name)); + log.info("{} 검색 결과 조회 완료", name); users.removeIf(user -> user.getId().equals(hostId)); // 검색 결과에서 자기 자신은 제외 (removeIf 메서드는 ArrayList에만 존재) return users.stream() .map(user -> ResponseSearchUserDto.of(user.getId(), user.getName(), user.getImage(), followRepository.existsByFromUserAndToUser(hostId, user.getId()))).collect(Collectors.toList()); @@ -111,24 +129,32 @@ public List searchUser(Long hostId, String name) { // 회원이 특정 회원 팔로우 @Transactional - public void followUser(Long userId, Long followId) { - validateUser(userId); - validateUser(followId); + public void followUser(Long fromId, Long toId) { + validateUser(fromId); + validateUser(toId); + log.info("팔로우 대상 검증 완료"); // 이미 팔로우 중인 경우 - if (followRepository.existsByFromUserAndToUser(userId, followId)) + if (followRepository.existsByFromUserAndToUser(fromId, toId)) { + log.info("{}는 이미 {}를 팔로우한 상태입니다.", fromId, toId); throw new UserException(ResponseCode.FOLLOWED_ALREADY); - followRepository.save(Follow.makeFollow(userId, followId)); + } + followRepository.save(Follow.makeFollow(toId, fromId)); + log.info("이제 {}가 {}를 팔로우합니다.", fromId, toId); } // 회원이 특정 회원 팔로우 취소 @Transactional - public void unfollowUser(Long userId, Long unfollowId) { - validateUser(userId); - validateUser(unfollowId); + public void unfollowUser(Long fromId, Long toId) { + validateUser(fromId); + validateUser(toId); + log.info("팔로우 대상 검증 완료"); // 이미 팔로우 취소한 경우 - if (!followRepository.existsByFromUserAndToUser(userId, unfollowId)) + if (!followRepository.existsByFromUserAndToUser(fromId, toId)) { + log.info("{}는 이미 {}를 팔로우 취소한 상태입니다.", fromId, toId); throw new UserException(ResponseCode.UNFOLLOWED_ALREADY); - followRepository.delete(Follow.makeFollow(userId, unfollowId)); + } + followRepository.deleteByFromUserAndToUser(fromId, toId); + log.info("이제 {}가 {}를 언팔로우합니다.", fromId, toId); } private void validateUser(Long userId) { From 02dc95e3136a9dd80b1aae353019c044ac23e905 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 17 Nov 2023 21:51:09 +0900 Subject: [PATCH 282/371] =?UTF-8?q?:ambulance:=20Fix:=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=EC=BD=94=EB=93=9C=20=EB=B0=98=EC=98=81=20(#106)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/com/diareat/diareat/service/UserServiceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/diareat/diareat/service/UserServiceTest.java b/src/test/java/com/diareat/diareat/service/UserServiceTest.java index 1bbbbc6..ca96d59 100644 --- a/src/test/java/com/diareat/diareat/service/UserServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/UserServiceTest.java @@ -263,7 +263,7 @@ void unfollowUser() { userService.unfollowUser(userId, unfollowId); // Then - verify(followRepository, times(1)).delete(any(Follow.class)); + verify(followRepository, times(1)).deleteByFromUserAndToUser(userId, unfollowId); } @DisplayName("회원이 특정 회원 팔로우 취소 중복 요청") From 2d4f5ee3dbd11706a002c34fabe9a9d172d5d664 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 17 Nov 2023 12:54:24 +0000 Subject: [PATCH 283/371] :construction_worker: chore: Update deployment to 08b0c5d465efaa640cc5272a34597b2f1ff882c7 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 9635149..2ac69bc 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 5d4bc1fb + newTag: 08b0c5d4 From 5dd247ef78dada31eed6ec242470f47bbd18026b Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sat, 18 Nov 2023 02:38:22 +0900 Subject: [PATCH 284/371] =?UTF-8?q?:ambulance:=20hotfix:=20userid=EB=B0=98?= =?UTF-8?q?=ED=99=98=EC=9D=B4=20=EC=95=84=EB=8B=8C=20favorite=20food=20id?= =?UTF-8?q?=EB=A1=9C=20=EC=A0=9C=EB=8C=80=EB=A1=9C=20=EB=B0=98=ED=99=98?= =?UTF-8?q?=ED=95=98=EB=8F=84=EB=A1=9D=20=EC=88=98=EC=A0=95=20(#108)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/food/service/FoodService.java | 2 +- 1 file changed, 1 insertion(+), 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 63a6395..bc31858 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -96,7 +96,7 @@ public List getFavoriteFoodList(Long userId){ validateUser(userId); List foodList = favoriteFoodRepository.findAllByUserId(userId); return foodList.stream() - .map(favoriteFood -> ResponseFavoriteFoodDto.of(favoriteFood.getUser().getId(),favoriteFood.getName(), + .map(favoriteFood -> ResponseFavoriteFoodDto.of(favoriteFood.getId(),favoriteFood.getName(), favoriteFood.getBaseNutrition(), favoriteFood.getCount())).collect(Collectors.toList()); } From 480093cdf5faa360cf7b815ba332c380c7d9d9b6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 17 Nov 2023 17:41:24 +0000 Subject: [PATCH 285/371] :construction_worker: chore: Update deployment to ccd0e4986092a4844fd5cb5d19ea4cd83f87e547 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 2ac69bc..b69c83a 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 08b0c5d4 + newTag: ccd0e498 From f734f34f13077b456d7a7436909b24a5ca50048c Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 19 Nov 2023 02:26:22 +0900 Subject: [PATCH 286/371] =?UTF-8?q?:bug:=20fix:=20timezone=20=EC=84=A4?= =?UTF-8?q?=EC=A0=95=20(#110)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/DiareatApplication.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/com/diareat/diareat/DiareatApplication.java b/src/main/java/com/diareat/diareat/DiareatApplication.java index 79fcc2e..77eece4 100644 --- a/src/main/java/com/diareat/diareat/DiareatApplication.java +++ b/src/main/java/com/diareat/diareat/DiareatApplication.java @@ -4,6 +4,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; +import javax.annotation.PostConstruct; +import java.util.TimeZone; + @EnableCaching @SpringBootApplication public class DiareatApplication { @@ -12,4 +15,9 @@ public static void main(String[] args) { SpringApplication.run(DiareatApplication.class, args); } + @PostConstruct + void started(){ + TimeZone.setDefault(TimeZone.getTimeZone("Asia/Seoul")); + } + } From f922ae6ffce89574ef12090d7efc3d9141ee6f84 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 18 Nov 2023 17:30:34 +0000 Subject: [PATCH 287/371] :construction_worker: chore: Update deployment to 16026d3105a57527649fa29f211c2ddffcfc6535 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index b69c83a..d8419dd 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: ccd0e498 + newTag: 16026d31 From 5a9cfcdef3c2a85c1cfa9478c6acf44a29ed94c5 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 19 Nov 2023 15:32:35 +0900 Subject: [PATCH 288/371] =?UTF-8?q?:bug:=20fix:=20JPA=EC=97=90=EA=B2=8C=20?= =?UTF-8?q?=EB=82=A0=EC=A7=9C=20=EC=A0=95=EB=A0=AC=20=EC=9C=84=EC=9E=84=20?= =?UTF-8?q?(#112)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/food/service/FoodService.java | 11 ----------- 1 file changed, 11 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 bc31858..2ddec65 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -236,17 +236,6 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId, int year, int month, i double totalWeekScore = calculateUserScoreThisWeek(user, LocalDate.of(year, month, day).with(DayOfWeek.MONDAY), LocalDate.of(year, month, day)).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<>(); From 2245509341409e9f022da6de908b1f921ea7b746 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Nov 2023 06:38:02 +0000 Subject: [PATCH 289/371] :construction_worker: chore: Update deployment to 304587e9863fdfa1ee7f14ef0a706c9261fcd78c --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index d8419dd..f10965a 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 16026d31 + newTag: "304587e9" From 0401c603259bb63200aed398a8a7e1a0df1fcffe Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 21 Nov 2023 16:01:37 +0900 Subject: [PATCH 290/371] =?UTF-8?q?:ambulance:=20Fix:=20=EA=B0=99=EC=9D=80?= =?UTF-8?q?=20=EC=9D=8C=EC=8B=9D=20=EC=A4=91=EB=B3=B5=20=EC=A6=90=EA=B2=A8?= =?UTF-8?q?=EC=B0=BE=EA=B8=B0=20=EC=98=88=EC=99=B8=EC=B2=98=EB=A6=AC=20?= =?UTF-8?q?=EB=B0=A9=EC=8B=9D=20=EC=88=98=EC=A0=95=20(#114)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/repository/FavoriteFoodRepository.java | 1 - src/main/java/com/diareat/diareat/food/service/FoodService.java | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java b/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java index fad8f7c..5514240 100644 --- a/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java +++ b/src/main/java/com/diareat/diareat/food/repository/FavoriteFoodRepository.java @@ -8,5 +8,4 @@ public interface FavoriteFoodRepository extends JpaRepository { List findAllByUserId(Long userId); boolean existsByIdAndUserId(Long id, Long userId); // 유저가 즐겨찾기에 추가한 음식인지 확인 - boolean existsByFoodId(Long foodId); // 이미 즐겨찾기에 추가된 음식인지 확인하기 위함 } 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 2ddec65..b9fc363 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -82,7 +82,7 @@ public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { User user = getUserById(createFavoriteFoodDto.getUserId()); Food food = getFoodById(createFavoriteFoodDto.getFoodId()); - if (favoriteFoodRepository.existsByFoodId(createFavoriteFoodDto.getFoodId())) + if (food.isFavorite()) throw new FavoriteException(ResponseCode.FAVORITE_ALREADY_EXIST); FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood(createFavoriteFoodDto.getName(), user, food, createFavoriteFoodDto.getBaseNutrition()); From b6d15a80b55bc4a31ead4ef05e8273ffb96ebc69 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 21 Nov 2023 16:02:16 +0900 Subject: [PATCH 291/371] =?UTF-8?q?:ambulance:=20Fix:=20=EC=9D=8C=EC=8B=9D?= =?UTF-8?q?=EA=B3=BC=20=EC=A6=90=EA=B2=A8=EC=B0=BE=EB=8A=94=20=EC=9D=8C?= =?UTF-8?q?=EC=8B=9D=20=EA=B0=84=20=EC=97=B0=EA=B4=80=EA=B4=80=EA=B3=84=20?= =?UTF-8?q?=EA=B0=9C=ED=8E=B8=20(#114)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/domain/FavoriteFood.java | 13 ++++++++----- .../java/com/diareat/diareat/food/domain/Food.java | 4 +++- .../diareat/diareat/food/service/FoodService.java | 2 +- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java index a4db401..a6d139c 100644 --- a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java +++ b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java @@ -8,6 +8,8 @@ import javax.persistence.*; import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @@ -20,9 +22,10 @@ public class FavoriteFood { private String name; - @OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST}, orphanRemoval = false) // 즐찾음식이 삭제되어도 음식은 삭제되지 않음 - @JoinColumn(name = "food_id") - private Food food; + //@OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST}, orphanRemoval = false) // 즐찾음식이 삭제되어도 음식은 삭제되지 않음 + //@JoinColumn(name = "food_id") + @OneToMany(mappedBy = "favoriteFood", cascade = CascadeType.PERSIST, orphanRemoval = false) // 즐찾음식이 삭제되어도 음식은 삭제되지 않음 + private List foods = new ArrayList<>(); @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id") @@ -40,10 +43,10 @@ public void addCount(){ public static FavoriteFood createFavoriteFood(String name, User user, Food food, BaseNutrition baseNutrition) { FavoriteFood favoriteFood = new FavoriteFood(); favoriteFood.name = name; - favoriteFood.food = food; + favoriteFood.foods.add(food); favoriteFood.user = user; favoriteFood.baseNutrition = baseNutrition; - food.setFavoriteFood(favoriteFood); + //food.setFavoriteFood(favoriteFood); 관계의 주인이 즐겨찾기로 명확하게 정해졌기에 주석처리 return favoriteFood; } 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 78d7175..0c7b9fa 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -26,7 +26,9 @@ public class Food { @JoinColumn(name = "user_id") private User user; - @OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST}, orphanRemoval = false) // 음식이 삭제되어도 즐찾음식은 삭제되지 않음 + //@OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST}, orphanRemoval = false) // 음식이 삭제되어도 즐찾음식은 삭제되지 않음 + //@JoinColumn(name = "favorite_food_id") + @ManyToOne(fetch = FetchType.LAZY) // 다대일로 매핑하여 음식의 즐찾음식을 찾을 수 있도록 함 @JoinColumn(name = "favorite_food_id") private FavoriteFood favoriteFood; 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 b9fc363..a8f11e9 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -82,7 +82,7 @@ public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { User user = getUserById(createFavoriteFoodDto.getUserId()); Food food = getFoodById(createFavoriteFoodDto.getFoodId()); - if (food.isFavorite()) + if (food.isFavorite()) // 이미 즐겨찾기에 추가된 음식인 경우 중복 추가 불가능 throw new FavoriteException(ResponseCode.FAVORITE_ALREADY_EXIST); FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood(createFavoriteFoodDto.getName(), user, food, createFavoriteFoodDto.getBaseNutrition()); From 505f12276e57a51f81db220aaa027c393bdae02d Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 21 Nov 2023 16:28:11 +0900 Subject: [PATCH 292/371] =?UTF-8?q?:ambulance:=20Fix:=20user=20=ED=8C=A8?= =?UTF-8?q?=ED=82=A4=EC=A7=80=20RequestDto=20=EB=B2=94=EC=9C=84=20?= =?UTF-8?q?=EC=9C=A0=ED=9A=A8=EC=84=B1=EA=B2=80=EC=82=AC=20decimal?= =?UTF-8?q?=EC=97=90=EC=84=9C=20range=EB=A1=9C=20=EC=88=98=EC=A0=95=20(#11?= =?UTF-8?q?4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/dto/request/JoinUserDto.java | 14 +++++--------- .../diareat/user/dto/request/UpdateUserDto.java | 12 ++++-------- .../user/dto/request/UpdateUserNutritionDto.java | 15 +++++---------- 3 files changed, 14 insertions(+), 27 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/dto/request/JoinUserDto.java b/src/main/java/com/diareat/diareat/user/dto/request/JoinUserDto.java index 0bd95f7..fa35adc 100644 --- a/src/main/java/com/diareat/diareat/user/dto/request/JoinUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/JoinUserDto.java @@ -4,6 +4,7 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import org.hibernate.validator.constraints.Range; import javax.validation.constraints.*; @@ -18,20 +19,15 @@ public class JoinUserDto { @NotBlank(message = MessageUtil.NOT_BLANK) private String nickName; - @DecimalMin(value = "0", message = MessageUtil.GENDER_RANGE) - @DecimalMax(value = "1", message = MessageUtil.GENDER_RANGE) + @Range(min = 0, max = 1, message = MessageUtil.GENDER_RANGE) private int gender; - @DecimalMin(value = "100", message = MessageUtil.HEIGHT_RANGE) - @DecimalMax(value = "250", message = MessageUtil.HEIGHT_RANGE) + @Range(min = 100, max = 250, message = MessageUtil.HEIGHT_RANGE) private int height; - @DecimalMin(value = "30", message = MessageUtil.WEIGHT_RANGE) - @DecimalMax(value = "150", message = MessageUtil.WEIGHT_RANGE) + @Range(min = 30, max = 150, message = MessageUtil.WEIGHT_RANGE) private int weight; - @DecimalMin(value = "5", message = MessageUtil.AGE_RANGE) - @DecimalMax(value = "100", message = MessageUtil.AGE_RANGE) + @Range(min = 5, max = 100, message = MessageUtil.AGE_RANGE) private int age; - } diff --git a/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java index 9f5821b..818f3e2 100644 --- a/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java @@ -4,9 +4,8 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import org.hibernate.validator.constraints.Range; -import javax.validation.constraints.DecimalMax; -import javax.validation.constraints.DecimalMin; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; @@ -21,16 +20,13 @@ public class UpdateUserDto { @NotBlank(message = MessageUtil.NOT_BLANK) private String name; - @DecimalMin(value = "100", message = MessageUtil.HEIGHT_RANGE) - @DecimalMax(value = "250", message = MessageUtil.HEIGHT_RANGE) + @Range(min = 100, max = 250, message = MessageUtil.HEIGHT_RANGE) private int height; - @DecimalMin(value = "30", message = MessageUtil.WEIGHT_RANGE) - @DecimalMax(value = "200", message = MessageUtil.WEIGHT_RANGE) + @Range(min = 30, max = 200, message = MessageUtil.WEIGHT_RANGE) private int weight; - @DecimalMin(value = "5", message = MessageUtil.AGE_RANGE) - @DecimalMax(value = "100", message = MessageUtil.AGE_RANGE) + @Range(min = 5, max = 100, message = MessageUtil.AGE_RANGE) private int age; private boolean isAutoUpdateNutrition; // 개인정보를 활용한 기준 영양소 자동계산 여부 diff --git a/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserNutritionDto.java b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserNutritionDto.java index 1ed25d6..aa3ad4c 100644 --- a/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserNutritionDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserNutritionDto.java @@ -4,9 +4,8 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import org.hibernate.validator.constraints.Range; -import javax.validation.constraints.DecimalMax; -import javax.validation.constraints.DecimalMin; import javax.validation.constraints.NotNull; @Getter @@ -17,20 +16,16 @@ public class UpdateUserNutritionDto { @NotNull(message = MessageUtil.NOT_NULL) private Long userId; - @DecimalMin(value = "100", message = MessageUtil.CALORIE_RANGE) - @DecimalMax(value = "10000", message = MessageUtil.CALORIE_RANGE) + @Range(min = 100, max = 10000, message = MessageUtil.CALORIE_RANGE) private int calorie; - @DecimalMin(value = "100", message = MessageUtil.CARBOHYDRATE_RANGE) - @DecimalMax(value = "500", message = MessageUtil.CARBOHYDRATE_RANGE) + @Range(min = 100, max = 500, message = MessageUtil.CARBOHYDRATE_RANGE) private int carbohydrate; - @DecimalMin(value = "25", message = MessageUtil.PROTEIN_RANGE) - @DecimalMax(value = "500", message = MessageUtil.PROTEIN_RANGE) + @Range(min = 25, max = 500, message = MessageUtil.PROTEIN_RANGE) private int protein; - @DecimalMin(value = "25", message = MessageUtil.FAT_RANGE) - @DecimalMax(value = "500", message = MessageUtil.FAT_RANGE) + @Range(min = 25, max = 500, message = MessageUtil.FAT_RANGE) private int fat; public static UpdateUserNutritionDto of(Long userId, int calorie, int carbohydrate, int protein, int fat) { From b856dc576ccf0b1416f4be22d1fb0575b3b7ddcc Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 21 Nov 2023 16:34:17 +0900 Subject: [PATCH 293/371] =?UTF-8?q?:ambulance:=20Fix:=20Food=20=EA=B0=9D?= =?UTF-8?q?=EC=B2=B4=20Cascade=20=EC=86=8D=EC=84=B1=20=EB=88=84=EB=9D=BD?= =?UTF-8?q?=20=EC=88=98=EC=A0=95=20(#114)?= 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 | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) 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 0c7b9fa..3eeb200 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -9,7 +9,6 @@ import javax.persistence.*; import java.time.LocalDate; import java.time.LocalDateTime; -import java.time.LocalTime; @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @@ -28,7 +27,7 @@ public class Food { //@OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST}, orphanRemoval = false) // 음식이 삭제되어도 즐찾음식은 삭제되지 않음 //@JoinColumn(name = "favorite_food_id") - @ManyToOne(fetch = FetchType.LAZY) // 다대일로 매핑하여 음식의 즐찾음식을 찾을 수 있도록 함 + @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST}) // 다대일로 매핑하여 음식의 즐찾음식을 찾을 수 있도록 함 @JoinColumn(name = "favorite_food_id") private FavoriteFood favoriteFood; From 517110c2ab6ba22fa14db03d6ff96f5fcbd0794a Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 21 Nov 2023 16:42:44 +0900 Subject: [PATCH 294/371] =?UTF-8?q?:ambulance:=20Fix:=20Food=20=EC=A6=90?= =?UTF-8?q?=EA=B2=A8=EC=B0=BE=EA=B8=B0=20=EB=93=B1=EB=A1=9D=20=EB=88=84?= =?UTF-8?q?=EB=9D=BD=EB=90=9C=20=EB=A1=9C=EC=A7=81=20=EC=88=98=EC=A0=95=20?= =?UTF-8?q?(#114)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/service/FoodService.java | 3 +++ 1 file changed, 3 insertions(+) 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 a8f11e9..b1d0798 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -86,6 +86,8 @@ public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { throw new FavoriteException(ResponseCode.FAVORITE_ALREADY_EXIST); FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood(createFavoriteFoodDto.getName(), user, food, createFavoriteFoodDto.getBaseNutrition()); + food.setFavoriteFood(favoriteFood); + foodRepository.save(food); return favoriteFoodRepository.save(favoriteFood).getId(); } @@ -302,6 +304,7 @@ public List getUserRankByWeek(Long userId, int year, int mo } @Transactional + // 즐겨찾기 음식으로부터 새로운 음식을 간편 등록 public Long createFoodFromFavoriteFood(CreateFoodFromFavoriteFoodDto createFoodFromFavoriteFoodDto) { validateFavoriteFood(createFoodFromFavoriteFoodDto.getFavoriteFoodId(), createFoodFromFavoriteFoodDto.getUserId()); FavoriteFood favoriteFood = getFavoriteFoodById(createFoodFromFavoriteFoodDto.getFavoriteFoodId()); From 0065cf58d6b68ef1ca2a2f7748769f17c1d58dc9 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 21 Nov 2023 19:43:13 +0900 Subject: [PATCH 295/371] =?UTF-8?q?:ambulance:=20Fix:=20=EB=A1=9C=EC=A7=81?= =?UTF-8?q?=20=ED=99=95=EC=9D=B8=EC=9A=A9=20FoodService=EC=97=90=20Log=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20(#114)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 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 b1d0798..f0eae73 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -16,6 +16,7 @@ import com.diareat.diareat.util.exception.FoodException; import com.diareat.diareat.util.exception.UserException; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.cache.annotation.CacheEvict; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; @@ -27,6 +28,7 @@ import java.util.*; import java.util.stream.Collectors; +@Slf4j @RequiredArgsConstructor @Service public class FoodService { @@ -41,10 +43,12 @@ public class FoodService { @Transactional public Long saveFood(CreateFoodDto createFoodDto) { if (foodRepository.existsByName(createFoodDto.getName())){ + log.info(createFoodDto.getName() + ": 이미 존재하는 음식 이름입니다."); throw new FoodException(ResponseCode.FOOD_NAME_ALREADY_EXIST); } User user = getUserById(createFoodDto.getUserId()); Food food = Food.createFood(createFoodDto.getName(), user, createFoodDto.getBaseNutrition(), createFoodDto.getYear(), createFoodDto.getMonth(), createFoodDto.getDay()); + log.info("신규 음식 저장: " + food.getName()); return foodRepository.save(food).getId(); } @@ -53,6 +57,7 @@ public Long saveFood(CreateFoodDto createFoodDto) { public List getFoodListByDate(Long userId, LocalDate date){ validateUser(userId); List foodList = foodRepository.findAllByUserIdAndDateOrderByAddedTimeAsc(userId, date); + log.info(date.toString() + "의 "+ userId + "에게 조회된 음식 개수: " + foodList.size() + "개"); return foodList.stream() .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); } @@ -63,6 +68,7 @@ public List getFoodListByDate(Long userId, LocalDate date){ public void updateFood(UpdateFoodDto updateFoodDto, LocalDate date) { Food food = getFoodById(updateFoodDto.getFoodId()); food.updateFood(updateFoodDto.getName(), updateFoodDto.getBaseNutrition()); + log.info("음식 정보 수정 완료: " + food.getName()); foodRepository.save(food); } @@ -72,6 +78,7 @@ public void updateFood(UpdateFoodDto updateFoodDto, LocalDate date) { public void deleteFood(Long foodId, Long userId, LocalDate date) { validateFood(foodId, userId); foodRepository.deleteById(foodId); + log.info("음식 삭제 완료: " + foodId); } // 즐겨찾기에 음식 저장 @@ -82,12 +89,15 @@ public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { User user = getUserById(createFavoriteFoodDto.getUserId()); Food food = getFoodById(createFavoriteFoodDto.getFoodId()); - if (food.isFavorite()) // 이미 즐겨찾기에 추가된 음식인 경우 중복 추가 불가능 + if (food.isFavorite()) {// 이미 즐겨찾기에 추가된 음식인 경우 중복 추가 불가능 + log.info(food.getId() + ": 이미 즐겨찾기에 추가된 음식입니다."); throw new FavoriteException(ResponseCode.FAVORITE_ALREADY_EXIST); + } FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood(createFavoriteFoodDto.getName(), user, food, createFavoriteFoodDto.getBaseNutrition()); food.setFavoriteFood(favoriteFood); foodRepository.save(food); + log.info("즐겨찾기 음식 저장 완료: " + favoriteFood.getName()); return favoriteFoodRepository.save(favoriteFood).getId(); } @@ -97,6 +107,7 @@ public Long saveFavoriteFood(CreateFavoriteFoodDto createFavoriteFoodDto) { public List getFavoriteFoodList(Long userId){ validateUser(userId); List foodList = favoriteFoodRepository.findAllByUserId(userId); + log.info(userId + "의 즐겨찾기 음식 개수: " + foodList.size() + "개 조회 완료"); return foodList.stream() .map(favoriteFood -> ResponseFavoriteFoodDto.of(favoriteFood.getId(),favoriteFood.getName(), favoriteFood.getBaseNutrition(), favoriteFood.getCount())).collect(Collectors.toList()); @@ -109,6 +120,7 @@ public void updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto) { FavoriteFood food = getFavoriteFoodById(updateFavoriteFoodDto.getFavoriteFoodId()); food.updateFavoriteFood(updateFavoriteFoodDto.getName(), updateFavoriteFoodDto.getBaseNutrition()); favoriteFoodRepository.save(food); + log.info("즐겨찾기 음식 수정 완료: " + food.getName()); } // 즐겨찾기 해제 @@ -117,6 +129,7 @@ public void updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto) { public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { validateFavoriteFood(favoriteFoodId, userId); favoriteFoodRepository.deleteById(favoriteFoodId); + log.info("즐겨찾기 음식 해제 완료: " + favoriteFoodId); } // @Cacheable(value = "ResponseNutritionSumByDateDto", key = "#userId+#date.toString()", cacheManager = "diareatCacheManager") @@ -125,6 +138,7 @@ public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDate date) { validateUser(userId); List foodList = foodRepository.findAllByUserIdAndDateOrderByAddedTimeAsc(userId, date); + log.info(date.toString() + "기준 "+ userId + "의 음식들의 영양성분별 총합 조회 완료"); return calculateNutritionSumAndRatio(userId, foodList, date, 1); } @@ -134,7 +148,6 @@ public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId, int year validateUser(userId); LocalDate endDate = LocalDate.of(year, month, day); List foodList = foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(userId, endDate.minusWeeks(1), endDate); - return calculateNutritionSumAndRatio(userId, foodList, endDate, 7); } From 1c63d40d78da6a64deb871ecfb4f0d3915df1432 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 21 Nov 2023 12:06:47 +0000 Subject: [PATCH 296/371] :construction_worker: chore: Update deployment to 5482d25fb34653675ae620f9990d5dc0909f4752 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index f10965a..9300448 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: "304587e9" + newTag: 5482d25f From 94a65a806f8998f6593f9a8660cd43379a9c7aa9 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Tue, 21 Nov 2023 21:54:57 +0900 Subject: [PATCH 297/371] =?UTF-8?q?:construction=5Fworker:=20chore:=20sona?= =?UTF-8?q?rqube=20workflow=20=EB=8F=84=EC=9E=85=20(#116)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/Diareat-CICD.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/Diareat-CICD.yml b/.github/workflows/Diareat-CICD.yml index 56f467f..d86f943 100644 --- a/.github/workflows/Diareat-CICD.yml +++ b/.github/workflows/Diareat-CICD.yml @@ -31,6 +31,12 @@ jobs: with: arguments: build + - name: SonarQube Scan + uses: kitabisa/sonarqube-action@v1.2.1 + with: + host: ${{ secrets.SONAR_ENDPOINT }} + login: ${{ secrets.SONAR_TOKEN }} + - name: Docker login uses: docker/login-action@v3.0.0 with: From 92b559b16ac998b1af72deef5188d2a63fee32af Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Tue, 21 Nov 2023 22:00:00 +0900 Subject: [PATCH 298/371] =?UTF-8?q?:green=5Fheart:=20chore:=20=EC=98=A4?= =?UTF-8?q?=EB=A5=98=EB=A1=9C=20=EC=9D=B8=ED=95=9C=20sonarqube=20=EC=B7=A8?= =?UTF-8?q?=EC=86=8C=20(#116)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/Diareat-CICD.yml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/.github/workflows/Diareat-CICD.yml b/.github/workflows/Diareat-CICD.yml index d86f943..56f467f 100644 --- a/.github/workflows/Diareat-CICD.yml +++ b/.github/workflows/Diareat-CICD.yml @@ -31,12 +31,6 @@ jobs: with: arguments: build - - name: SonarQube Scan - uses: kitabisa/sonarqube-action@v1.2.1 - with: - host: ${{ secrets.SONAR_ENDPOINT }} - login: ${{ secrets.SONAR_TOKEN }} - - name: Docker login uses: docker/login-action@v3.0.0 with: From 92dd0a8a7fdd8afe08193dd93928554980755edc Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 21 Nov 2023 13:02:52 +0000 Subject: [PATCH 299/371] :construction_worker: chore: Update deployment to 912a77b5fd39e14383f4212b64751c4df100f584 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 9300448..abb21ac 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 5482d25f + newTag: 912a77b5 From 385a69614ce43e9b897a42db0840f851b995f2e3 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 21 Nov 2023 23:46:11 +0900 Subject: [PATCH 300/371] =?UTF-8?q?:ambulance:=20Fix:=20=EC=A6=90=EC=B0=BE?= =?UTF-8?q?=20=ED=95=B4=EC=A0=9C=20=EC=8B=9C=20=EC=9E=90=EC=8B=9D=20?= =?UTF-8?q?=EC=9D=8C=EC=8B=9D=EA=B0=9D=EC=B2=B4=20=EC=97=B0=EC=87=84?= =?UTF-8?q?=EC=82=AD=EC=A0=9C=20=EB=AA=85=EC=8B=9C=EC=A0=81=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EC=B6=94=EA=B0=80=20(#114)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/food/service/FoodService.java | 2 ++ 1 file changed, 2 insertions(+) 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 f0eae73..7e4ed47 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -128,6 +128,8 @@ public void updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto) { @Transactional public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { validateFavoriteFood(favoriteFoodId, userId); + FavoriteFood favoriteFood = getFavoriteFoodById(favoriteFoodId); + favoriteFood.getFoods().forEach(food -> food.setFavoriteFood(null)); // 즐겨찾기 음식으로부터 태어난 음식들의 즐겨찾기 정보를 null로 초기화 favoriteFoodRepository.deleteById(favoriteFoodId); log.info("즐겨찾기 음식 해제 완료: " + favoriteFoodId); } From 005c18eac7eafb01d7e498389b13db1ea0b040d4 Mon Sep 17 00:00:00 2001 From: CHAE Date: Wed, 22 Nov 2023 10:04:15 +0900 Subject: [PATCH 301/371] =?UTF-8?q?:ambulance:=20Fix:=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=EC=BD=94=EB=93=9C=20=EC=88=98=EC=A0=95=20(#114)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/com/diareat/diareat/service/FoodServiceTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 761f022..d51d636 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -177,10 +177,12 @@ void testDeleteFavoriteFood() { User user = User.createUser("testUser", "testImage","tessPassword", 1, 180, 80, 18, testBaseNutrition); Food food = Food.createFood("testFood", user, testBaseNutrition, 2010,1,1); FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("testFood", user, food, testBaseNutrition); + food.setFavoriteFood(favoriteFood); favoriteFood.setId(1L); given(favoriteFoodRepository.existsById(favoriteFood.getId())).willReturn(true); given(favoriteFoodRepository.existsByIdAndUserId(favoriteFood.getId(), 1L)).willReturn(true); + given(favoriteFoodRepository.findById(favoriteFood.getId())).willReturn(Optional.of(favoriteFood)); //when foodService.deleteFavoriteFood(favoriteFood.getId(), 1L); From a8418f84bb81fed998ebbccb3528b4cd8d681a2d Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 22 Nov 2023 10:54:19 +0000 Subject: [PATCH 302/371] :construction_worker: chore: Update deployment to 258b3356b60cc650b423e64bb8322b6a305cf917 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index abb21ac..4b9d4fa 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 912a77b5 + newTag: 258b3356 From 4e3c84e7b6162ca39964c4f1e08fa67025ccf7f1 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 26 Nov 2023 19:36:25 +0900 Subject: [PATCH 303/371] =?UTF-8?q?:sparkles:=20feat:=20=EC=9D=BC=EB=B3=84?= =?UTF-8?q?=20=EC=9D=8C=EC=8B=9D=EC=97=90=EC=84=9C=20=ED=95=B4=EB=8B=B9=20?= =?UTF-8?q?=EB=82=A0=EC=A7=9C=20=EC=97=86=EC=9C=BC=EB=A9=B4=200=20?= =?UTF-8?q?=EB=B0=98=ED=99=98=20=EB=B0=8F=20=ED=95=9C=20=EC=A3=BC=20?= =?UTF-8?q?=EB=8B=A8=EC=9C=84=EB=A1=9C=20=EB=AC=B6=EC=96=B4=20=EB=8D=B0?= =?UTF-8?q?=EC=9D=B4=ED=84=B0=20=EB=B0=98=ED=99=98=20(#120)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/service/FoodService.java | 61 ++++++++++++------- .../diareat/service/FoodServiceTest.java | 4 +- 2 files changed, 42 insertions(+), 23 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 7e4ed47..46d62cc 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -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; @@ -247,9 +248,12 @@ 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> nutritionSumOfUserByWeek = getNutritionSumByDateMap(userId, LocalDate.of(year,month,day).minusWeeks(1), LocalDate.of(year, month, day)); - HashMap> nutritionSumOfUserByMonth = getNutritionSumByDateMap(userId, LocalDate.of(year,month,day).minusWeeks(3).with(DayOfWeek.MONDAY), LocalDate.of(year, month ,day)); + HashMap> nutritionSumOfUserByWeek = getNutritionSumByDateMap(userId, currentDate.minusWeeks(1), currentDate); + HashMap> 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(); @@ -262,27 +266,42 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId, int year, int month, i 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(); - 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)){ + System.out.println(date); + if(!nutritionSumOfUserByWeek.containsKey(date)){ //해당 날짜에 먹은 음식이 없는 경우는 0으로 반환 + calorieLastSevenDays.add(0.0); + carbohydrateLastSevenDays.add(0.0); + proteinLastSevenDays.add(0.0); + fatLastSevenDays.add(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((double) totalKcal); + carbohydrateLastSevenDays.add((double) totalCarbohydrate); + proteinLastSevenDays.add((double) totalProtein); + fatLastSevenDays.add((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); diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index d51d636..580679a 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -461,8 +461,8 @@ void testGetAnalysisOfUser(){ 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); From 82ff9b012fc947ef1e3cfcec3a42a621a651dc06 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 26 Nov 2023 19:56:01 +0900 Subject: [PATCH 304/371] =?UTF-8?q?:sparkles:=20=EB=82=A0=EC=A7=9C?= =?UTF-8?q?=EA=B9=8C=EC=A7=80=20=ED=8F=AC=ED=95=A8=ED=95=B4=EC=84=9C=20?= =?UTF-8?q?=EC=98=81=EC=96=91=EC=86=8C=20=EC=A3=BC=EB=8F=84=EB=A1=9D=20?= =?UTF-8?q?=EC=84=A4=EC=A0=95=20(#120)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/dto/ResponseAnalysisDto.java | 12 +++++---- .../diareat/food/service/FoodService.java | 25 +++++++++---------- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java index 0d50559..7d94a36 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java @@ -4,7 +4,9 @@ import lombok.Getter; import lombok.NoArgsConstructor; +import java.time.LocalDate; import java.util.List; +import java.util.Map; @Getter @NoArgsConstructor @@ -12,16 +14,16 @@ public class ResponseAnalysisDto { // 그래프 + 점수에 사용되는 DTO private double totalScore; - private List calorieLastSevenDays; // 최근 7일간의 칼로리 (7개 과거부터 나열) + private List> calorieLastSevenDays; // 최근 7일간의 칼로리 (7개 과거부터 나열) private List calorieLastFourWeek; // 최근 4주간의 칼로리 (4개 과거부터 나열) - private List carbohydrateLastSevenDays; // 최근 7일간의 탄수화물 + private List> carbohydrateLastSevenDays; // 최근 7일간의 탄수화물 private List carbohydrateLastFourWeek; // 최근 4주간의 탄수화물 - private List proteinLastSevenDays; // 최근 7일간의 단백질 + private List> proteinLastSevenDays; // 최근 7일간의 단백질 private List proteinLastFourWeek; // 최근 4주간의 단백질 - private List fatLastSevenDays; // 최근 7일간의 지방 + private List> fatLastSevenDays; // 최근 7일간의 지방 private List fatLastFourWeek; // 최근 4주간의 지방 - public static ResponseAnalysisDto of(double totalScore, List calorieLastSevenDays, List calorieLastFourWeek, List carbohydrateLastSevenDays, List carbohydrateLastFourWeek, List proteinLastSevenDays, List proteinLastFourWeek, List fatLastSevenDays, List fatLastFourWeek) { + public static ResponseAnalysisDto of(double totalScore, List> calorieLastSevenDays, List calorieLastFourWeek,List> carbohydrateLastSevenDays, List carbohydrateLastFourWeek,List> proteinLastSevenDays, List proteinLastFourWeek, List> fatLastSevenDays, List fatLastFourWeek) { return new ResponseAnalysisDto(totalScore, calorieLastSevenDays, calorieLastFourWeek, carbohydrateLastSevenDays, carbohydrateLastFourWeek, proteinLastSevenDays, proteinLastFourWeek, fatLastSevenDays, fatLastFourWeek); } } 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 46d62cc..ecc8f3a 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -257,33 +257,32 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId, int year, int month, i double totalWeekScore = calculateUserScoreThisWeek(user, LocalDate.of(year, month, day).with(DayOfWeek.MONDAY), LocalDate.of(year, month, day)).getTotalScore(); - List calorieLastSevenDays = new ArrayList<>(); + List>calorieLastSevenDays = new ArrayList<>(); List calorieLastFourWeek = new ArrayList<>(); - List carbohydrateLastSevenDays = new ArrayList<>(); + List> carbohydrateLastSevenDays = new ArrayList<>(); List carbohydrateLastFourWeek = new ArrayList<>(); - List proteinLastSevenDays = new ArrayList<>(); + List> proteinLastSevenDays = new ArrayList<>(); List proteinLastFourWeek = new ArrayList<>(); - List fatLastSevenDays = new ArrayList<>(); + List> fatLastSevenDays = new ArrayList<>(); List fatLastFourWeek = new ArrayList<>(); //최근 7일간의 식습관, 비어있으면 0으로 반환 for (LocalDate date = currentDate.minusWeeks(1); date.isBefore(currentDate); date = date.plusDays(1)){ - System.out.println(date); if(!nutritionSumOfUserByWeek.containsKey(date)){ //해당 날짜에 먹은 음식이 없는 경우는 0으로 반환 - calorieLastSevenDays.add(0.0); - carbohydrateLastSevenDays.add(0.0); - proteinLastSevenDays.add(0.0); - fatLastSevenDays.add(0.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((double) totalKcal); - carbohydrateLastSevenDays.add((double) totalCarbohydrate); - proteinLastSevenDays.add((double) totalProtein); - fatLastSevenDays.add((double) totalFat); + 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)); } } From d3922c1c28959231e8a2b8b72d13fc5a58d2f97e Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 26 Nov 2023 19:56:21 +0900 Subject: [PATCH 305/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20?= =?UTF-8?q?=EB=A1=9C=EC=A7=81=20=EC=88=98=EC=A0=95=EC=97=90=20=EB=94=B0?= =?UTF-8?q?=EB=A5=B8=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20=EB=B0=8F=20=ED=86=B5=EA=B3=BC=20(#120)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/controller/FoodControllerTest.java | 16 +++++++++------- .../diareat/diareat/service/FoodServiceTest.java | 3 ++- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index 0b7d88a..eedd8be 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -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; @@ -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; @@ -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 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); @@ -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))) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 580679a..1861410 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -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.*; @@ -453,7 +454,7 @@ void testGetAnalysisOfUser(){ ResponseAnalysisDto response = foodService.getAnalysisOfUser(user.getId(), fixedDate.getYear(), fixedDate.getMonthValue(), fixedDate.getDayOfMonth()); double totalScore = response.getTotalScore(); - List calorieLastSevenDays = response.getCalorieLastSevenDays(); + List> calorieLastSevenDays = response.getCalorieLastSevenDays(); List calorieLastFourWeeks = response.getCalorieLastFourWeek(); From c2282629acff98a8cb601bd357f9472f1be4d1eb Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 26 Nov 2023 11:04:46 +0000 Subject: [PATCH 306/371] :construction_worker: chore: Update deployment to f1348c2ff861b8c4e961cadf2acf5e77e9b3725f --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 4b9d4fa..992a67a 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 258b3356 + newTag: f1348c2f From f0e3e86f7dc535d5a517c60663d766a96bfc34ca Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 28 Nov 2023 11:22:37 +0900 Subject: [PATCH 307/371] =?UTF-8?q?:ambulance:=20Fix:=20jwt=20=EA=B4=80?= =?UTF-8?q?=EB=A0=A8=20=EC=9D=BC=EB=B6=80=20=EC=88=98=EC=A0=95=20(#122)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/auth/component/JwtTokenProvider.java | 2 +- .../diareat/diareat/auth/service/CustomUserDetailService.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java index eed48e3..cbaa13d 100644 --- a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java +++ b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java @@ -67,6 +67,6 @@ public boolean validateToken(String jwtToken) { // Request의 Header에서 token 값 가져오기 public String resolveToken(HttpServletRequest request) { - return request.getHeader("X-AUTH-TOKEN"); + return request.getHeader("accessToken"); } } diff --git a/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java b/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java index 622e09f..f74e6fd 100644 --- a/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java +++ b/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java @@ -15,8 +15,8 @@ public class CustomUserDetailService implements UserDetailsService { private final UserRepository userRepository; @Override - public UserDetails loadUserByUsername(String keyCode) throws UsernameNotFoundException { - return userRepository.findByKeyCode(keyCode) + public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException { + return userRepository.findById(Long.parseLong(id)) .orElseThrow(() -> new UsernameNotFoundException(ResponseCode.USER_NOT_FOUND.getMessage())); } } From 85703c53bf34889f6df6b88ac7807058fddaea4f Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 28 Nov 2023 11:23:37 +0900 Subject: [PATCH 308/371] =?UTF-8?q?:ambulance:=20Fix:=20=EA=B8=B0=EC=A4=80?= =?UTF-8?q?=EC=84=AD=EC=B7=A8=EB=9F=89=20=EC=9E=90=EB=8F=99=EA=B3=84?= =?UTF-8?q?=EC=82=B0=20=EC=97=AC=EB=B6=80=20boolean=EC=97=90=EC=84=9C=20in?= =?UTF-8?q?t=EB=A1=9C=20=EC=88=98=EC=A0=95=20(#122)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/user/domain/User.java | 4 ++-- .../diareat/diareat/user/dto/request/UpdateUserDto.java | 7 ++++--- .../java/com/diareat/diareat/user/service/UserService.java | 2 +- src/main/java/com/diareat/diareat/util/MessageUtil.java | 1 + 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index f0d7c9c..264d1ac 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -112,12 +112,12 @@ public static User createUser(String name, String image, String keyCode, int hei } // 회원정보 수정 - public void updateUser(String name, int height, int weight, int age, boolean autoUpdate) { + public void updateUser(String name, int height, int weight, int age, int autoUpdate) { this.name = name; this.height = height; this.weight = weight; this.age = age; - if(autoUpdate) { + if(autoUpdate == 1) { this.type = UserTypeUtil.decideUserType(this.gender, this.age); } } diff --git a/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java index 818f3e2..c4540ad 100644 --- a/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java @@ -29,9 +29,10 @@ public class UpdateUserDto { @Range(min = 5, max = 100, message = MessageUtil.AGE_RANGE) private int age; - private boolean isAutoUpdateNutrition; // 개인정보를 활용한 기준 영양소 자동계산 여부 + @Range(min = 0, max = 1, message = MessageUtil.ZERO_OR_ONE) + private int autoUpdateNutrition; // 개인정보를 활용한 기준 영양소 자동계산 여부 (0, 1) - public static UpdateUserDto of(Long userId, String userName, int userHeight, int userWeight, int userAge, boolean isAutoUpdateNutrition) { - return new UpdateUserDto(userId, userName, userHeight, userWeight, userAge, isAutoUpdateNutrition); + public static UpdateUserDto of(Long userId, String userName, int userHeight, int userWeight, int userAge, boolean autoUpdateNutrition) { + return new UpdateUserDto(userId, userName, userHeight, userWeight, userAge, Integer.parseInt(String.valueOf(autoUpdateNutrition))); } } diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 66468fa..aaade88 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -78,7 +78,7 @@ public ResponseUserDto getUserInfo(Long userId) { public void updateUserInfo(UpdateUserDto updateUserDto) { User user = getUserById(updateUserDto.getUserId()); log.info("{} 회원정보 조회 완료: ", user.getName()); - user.updateUser(updateUserDto.getName(), updateUserDto.getHeight(), updateUserDto.getWeight(), updateUserDto.getAge(), updateUserDto.isAutoUpdateNutrition()); + user.updateUser(updateUserDto.getName(), updateUserDto.getHeight(), updateUserDto.getWeight(), updateUserDto.getAge(), updateUserDto.getAutoUpdateNutrition()); userRepository.save(user); log.info("{} 회원정보 수정 완료: ", user.getName()); } diff --git a/src/main/java/com/diareat/diareat/util/MessageUtil.java b/src/main/java/com/diareat/diareat/util/MessageUtil.java index aba71cd..ba4d77b 100644 --- a/src/main/java/com/diareat/diareat/util/MessageUtil.java +++ b/src/main/java/com/diareat/diareat/util/MessageUtil.java @@ -18,6 +18,7 @@ public class MessageUtil { // 반복되는 메시지의 형식을 저장하고 public static final String CARBOHYDRATE_RANGE = "탄수화물은 100 이상, 500 이하의 값을 입력해주세요."; public static final String PROTEIN_RANGE = "단백질은 25 이상, 500 이하의 값을 입력해주세요."; public static final String FAT_RANGE = "지방은 25 이상, 500 이하의 값을 입력해주세요."; + public static final String ZERO_OR_ONE = "0 또는 1의 값을 입력해주세요."; public static final String PAST_OR_PRESENT = "과거 또는 오늘 날짜여야 합니다."; public static final String TIME_STAMP = "addedTime"; From ea677fbbf0f6caeea4f008d56012d04d41a21933 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 28 Nov 2023 11:25:28 +0900 Subject: [PATCH 309/371] =?UTF-8?q?:ambulance:=20Fix:=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=EC=BD=94=EB=93=9C=20=EB=B0=98=EC=98=81=20(#122)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/user/dto/request/UpdateUserDto.java | 4 ++-- .../com/diareat/diareat/controller/UserControllerTest.java | 4 ++-- .../java/com/diareat/diareat/service/UserServiceTest.java | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java index c4540ad..8c75931 100644 --- a/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/request/UpdateUserDto.java @@ -32,7 +32,7 @@ public class UpdateUserDto { @Range(min = 0, max = 1, message = MessageUtil.ZERO_OR_ONE) private int autoUpdateNutrition; // 개인정보를 활용한 기준 영양소 자동계산 여부 (0, 1) - public static UpdateUserDto of(Long userId, String userName, int userHeight, int userWeight, int userAge, boolean autoUpdateNutrition) { - return new UpdateUserDto(userId, userName, userHeight, userWeight, userAge, Integer.parseInt(String.valueOf(autoUpdateNutrition))); + public static UpdateUserDto of(Long userId, String userName, int userHeight, int userWeight, int userAge, int autoUpdateNutrition) { + return new UpdateUserDto(userId, userName, userHeight, userWeight, userAge, autoUpdateNutrition); } } diff --git a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java index 8ec9171..d8b1b37 100644 --- a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java @@ -105,7 +105,7 @@ void getUserInfo() throws Exception { void updateUser() throws Exception { // Given ApiResponse expectedResponse = ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); - UpdateUserDto user = UpdateUserDto.of(testUserId, "test2", 170, 80, 21, true); + UpdateUserDto user = UpdateUserDto.of(testUserId, "test2", 170, 80, 21, 1); String json = mapper.writeValueAsString(user); // When & Then @@ -125,7 +125,7 @@ void updateUser() throws Exception { @WithMockUser("test") void updateUserFail() throws Exception { // Given - UpdateUserDto user = UpdateUserDto.of(testUserId, "", 300, 80, 500, true); + UpdateUserDto user = UpdateUserDto.of(testUserId, "", 300, 80, 500, 1); String json = mapper.writeValueAsString(user); // When & Then diff --git a/src/test/java/com/diareat/diareat/service/UserServiceTest.java b/src/test/java/com/diareat/diareat/service/UserServiceTest.java index ca96d59..41691bf 100644 --- a/src/test/java/com/diareat/diareat/service/UserServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/UserServiceTest.java @@ -112,7 +112,7 @@ void getUserInfo() { @Test void updateUserInfo() { // given - UpdateUserDto updateUserDto = UpdateUserDto.of(1L, "update", 180, 75, 25, false); + UpdateUserDto updateUserDto = UpdateUserDto.of(1L, "update", 180, 75, 25, 0); User user = User.createUser("test", "profile.jpg", "keycode123", 175, 70, 0, 30, BaseNutrition.createNutrition(2000, 300, 80, 80)); given(userRepository.findById(updateUserDto.getUserId())).willReturn(Optional.of(user)); From 543963fb02803d7f67e203fc06d218e362e5ff11 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 28 Nov 2023 02:32:19 +0000 Subject: [PATCH 310/371] :construction_worker: chore: Update deployment to 964c44b7503e182ead7e3385c6217df0a04f3db4 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 992a67a..402e57d 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: f1348c2f + newTag: 964c44b7 From 461768590053ad91dcbb8bba0ed898bf3a8c75ed Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 28 Nov 2023 19:59:52 +0900 Subject: [PATCH 311/371] =?UTF-8?q?:ambulance:=20Fix:=20ResponseFoodDto?= =?UTF-8?q?=EC=97=90=20=EC=83=9D=EC=84=B1=EC=8B=9C=EA=B0=84=20=EB=88=84?= =?UTF-8?q?=EB=9D=BD=20=EB=B0=98=EC=98=81=20(#122)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/dto/ResponseFoodDto.java | 7 ++++--- .../java/com/diareat/diareat/food/service/FoodService.java | 2 +- .../com/diareat/diareat/controller/FoodControllerTest.java | 3 ++- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java index af7e268..86c50c9 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java @@ -19,12 +19,13 @@ public class ResponseFoodDto { private String name; private BaseNutrition baseNutrition; private boolean favoriteChecked; + private LocalTime time; - public static ResponseFoodDto of(Long foodId, Long userId, String name, BaseNutrition baseNutrition, boolean favoriteChecked) { - return new ResponseFoodDto(foodId, userId, name, baseNutrition, favoriteChecked); + public static ResponseFoodDto of(Long foodId, Long userId, String name, BaseNutrition baseNutrition, boolean favoriteChecked, LocalTime time) { + return new ResponseFoodDto(foodId, userId, name, baseNutrition, favoriteChecked, time); } public static ResponseFoodDto from(Food food) { - return new ResponseFoodDto(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite()); + return new ResponseFoodDto(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite(), food.getAddedTime().toLocalTime()); } } 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 ecc8f3a..fbd43d7 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -60,7 +60,7 @@ public List getFoodListByDate(Long userId, LocalDate date){ List foodList = foodRepository.findAllByUserIdAndDateOrderByAddedTimeAsc(userId, date); log.info(date.toString() + "의 "+ userId + "에게 조회된 음식 개수: " + foodList.size() + "개"); return foodList.stream() - .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite())).collect(Collectors.toList()); + .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite(), food.getAddedTime().toLocalTime())).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 eedd8be..91cc946 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -29,6 +29,7 @@ import org.springframework.web.context.WebApplicationContext; import java.time.LocalDate; +import java.time.LocalTime; import java.util.List; import java.util.Map; @@ -103,7 +104,7 @@ void testGetFoodListByDate() throws Exception { int mm = 12; LocalDate date = LocalDate.of(yy, mm, dd); - ResponseFoodDto food1 = ResponseFoodDto.of(testFoodId, testUserId,"test",testBaseNutrition,false); + ResponseFoodDto food1 = ResponseFoodDto.of(testFoodId, testUserId,"test",testBaseNutrition,false, LocalTime.of(12,0,0)); 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()); From 94a390cce0770a4f51f5308f22e22b3a0f60fd29 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 28 Nov 2023 11:26:17 +0000 Subject: [PATCH 312/371] :construction_worker: chore: Update deployment to 984b343272550a0ecf96737997018e27e19b3719 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 402e57d..d2ed132 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 964c44b7 + newTag: 984b3432 From 0ade9d94eefb56916590bcda698237010108e848 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Tue, 28 Nov 2023 21:22:34 +0900 Subject: [PATCH 313/371] =?UTF-8?q?:recycle:=20refactor:=20LocalTime=20?= =?UTF-8?q?=EA=B0=9D=EC=B2=B4=EB=A5=BC=20int=20=ED=98=95=EC=9C=BC=EB=A1=9C?= =?UTF-8?q?=20=EB=B6=84=ED=95=B4=20(#125)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/food/dto/ResponseFoodDto.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java index 86c50c9..6c01c5b 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java @@ -19,13 +19,14 @@ public class ResponseFoodDto { private String name; private BaseNutrition baseNutrition; private boolean favoriteChecked; - private LocalTime time; + private int hour; + private int minute; - public static ResponseFoodDto of(Long foodId, Long userId, String name, BaseNutrition baseNutrition, boolean favoriteChecked, LocalTime time) { - return new ResponseFoodDto(foodId, userId, name, baseNutrition, favoriteChecked, time); + public static ResponseFoodDto of(Long foodId, Long userId, String name, BaseNutrition baseNutrition, boolean favoriteChecked, int hour, int minute) { + return new ResponseFoodDto(foodId, userId, name, baseNutrition, favoriteChecked, hour, minute); } public static ResponseFoodDto from(Food food) { - return new ResponseFoodDto(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite(), food.getAddedTime().toLocalTime()); + return new ResponseFoodDto(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite(), food.getAddedTime().getHour(), food.getAddedTime().getMinute()); } } From 2cd8eacb0389b905b8afd5613c5ca134b3b6ca68 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Tue, 28 Nov 2023 21:23:08 +0900 Subject: [PATCH 314/371] =?UTF-8?q?:bug:=20fix:=20=ED=98=84=EC=9E=AC=20?= =?UTF-8?q?=EB=82=A0=EC=A7=9C=20=ED=8F=AC=ED=95=A8=ED=95=B4=EC=84=9C=20?= =?UTF-8?q?=EC=9D=8C=EC=8B=9D=20=EC=A0=95=EB=B3=B4=20=EC=A3=BC=EB=8F=84?= =?UTF-8?q?=EB=A1=9D=20=EC=88=98=EC=A0=95=20(#125)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/service/FoodService.java | 4 ++-- 1 file changed, 2 insertions(+), 2 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 fbd43d7..65e64df 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -60,7 +60,7 @@ public List getFoodListByDate(Long userId, LocalDate date){ List foodList = foodRepository.findAllByUserIdAndDateOrderByAddedTimeAsc(userId, date); log.info(date.toString() + "의 "+ userId + "에게 조회된 음식 개수: " + foodList.size() + "개"); return foodList.stream() - .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite(), food.getAddedTime().toLocalTime())).collect(Collectors.toList()); + .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite(), food.getAddedTime().getHour(), food.getAddedTime().getMinute())).collect(Collectors.toList()); } // 음식 정보 수정 @@ -433,7 +433,7 @@ private void validateFavoriteFood(Long favoriteFoodId, Long userId) { // 1주일동안 먹은 음식들의 영양성분 총합을 요일을 Key로 한 Map을 통해 반환 private HashMap> getNutritionSumByDateMap(Long userId, LocalDate startDate, LocalDate endDate) { HashMap> maps = new HashMap<>(); - List foodList = foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(userId, startDate, endDate); + List foodList = foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(userId, startDate.plusDays(1), endDate.plusDays(1)); for (Food food : foodList) { if (maps.containsKey(food.getDate())) { maps.get(food.getDate()).add(food.getBaseNutrition()); From 2a9ae51019b5519177531ff30be36f6153a2f408 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Tue, 28 Nov 2023 21:23:41 +0900 Subject: [PATCH 315/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20DTO=20?= =?UTF-8?q?=EB=B0=8F=20=EB=A1=9C=EC=A7=81=20=EC=88=98=EC=A0=95=EC=97=90=20?= =?UTF-8?q?=EB=94=B0=EB=A5=B8=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94?= =?UTF-8?q?=EB=93=9C=20=EC=88=98=EC=A0=95=20(#125)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/controller/FoodControllerTest.java | 2 +- .../com/diareat/diareat/service/FoodServiceTest.java | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index 91cc946..f73b5b9 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -104,7 +104,7 @@ void testGetFoodListByDate() throws Exception { int mm = 12; LocalDate date = LocalDate.of(yy, mm, dd); - ResponseFoodDto food1 = ResponseFoodDto.of(testFoodId, testUserId,"test",testBaseNutrition,false, LocalTime.of(12,0,0)); + ResponseFoodDto food1 = ResponseFoodDto.of(testFoodId, testUserId,"test",testBaseNutrition,false,12,1); 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()); diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 1861410..40698f9 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -445,9 +445,9 @@ void testGetAnalysisOfUser(){ given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.getReferenceById(any(Long.class))).willReturn(user); - given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(1), fixedDate)).willReturn(foodListOfWeek); - given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY), fixedDate)).willReturn(foodListOfMonth); - given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.with(DayOfWeek.MONDAY), fixedDate)).willReturn(foodListOfWeek); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(1).plusDays(1), fixedDate.plusDays(1))).willReturn(foodListOfWeek); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY).plusDays(1), fixedDate.plusDays(1))).willReturn(foodListOfMonth); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.with(DayOfWeek.MONDAY).plusDays(1), fixedDate.plusDays(1))).willReturn(foodListOfWeek); // when @@ -466,9 +466,9 @@ void testGetAnalysisOfUser(){ assertEquals(4, calorieLastFourWeeks.size()); //한달동안의 음식 -> 5개 - verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(1), fixedDate); - verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY), fixedDate); - verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.with(DayOfWeek.MONDAY), fixedDate); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(1).plusDays(1), fixedDate.plusDays(1)); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY).plusDays(1), fixedDate.plusDays(1)); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.with(DayOfWeek.MONDAY).plusDays(1), fixedDate.plusDays(1)); } From f13f6f144f198f01846df8162dcb7fc4d64ad8b6 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 28 Nov 2023 21:35:55 +0900 Subject: [PATCH 316/371] =?UTF-8?q?:ambulance:=20Fix:=20=EA=B8=B0=EC=A4=80?= =?UTF-8?q?=EC=84=AD=EC=B7=A8=EB=9F=89=20=EC=9E=90=EB=8F=99=EA=B3=84?= =?UTF-8?q?=EC=82=B0=20=EC=98=B5=EC=85=98=20=EB=B0=9C=EB=8F=99=EB=90=98?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EB=8D=98=20=EB=B2=84=EA=B7=B8=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=20(#122)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/user/domain/User.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index 264d1ac..3bb31b7 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -119,6 +119,8 @@ public void updateUser(String name, int height, int weight, int age, int autoUpd this.age = age; if(autoUpdate == 1) { this.type = UserTypeUtil.decideUserType(this.gender, this.age); + List standard = UserTypeUtil.getStanardByUserType(this.type); + this.baseNutrition = BaseNutrition.createNutrition(standard.get(0), standard.get(2), this.weight, standard.get(1)); } } From f3bf91c692088b568f6079a29a6b5f3d31b4e7e7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 28 Nov 2023 12:38:13 +0000 Subject: [PATCH 317/371] :construction_worker: chore: Update deployment to cb5c758815c3b81ca43186a9c409c2d03121f0f1 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index d2ed132..b24c798 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 984b3432 + newTag: cb5c7588 From 459b9e52e63b28e82539f07730c9d61d8c8ddfa0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 28 Nov 2023 13:50:50 +0000 Subject: [PATCH 318/371] :construction_worker: chore: Update deployment to 20bc227284745f59bb0427fee6d4f672205fdbee --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index b24c798..9c036fc 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: cb5c7588 + newTag: 20bc2272 From 2bc36a1c6a94e6a561ec7c802dafc0af286026fe Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Tue, 28 Nov 2023 23:18:02 +0900 Subject: [PATCH 319/371] =?UTF-8?q?:bug:=20fix:=20=ED=98=84=EC=9E=AC=20?= =?UTF-8?q?=EB=82=A0=EC=A7=9C=EA=B9=8C=EC=A7=80=20=ED=8F=AC=ED=95=A8?= =?UTF-8?q?=ED=95=98=EB=8F=84=EB=A1=9D=20=EC=88=98=EC=A0=95=20(#125)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/food/service/FoodService.java | 4 ++-- 1 file changed, 2 insertions(+), 2 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 65e64df..14519c6 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -249,7 +249,7 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId, int year, int month, i User user = userRepository.getReferenceById(userId); //현재 날짜 - LocalDate currentDate = LocalDate.of(year,month,day); + LocalDate currentDate = LocalDate.of(year,month,day).plusDays(1); //최근 1주간 유저가 먹은 음식들의 날짜별 HashMap HashMap> nutritionSumOfUserByWeek = getNutritionSumByDateMap(userId, currentDate.minusWeeks(1), currentDate); @@ -433,7 +433,7 @@ private void validateFavoriteFood(Long favoriteFoodId, Long userId) { // 1주일동안 먹은 음식들의 영양성분 총합을 요일을 Key로 한 Map을 통해 반환 private HashMap> getNutritionSumByDateMap(Long userId, LocalDate startDate, LocalDate endDate) { HashMap> maps = new HashMap<>(); - List foodList = foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(userId, startDate.plusDays(1), endDate.plusDays(1)); + List foodList = foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(userId, startDate, endDate); for (Food food : foodList) { if (maps.containsKey(food.getDate())) { maps.get(food.getDate()).add(food.getBaseNutrition()); From d28a4b583bd5981ee4b18531bc7fb8abd7413185 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Tue, 28 Nov 2023 23:33:32 +0900 Subject: [PATCH 320/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20Stubbi?= =?UTF-8?q?ng=20=EB=AC=B8=EC=A0=9C=20=ED=95=B4=EA=B2=B0=20(#125)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/service/FoodServiceTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 40698f9..a92fb82 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -446,8 +446,8 @@ void testGetAnalysisOfUser(){ given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.getReferenceById(any(Long.class))).willReturn(user); given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(1).plusDays(1), fixedDate.plusDays(1))).willReturn(foodListOfWeek); - given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY).plusDays(1), fixedDate.plusDays(1))).willReturn(foodListOfMonth); - given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.with(DayOfWeek.MONDAY).plusDays(1), fixedDate.plusDays(1))).willReturn(foodListOfWeek); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY), fixedDate.plusDays(1))).willReturn(foodListOfMonth); + given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.with(DayOfWeek.MONDAY), fixedDate)).willReturn(foodListOfWeek); // when @@ -467,8 +467,8 @@ void testGetAnalysisOfUser(){ verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(1).plusDays(1), fixedDate.plusDays(1)); - verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY).plusDays(1), fixedDate.plusDays(1)); - verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.with(DayOfWeek.MONDAY).plusDays(1), fixedDate.plusDays(1)); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(3).with(DayOfWeek.MONDAY), fixedDate.plusDays(1)); + verify(foodRepository, times(1)).findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.with(DayOfWeek.MONDAY), fixedDate); } From c863a6408f56b2994f0ff7f27bfa9a2e48b2b6f4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 28 Nov 2023 14:37:17 +0000 Subject: [PATCH 321/371] :construction_worker: chore: Update deployment to 726434fd501082442328b80619105a7c64520b29 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 9c036fc..f2faeea 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 20bc2272 + newTag: 726434fd From 71ecda5cc79afb764809301085b28afd6ff76683 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sat, 2 Dec 2023 22:26:37 +0900 Subject: [PATCH 322/371] =?UTF-8?q?:sparkles:=20feat:=20=EC=9D=91=EB=8B=B5?= =?UTF-8?q?=20Dto=20=EC=97=90=20=EB=B0=B0=EC=97=B4=EC=9D=B4=20=EB=B9=84?= =?UTF-8?q?=EC=96=B4=EC=9E=88=EB=8A=94=20=EC=A7=80=20=ED=8C=90=EB=B3=84?= =?UTF-8?q?=ED=95=98=EB=8A=94=20=EC=86=8D=EC=84=B1=20=EC=B6=94=EA=B0=80=20?= =?UTF-8?q?(#129)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/dto/ResponseNutritionSumByDateDto.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java index 09a99cd..17e7dd3 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java @@ -29,12 +29,14 @@ public class ResponseNutritionSumByDateDto implements Serializable { BaseNutrition baseNutrition; + boolean isEmpty; + public static ResponseNutritionSumByDateDto of (Long userId, LocalDate checkDate, int nutritionSumType, int totalKcal, int totalCarbohydrate, int totalProtein, int totalFat, double ratioKcal, double ratioCarbohydrate, double ratioProtein, double ratioFat, - BaseNutrition baseNutrition){ + BaseNutrition baseNutrition, boolean isEmpty){ return new ResponseNutritionSumByDateDto(userId, nutritionSumType, totalKcal, totalCarbohydrate, totalProtein, totalFat, ratioKcal, - ratioCarbohydrate, ratioProtein, ratioFat, baseNutrition); + ratioCarbohydrate, ratioProtein, ratioFat, baseNutrition, isEmpty); } } From 08c652601cb841d04bccf8e2986c53130298f977 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sat, 2 Dec 2023 22:29:55 +0900 Subject: [PATCH 323/371] =?UTF-8?q?:bug:=20fix:=20=EB=B9=88=20=EB=B0=B0?= =?UTF-8?q?=EC=97=B4=EC=9D=BC=20=EA=B2=BD=EC=9A=B0=20=EC=9D=B4=EB=A5=BC=20?= =?UTF-8?q?=EC=95=8C=EB=A6=AC=EB=8F=84=EB=A1=9D=20=EC=88=98=EC=A0=95=20(#1?= =?UTF-8?q?29)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/food/service/FoodService.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 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 14519c6..8689bd1 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -142,7 +142,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByDate(Long userId, LocalDat validateUser(userId); List foodList = foodRepository.findAllByUserIdAndDateOrderByAddedTimeAsc(userId, date); log.info(date.toString() + "기준 "+ userId + "의 음식들의 영양성분별 총합 조회 완료"); - return calculateNutritionSumAndRatio(userId, foodList, date, 1); + return calculateNutritionSumAndRatio(userId, foodList, date, 1, foodList.isEmpty()); } @Transactional(readOnly = true) @@ -151,7 +151,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByWeek(Long userId, int year validateUser(userId); LocalDate endDate = LocalDate.of(year, month, day); List foodList = foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(userId, endDate.minusWeeks(1), endDate); - return calculateNutritionSumAndRatio(userId, foodList, endDate, 7); + return calculateNutritionSumAndRatio(userId, foodList, endDate, 7, foodList.isEmpty()); } @Transactional(readOnly = true) @@ -161,7 +161,7 @@ public ResponseNutritionSumByDateDto getNutritionSumByMonth(Long userId, int yea LocalDate endDate = LocalDate.of(year, month, day); List foodList = foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(userId, endDate.minusMonths(1), endDate); - return calculateNutritionSumAndRatio(userId, foodList, endDate, 30); + return calculateNutritionSumAndRatio(userId, foodList, endDate, 30, foodList.isEmpty()); } @Transactional(readOnly = true) @@ -386,7 +386,8 @@ private ResponseRankUserDto calculateUserScoreThisWeek(User targetUser, LocalDat return ResponseRankUserDto.of(targetUser.getId(), targetUser.getName(), targetUser.getImage(), kcalScore, carbohydrateScore, proteinScore, fatScore, totalScore); } - private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, List foodList, LocalDate checkDate, int nutritionSumType) { + private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, List foodList, LocalDate checkDate, int nutritionSumType, + boolean isEmpty) { User targetUser = getUserById(userId); int totalKcal = 0; int totalCarbohydrate = 0; @@ -408,7 +409,7 @@ private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, return ResponseNutritionSumByDateDto.of(userId, checkDate, nutritionSumType, totalKcal, totalCarbohydrate, totalProtein, totalFat, ratioKcal, - ratioCarbohydrate, ratioProtein, ratioFat, targetUser.getBaseNutrition()); + ratioCarbohydrate, ratioProtein, ratioFat, targetUser.getBaseNutrition(), isEmpty); } private void validateUser(Long userId) { From 6ceceb63efed2986b954ddb3ae5260fa82a2fc68 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sat, 2 Dec 2023 22:30:29 +0900 Subject: [PATCH 324/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20test:=20?= =?UTF-8?q?=EB=A1=9C=EC=A7=81=20=EC=88=98=EC=A0=95=EC=97=90=20=EB=94=B0?= =?UTF-8?q?=EB=A5=B8=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20(#129)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/controller/FoodControllerTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index f73b5b9..cbfe8ed 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -277,7 +277,7 @@ void testGetNutritionSumByDate() throws Exception{ LocalDate date = LocalDate.of(2021,10,10); ResponseNutritionSumByDateDto responseNutritionSumByDateDto = ResponseNutritionSumByDateDto.of(testUserId,date,1 ,500,100,50,50,0.2,0.3,0.4,0.5, - BaseNutrition.createNutrition(500,100,50,50)); + BaseNutrition.createNutrition(500,100,50,50), false); ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto,ResponseCode.FOOD_READ_SUCCESS.getMessage()); when(foodService.getNutritionSumByDate(any(Long.class),any(LocalDate.class))).thenReturn(responseNutritionSumByDateDto); @@ -315,7 +315,7 @@ void testGetNutritionSumByWeek() throws Exception { LocalDate date = LocalDate.of(2021, 10, 10); ResponseNutritionSumByDateDto responseNutritionSumByDateDto = ResponseNutritionSumByDateDto.of(testUserId, date, 7 , 500, 100, 50, 50, 0.2, 0.3, 0.4, 0.5, - BaseNutrition.createNutrition(500, 100, 50, 50)); + BaseNutrition.createNutrition(500, 100, 50, 50), false); ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); when(foodService.getNutritionSumByWeek(any(Long.class), any(int.class), any(int.class), any(int.class))).thenReturn(responseNutritionSumByDateDto); @@ -353,7 +353,7 @@ void testGetNutritionSumByMonth() throws Exception { LocalDate date = LocalDate.of(2021, 10, 10); ResponseNutritionSumByDateDto responseNutritionSumByDateDto = ResponseNutritionSumByDateDto.of(testUserId, date, 30 , 500, 100, 50, 50, 0.2, 0.3, 0.4, 0.5, - BaseNutrition.createNutrition(500, 100, 50, 50)); + BaseNutrition.createNutrition(500, 100, 50, 50), false); ApiResponse expectedResponse = ApiResponse.success(responseNutritionSumByDateDto, ResponseCode.FOOD_READ_SUCCESS.getMessage()); when(foodService.getNutritionSumByMonth(any(Long.class), any(int.class), any(int.class), any(int.class))).thenReturn(responseNutritionSumByDateDto); From 657081a3425ea0f3ea1176d8609914755e60dd6a Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 2 Dec 2023 13:50:45 +0000 Subject: [PATCH 325/371] :construction_worker: chore: Update deployment to 3889aef0bb258ada901a2c410db174ff125ccbdc --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index f2faeea..cf117f8 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 726434fd + newTag: 3889aef0 From 539f8d827693a0cb5ed714a6e508acd82e113fe8 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 4 Dec 2023 18:25:46 +0900 Subject: [PATCH 326/371] =?UTF-8?q?:ambulance:=20Fix:=20JWT=20=ED=86=A0?= =?UTF-8?q?=ED=81=B0=20=EC=9D=B8=EC=A6=9D=20=ED=99=9C=EC=84=B1=ED=99=94=20?= =?UTF-8?q?=EB=B0=8F=20=EC=9C=A0=ED=9A=A8=EC=8B=9C=EA=B0=84=2012=EC=8B=9C?= =?UTF-8?q?=EA=B0=84=EC=9C=BC=EB=A1=9C=20=ED=99=95=EB=8C=80=20(#131)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/auth/component/JwtTokenProvider.java | 2 +- src/main/java/com/diareat/diareat/config/WebSecurityConfig.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java index cbaa13d..7a56add 100644 --- a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java +++ b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java @@ -39,7 +39,7 @@ public String createToken(String userPk) { return Jwts.builder() .setClaims(claims) // 정보 저장 .setIssuedAt(now) // 토큰 발행 시간 정보 - .setExpiration(new Date(now.getTime() + (360 * 60 * 1000L))) // 토큰 유효시각 설정 (360분) + .setExpiration(new Date(now.getTime() + (720 * 60 * 1000L))) // 토큰 유효시각 설정 (12시간) .signWith(SignatureAlgorithm.HS256, secretKey) // 암호화 알고리즘과, secret 값 .compact(); } diff --git a/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java b/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java index 0ef5736..0bd9f3a 100644 --- a/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java +++ b/src/main/java/com/diareat/diareat/config/WebSecurityConfig.java @@ -28,7 +28,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .and() .authorizeRequests() .antMatchers(AUTH_LIST).permitAll() // swagger 관련 URL은 인증 없이 접근 가능 (테스트용) - .antMatchers("/api/**").permitAll() // 회원가입/로그인 관련 URL은 인증 없이 접근 가능 + .antMatchers("/api/auth/**").permitAll() // 회원가입/로그인 관련 URL은 인증 없이 접근 가능 .anyRequest().authenticated() // 나머지 모든 URL은 Jwt 인증 필요 .and() .addFilterBefore(new JwtAuthFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); From 1b57560e2a4e51408ff7afc28c5b42d3a55efed8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 4 Dec 2023 09:33:12 +0000 Subject: [PATCH 327/371] :construction_worker: chore: Update deployment to 1c5376b2b9d09d9790847297a335acbae8c254e8 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index cf117f8..82465f0 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 3889aef0 + newTag: 1c5376b2 From 7372ee44ed5d71dc41cd0bc7e341ad69e308c94d Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 4 Dec 2023 21:05:33 +0900 Subject: [PATCH 328/371] =?UTF-8?q?:ambulance:=20Fix:=20=EC=9D=8C=EC=8B=9D?= =?UTF-8?q?=EB=AA=85=20=EC=A4=91=EB=B3=B5=EC=97=90=20=EB=8C=80=ED=95=9C=20?= =?UTF-8?q?=EC=98=88=EC=99=B8=EC=B2=98=EB=A6=AC=20=EC=A0=9C=EA=B1=B0=20(#1?= =?UTF-8?q?33)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/food/service/FoodService.java | 9 --------- 1 file changed, 9 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 8689bd1..ec4dcae 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -10,19 +10,14 @@ import com.diareat.diareat.user.dto.response.ResponseRankUserDto; import com.diareat.diareat.user.repository.FollowRepository; import com.diareat.diareat.user.repository.UserRepository; -import com.diareat.diareat.util.MessageUtil; import com.diareat.diareat.util.api.ResponseCode; import com.diareat.diareat.util.exception.FavoriteException; import com.diareat.diareat.util.exception.FoodException; import com.diareat.diareat.util.exception.UserException; 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; -import org.springframework.cache.annotation.Cacheable; import java.time.DayOfWeek; import java.time.LocalDate; @@ -43,10 +38,6 @@ public class FoodService { // @CacheEvict(value = {"ResponseNutritionSumByDateDto"}, key = "#userId+createFoodDto.getDate()", cacheManager = "diareatCacheManager") @Transactional public Long saveFood(CreateFoodDto createFoodDto) { - if (foodRepository.existsByName(createFoodDto.getName())){ - log.info(createFoodDto.getName() + ": 이미 존재하는 음식 이름입니다."); - throw new FoodException(ResponseCode.FOOD_NAME_ALREADY_EXIST); - } User user = getUserById(createFoodDto.getUserId()); Food food = Food.createFood(createFoodDto.getName(), user, createFoodDto.getBaseNutrition(), createFoodDto.getYear(), createFoodDto.getMonth(), createFoodDto.getDay()); log.info("신규 음식 저장: " + food.getName()); From bb80687e3eebcab39bb9f8603403e6a7480b0373 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 4 Dec 2023 13:54:11 +0000 Subject: [PATCH 329/371] :construction_worker: chore: Update deployment to da7210ef49b3a4562faefc5990160f8ea1a430a9 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 82465f0..3249ab3 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 1c5376b2 + newTag: da7210ef From 768f7c1d45bda91b9b2958d0e0d9325af05ac4ce Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Tue, 12 Dec 2023 15:28:16 +0900 Subject: [PATCH 330/371] Create README.md --- README.md | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..e6649b0 --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +# 프로젝트명 +다이어릿 - Diareat (2023.09 ~ 2023.12) + +# Diareat, 사각지대 없는 식습관 관리를 위해! +image + +<다이어릿>은 음식을 촬영하면 칼로리를 대략적으로 계산해주는 기존 서비스에서 영감을 받아, 가공식품의 영양성분표를 촬영하면 칼로리를 추출해주는 OCR 기능을 추가로 결합해 식습관 기록의 사각지대를 해소하는 데 기여하는 Food Capture 서비스입니다. +## Camera + +https://github.com/CAUSOLDOUTMEN/Diareat_backend/assets/53044069/f36dba64-3022-4b1b-b811-d9203fb987b5 + + +- 음식이나 영양성분표를 촬영하면 일정 시간 후 영양성분을 추출하실 수 있습니다. + - 실제 음식의 경우 두잉랩의 foodlens에서 제공하는 외부 API를 사용합니다. + - 영양성분표의 경우 Pororo OCR을 기반으로 자체 구축한 OCR 서버를 활용합니다. +## Diary +image + + +- [오늘의 영양] 화면에서 오늘 촬영한 음식들에 대한 영양분이 실시간으로 결산됩니다. +- [다이어리] 화면에서 오늘 촬영한 음식들에 대한 정보를 확인할 수 있습니다. +- [즐겨찾기] 기능을 통해 자주 먹는 음식을 등록하여 재촬영 없이 편리한 다이어리 추가가 가능합니다. +- [프로필] 화면에서 개인정보 및 목표로 설정된 기준섭취량을 확인하고 직접 수정하실 수 있습니다. + +## Analysis +image + +- [일기 분석] 화면에서 최근 7일 및 4주 간의 영양소별 섭취 현황을 그래프로 제공합니다. +- [자세히 보기]를 통해 이번 주의 구체적인 식습관 점수 현황, 최근 Best, Worst 음식들을 확인하실 수 있습니다. +- [주간 랭킹] 화면에서 검색 기능을 통해 특정 유저를 팔로우 혹은 팔로우 취소할 수 있고, 자신이 팔로우한 유저들의 주간 식습관 점수를 확인하실 수 있습니다. +- 친구들과 함께 앱을 사용하며 식습관 개선 목표를 달성하기 위해 서로 경쟁해보세요! + +# Project Information + +## Members +![image](https://github.com/CAUSOLDOUTMEN/Diareat_backend/assets/53044069/f85d298e-9c12-417b-b2b6-bdbfd5b86bbb) + +## Tech Stack + +### Frontend + +- Android +- Kotlin + +### Backend + +- Java 11 +- Springboot +- Redis +- MySQL + +### OCR Server + +- Python (Pororo OCR) +- OpenCV +- FastAPI +- AWS EC2 + +### Infra & CI/CD + +- Kubernetes +- Argo CD +- Kustomization +- Github actions +- Docker + +## Project **Architecture** +![image](https://github.com/CAUSOLDOUTMEN/Diareat_backend/assets/53044069/21f5deb4-8dce-4cc9-a148-6a78e8370c4e) From a2b472c2dc4d3afa51d1f29e254d76b2a397d0d0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 12 Dec 2023 06:30:10 +0000 Subject: [PATCH 331/371] :construction_worker: chore: Update deployment to 768f7c1d45bda91b9b2958d0e0d9325af05ac4ce --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 3249ab3..e23c648 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: da7210ef + newTag: 768f7c1d From da7aacfec8a8ceb7a61b7e0c1a190ce72b696bde Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 4 Jan 2024 16:51:46 +0900 Subject: [PATCH 332/371] =?UTF-8?q?:art:=20Refactor:=20Jwt->PK=20=EB=A9=94?= =?UTF-8?q?=EC=84=9C=EB=93=9C=20=EC=88=98=EC=A0=95=20=EB=B0=8F=20UserContr?= =?UTF-8?q?oller=EC=97=90=20=EC=A0=81=EC=9A=A9=20(#137)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/component/JwtTokenProvider.java | 6 ++-- .../user/controller/UserController.java | 33 +++++++++++-------- 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java index 7a56add..9bb6aaf 100644 --- a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java +++ b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java @@ -46,13 +46,13 @@ public String createToken(String userPk) { // 인증 정보 조회 public Authentication getAuthentication(String token) { - UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUserPk(token)); + UserDetails userDetails = userDetailsService.loadUserByUsername(String.valueOf(this.getUserPk(token))); return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); } // 토큰에서 회원 정보 추출 - public String getUserPk(String token) { - return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject(); + public Long getUserPk(String token) { + return Long.parseLong(Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject()); } // 토큰 유효성, 만료일자 확인 diff --git a/src/main/java/com/diareat/diareat/user/controller/UserController.java b/src/main/java/com/diareat/diareat/user/controller/UserController.java index 51623bb..06cd27b 100644 --- a/src/main/java/com/diareat/diareat/user/controller/UserController.java +++ b/src/main/java/com/diareat/diareat/user/controller/UserController.java @@ -1,5 +1,6 @@ package com.diareat.diareat.user.controller; +import com.diareat.diareat.auth.component.JwtTokenProvider; import com.diareat.diareat.user.dto.request.SearchUserDto; import com.diareat.diareat.user.dto.request.UpdateUserDto; import com.diareat.diareat.user.dto.request.UpdateUserNutritionDto; @@ -25,18 +26,21 @@ public class UserController { private final UserService userService; + private final JwtTokenProvider jwtTokenProvider; // 회원 기본정보 조회 @Operation(summary = "[프로필] 회원 기본정보 조회", description = "회원 기본정보를 조회합니다.") - @GetMapping("{userId}/info/simple") - public ApiResponse getSimpleUserInfo(@PathVariable Long userId) { + @GetMapping("/info/simple") + public ApiResponse getSimpleUserInfo(@RequestHeader String accessToken) { + Long userId = jwtTokenProvider.getUserPk(accessToken); return ApiResponse.success(userService.getSimpleUserInfo(userId), ResponseCode.USER_CREATE_SUCCESS.getMessage()); } // 회원정보 조회 @Operation(summary = "[프로필] 회원 정보 조회", description = "회원 정보를 조회합니다.") - @GetMapping("{userId}/info") - public ApiResponse getUserInfo(@PathVariable Long userId) { + @GetMapping("/info") + public ApiResponse getUserInfo(@RequestHeader String accessToken) { + Long userId = jwtTokenProvider.getUserPk(accessToken); return ApiResponse.success(userService.getUserInfo(userId), ResponseCode.USER_CREATE_SUCCESS.getMessage()); } @@ -50,14 +54,15 @@ public ApiResponse updateUserInfo(@RequestBody @Valid UpdateUserDto update // 회원 기준섭취량 조회 @Operation(summary = "[프로필] 회원 기준섭취량 조회", description = "회원 기준섭취량을 조회합니다.") - @GetMapping("{userId}/nutrition") - public ApiResponse getUserNutrition(@PathVariable Long userId) { + @GetMapping("/info/nutrition") + public ApiResponse getUserNutrition(@RequestHeader String accessToken) { + Long userId = jwtTokenProvider.getUserPk(accessToken); return ApiResponse.success(userService.getUserNutrition(userId), ResponseCode.USER_READ_SUCCESS.getMessage()); } // 회원 기준섭취량 직접 수정 @Operation(summary = "[프로필] 회원 기준섭취량 직접 수정", description = "회원 기준섭취량을 직접 수정합니다.") - @PutMapping("{userId}/nutrition") + @PutMapping("/info/nutrition") public ApiResponse updateUserNutrition(@RequestBody @Valid UpdateUserNutritionDto updateUserNutritionDto) { userService.updateBaseNutrition(updateUserNutritionDto); return ApiResponse.success(null, ResponseCode.USER_UPDATE_SUCCESS.getMessage()); @@ -72,17 +77,19 @@ public ApiResponse> searchUser(@RequestBody @Valid S // 회원이 특정 회원 팔로우 @Operation(summary = "[주간 랭킹] 회원이 특정 회원 팔로우", description = "회원이 특정 회원을 팔로우합니다.") - @PostMapping("{userId}/follow/{followId}") - public ApiResponse followUser(@PathVariable Long userId, @PathVariable Long followId) { - userService.followUser(userId, followId); + @PostMapping("/follow/{toUserId}") + public ApiResponse followUser(@RequestHeader String accessToken, @PathVariable Long toUserId) { + Long userId = jwtTokenProvider.getUserPk(accessToken); + userService.followUser(userId, toUserId); return ApiResponse.success(null, ResponseCode.USER_FOLLOW_SUCCESS.getMessage()); } // 회원이 특정 회원 팔로우 취소 @Operation(summary = "[주간 랭킹] 회원이 특정 회원 팔로우 취소", description = "회원이 특정 회원을 팔로우 취소합니다.") - @DeleteMapping("{userId}/follow/{followId}") - public ApiResponse unfollowUser(@PathVariable Long userId, @PathVariable Long followId) { - userService.unfollowUser(userId, followId); + @DeleteMapping("/follow/{toUserId}") + public ApiResponse unfollowUser(@RequestHeader String accessToken, @PathVariable Long toUserId) { + Long userId = jwtTokenProvider.getUserPk(accessToken); + userService.unfollowUser(userId, toUserId); return ApiResponse.success(null, ResponseCode.USER_UNFOLLOW_SUCCESS.getMessage()); } } From 95352b1029c00e987f9af24ac5a2f724896faa40 Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 4 Jan 2024 17:10:49 +0900 Subject: [PATCH 333/371] =?UTF-8?q?:recycle:=20User=20=ED=8C=A8=ED=82=A4?= =?UTF-8?q?=EC=A7=80=20ResponseDto=20=EB=B9=8C=EB=8D=94=ED=8C=A8=ED=84=B4?= =?UTF-8?q?=20=EC=A0=81=EC=9A=A9=20(#137)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dto/response/ResponseRankUserDto.java | 10 ++------- .../dto/response/ResponseSearchUserDto.java | 10 ++------- .../dto/response/ResponseSimpleUserDto.java | 10 ++------- .../user/dto/response/ResponseUserDto.java | 15 ++----------- .../response/ResponseUserNutritionDto.java | 21 ++----------------- 5 files changed, 10 insertions(+), 56 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java index cc657a4..bf75c30 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java @@ -2,15 +2,13 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; -import lombok.NoArgsConstructor; import java.io.Serializable; @Getter -@NoArgsConstructor -@AllArgsConstructor +@Builder @JsonSerialize @JsonDeserialize public class ResponseRankUserDto implements Serializable { @@ -23,8 +21,4 @@ public class ResponseRankUserDto implements Serializable { private double proteinScore; private double fatScore; private double totalScore; - - public static ResponseRankUserDto of(Long userId, String name, String image, double calorieScore, double carbohydrateScore, double proteinScore, double fatScore, double totalScore) { - return new ResponseRankUserDto(userId, name, image, calorieScore, carbohydrateScore, proteinScore, fatScore, totalScore); - } } diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java index 919c27b..ab38198 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSearchUserDto.java @@ -2,15 +2,13 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; -import lombok.NoArgsConstructor; import java.io.Serializable; @Getter -@NoArgsConstructor -@AllArgsConstructor +@Builder @JsonSerialize @JsonDeserialize public class ResponseSearchUserDto implements Serializable { @@ -19,8 +17,4 @@ public class ResponseSearchUserDto implements Serializable { private String name; private String image; private boolean follow; // 유저가 이미 팔로우한 유저인지 확인 - - public static ResponseSearchUserDto of(Long userId, String name, String image, boolean isFollow) { - return new ResponseSearchUserDto(userId, name, image, isFollow); - } } diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java index d550575..b60eb53 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseSimpleUserDto.java @@ -2,23 +2,17 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; -import lombok.NoArgsConstructor; import java.io.Serializable; @Getter -@NoArgsConstructor -@AllArgsConstructor +@Builder @JsonSerialize @JsonDeserialize public class ResponseSimpleUserDto implements Serializable { private String name; private String image; - - public static ResponseSimpleUserDto of(String name, String image) { - return new ResponseSimpleUserDto(name, image); - } } diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java index 2625df2..a105340 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserDto.java @@ -1,17 +1,14 @@ package com.diareat.diareat.user.dto.response; -import com.diareat.diareat.user.domain.User; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; -import lombok.NoArgsConstructor; import java.io.Serializable; @Getter -@NoArgsConstructor -@AllArgsConstructor +@Builder @JsonSerialize @JsonDeserialize public class ResponseUserDto implements Serializable { @@ -20,12 +17,4 @@ public class ResponseUserDto implements Serializable { private int height; private int weight; private int age; - - public static ResponseUserDto from(User user) { - return new ResponseUserDto(user.getName(), user.getHeight(), user.getWeight(), user.getAge()); - } - - public static ResponseUserDto of(String name, int height, int weight, int age) { - return new ResponseUserDto(name, height, weight, age); - } } diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java index 6661313..95f742e 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseUserNutritionDto.java @@ -1,17 +1,14 @@ package com.diareat.diareat.user.dto.response; -import com.diareat.diareat.user.domain.User; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; -import lombok.NoArgsConstructor; import java.io.Serializable; @Getter -@NoArgsConstructor -@AllArgsConstructor +@Builder @JsonSerialize @JsonDeserialize public class ResponseUserNutritionDto implements Serializable { @@ -20,18 +17,4 @@ public class ResponseUserNutritionDto implements Serializable { private int carbohydrate; private int protein; private int fat; - - private int defaultCalorie; // 개인정보에 따라 기본적으로 설정되는 영양소 기준섭취량 - private int defaultCarbohydrate; - private int defaultProtein; - private int defaultFat; - - public static ResponseUserNutritionDto of(int calorie, int carbohydrate, int protein, int fat, int defaultCalorie, int defaultCarbohydrate, int defaultProtein, int defaultFat) { - return new ResponseUserNutritionDto(calorie, carbohydrate, protein, fat, defaultCalorie, defaultCarbohydrate, defaultProtein, defaultFat); - } - - public static ResponseUserNutritionDto from(User user, int defaultCalorie, int defaultCarbohydrate, int defaultProtein, int defaultFat) { - return new ResponseUserNutritionDto(user.getBaseNutrition().getKcal(), user.getBaseNutrition().getCarbohydrate(), - user.getBaseNutrition().getProtein(), user.getBaseNutrition().getFat(), defaultCalorie, defaultCarbohydrate, defaultProtein, defaultFat); - } } From 429cbf21157b21a44d4001939c51a249cbb7a597 Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 4 Jan 2024 17:19:46 +0900 Subject: [PATCH 334/371] =?UTF-8?q?:art:=20Refactor:=20UserService=20?= =?UTF-8?q?=EB=B0=98=ED=99=98=20Dto=20=EB=B9=8C=EB=8D=94=ED=8C=A8=ED=84=B4?= =?UTF-8?q?=20=EC=A0=81=EC=9A=A9=20(#137)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/service/UserService.java | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index aaade88..259b749 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -41,7 +41,7 @@ public Long saveUser(CreateUserDto createUserDto) { log.info("이미 존재하는 닉네임입니다 by {}", createUserDto.getName()); throw new UserException(ResponseCode.USER_NAME_ALREADY_EXIST); } - if(userRepository.existsByKeyCode(createUserDto.getKeyCode())) { + if (userRepository.existsByKeyCode(createUserDto.getKeyCode())) { log.info("이미 존재하는 키코드입니다 by {}", createUserDto.getKeyCode()); throw new UserException(ResponseCode.USER_ALREADY_EXIST); } @@ -60,7 +60,10 @@ public Long saveUser(CreateUserDto createUserDto) { public ResponseSimpleUserDto getSimpleUserInfo(Long userId) { User user = getUserById(userId); log.info("{} 회원 기본정보 조회 완료: ", user.getName()); - return ResponseSimpleUserDto.of(user.getName(), user.getImage()); + return ResponseSimpleUserDto.builder() + .name(user.getName()) + .image(user.getImage()) + .build(); } // 회원정보 조회 @@ -69,7 +72,12 @@ public ResponseSimpleUserDto getSimpleUserInfo(Long userId) { public ResponseUserDto getUserInfo(Long userId) { User user = getUserById(userId); log.info("{} 회원정보 조회 완료: ", user.getName()); - return ResponseUserDto.from(user); + return ResponseUserDto.builder() + .name(user.getName()) + .height(user.getHeight()) + .weight(user.getWeight()) + .age(user.getAge()) + .build(); } // 회원정보 수정 @@ -89,9 +97,12 @@ public void updateUserInfo(UpdateUserDto updateUserDto) { public ResponseUserNutritionDto getUserNutrition(Long userId) { User user = getUserById(userId); log.info("{} user 객체 조회 완료: ", user.getName()); - List standard = UserTypeUtil.getStanardByUserType(user.getType()); // 유저 타입에 따른 기본 기준섭취량 조회 - log.info("{} 회원 기준섭취량 조회 완료: ", user.getName()); - return ResponseUserNutritionDto.from(user, standard.get(0), standard.get(2), user.getWeight(), standard.get(1)); // 단백질은 자신 체중 기준으로 계산 + return ResponseUserNutritionDto.builder() + .calorie(user.getBaseNutrition().getKcal()) + .carbohydrate(user.getBaseNutrition().getCarbohydrate()) + .protein(user.getBaseNutrition().getProtein()) + .fat(user.getBaseNutrition().getFat()) + .build(); } // 회원 기준섭취량 직접 수정 @@ -124,7 +135,12 @@ public List searchUser(Long hostId, String name) { log.info("{} 검색 결과 조회 완료", name); users.removeIf(user -> user.getId().equals(hostId)); // 검색 결과에서 자기 자신은 제외 (removeIf 메서드는 ArrayList에만 존재) return users.stream() - .map(user -> ResponseSearchUserDto.of(user.getId(), user.getName(), user.getImage(), followRepository.existsByFromUserAndToUser(hostId, user.getId()))).collect(Collectors.toList()); + .map(user -> ResponseSearchUserDto.builder() + .userId(user.getId()) + .name(user.getName()) + .image(user.getImage()) + .follow(followRepository.existsByFromUserAndToUser(hostId, user.getId())) + .build()).collect(Collectors.toList()); } // 회원이 특정 회원 팔로우 From ef70bf7e87d13fcfcd1f4901ee8ff4bcc89beb2e Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 4 Jan 2024 17:23:33 +0900 Subject: [PATCH 335/371] =?UTF-8?q?:art:=20Refactor:=20=EB=9E=AD=ED=82=B9?= =?UTF-8?q?=20=EA=B4=80=EB=A0=A8=20=EB=B0=98=ED=99=98=20Dto=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1=EB=A9=94=EC=84=9C=EB=93=9C=20=EC=9E=84=EC=8B=9C=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20(#137)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/dto/response/ResponseRankUserDto.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java b/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java index bf75c30..2c7940c 100644 --- a/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java +++ b/src/main/java/com/diareat/diareat/user/dto/response/ResponseRankUserDto.java @@ -21,4 +21,17 @@ public class ResponseRankUserDto implements Serializable { private double proteinScore; private double fatScore; private double totalScore; + + public static ResponseRankUserDto of(Long userId, String name, String image, double calorieScore, double carbohydrateScore, double proteinScore, double fatScore, double totalScore) { + return ResponseRankUserDto.builder() + .userId(userId) + .name(name) + .image(image) + .calorieScore(calorieScore) + .carbohydrateScore(carbohydrateScore) + .proteinScore(proteinScore) + .fatScore(fatScore) + .totalScore(totalScore) + .build(); + } } From 0853d8493e0b587eab4689a49eb91907beb521a2 Mon Sep 17 00:00:00 2001 From: Jiwan Ahn Date: Thu, 4 Jan 2024 22:53:33 +0900 Subject: [PATCH 336/371] :green_heart: chore: Update manifest.yaml --- k8s/manifest.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/manifest.yaml b/k8s/manifest.yaml index ec3458e..b33742d 100644 --- a/k8s/manifest.yaml +++ b/k8s/manifest.yaml @@ -23,7 +23,7 @@ spec: resources: requests: memory: "2G" - cpu: 0.4 + cpu: 0.2 limits: memory: "4G" cpu: 1 From d989f077fece33f44b6d06cea5d61a0219a20ac8 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 5 Jan 2024 16:09:49 +0900 Subject: [PATCH 337/371] =?UTF-8?q?:art:=20Refactor:=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=EC=BD=94=EB=93=9C=20jwt=20=EC=9D=B8=EC=A6=9D=20?= =?UTF-8?q?=EB=A9=B4=EC=A0=9C=ED=95=98=EB=8F=84=EB=A1=9D=20TestConfig=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20(#137)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/config/TestConfig.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/test/java/com/diareat/diareat/config/TestConfig.java diff --git a/src/test/java/com/diareat/diareat/config/TestConfig.java b/src/test/java/com/diareat/diareat/config/TestConfig.java new file mode 100644 index 0000000..d90bdbc --- /dev/null +++ b/src/test/java/com/diareat/diareat/config/TestConfig.java @@ -0,0 +1,19 @@ +package com.diareat.diareat.config; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.web.SecurityFilterChain; + +@TestConfiguration +public class TestConfig { + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http + .csrf().disable() + .authorizeRequests() + .anyRequest().permitAll(); + return http.build(); + } +} From 57b0832eac51e217c5e7e9d705b365c4d53c7455 Mon Sep 17 00:00:00 2001 From: CHAE Date: Fri, 5 Jan 2024 16:10:18 +0900 Subject: [PATCH 338/371] =?UTF-8?q?:art:=20Refactor:=20UserControllerTest?= =?UTF-8?q?=20jwt=20=EA=B4=80=EB=A0=A8=20=EB=A6=AC=ED=8C=A9=ED=86=A0?= =?UTF-8?q?=EB=A7=81=20(#137)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/UserControllerTest.java | 143 +++++++++++++----- 1 file changed, 103 insertions(+), 40 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java index d8b1b37..76247a4 100644 --- a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java @@ -1,5 +1,7 @@ package com.diareat.diareat.controller; +import com.diareat.diareat.auth.component.JwtTokenProvider; +import com.diareat.diareat.config.TestConfig; import com.diareat.diareat.user.controller.UserController; import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; @@ -21,8 +23,11 @@ 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.context.annotation.Import; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; +import org.springframework.security.authentication.TestingAuthenticationToken; +import org.springframework.security.core.Authentication; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @@ -34,29 +39,45 @@ import java.util.List; import static org.mockito.Mockito.*; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; @WebMvcTest(controllers = UserController.class) +@Import(TestConfig.class) class UserControllerTest { @Autowired - private MockMvc mockMvc; + private MockMvc mockMvc; @Autowired private WebApplicationContext webApplicationContext; + @MockBean + private JwtTokenProvider jwtTokenProvider; + @MockBean private UserService userService; private final Long testUserId = 1L; 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 User testUser = User.createUser("test", "test", "test", 180, 70, 0, 20, BaseNutrition.createNutrition(2000, 300, 80, 80)); + private final Authentication authentication = new TestingAuthenticationToken(1L, null, "ROLE_USER"); @BeforeEach void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); testUser.setId(testUserId); - when(userService.getSimpleUserInfo(testUserId)).thenReturn(ResponseSimpleUserDto.of(testUser.getName(), testUser.getImage())); - when(userService.getUserInfo(testUserId)).thenReturn(ResponseUserDto.from(testUser)); + when(userService.getSimpleUserInfo(any(Long.class))) + .thenReturn(ResponseSimpleUserDto.builder() + .name(testUser.getName()) + .image(testUser.getImage()) + .build()); + when(userService.getUserInfo(any(Long.class))) + .thenReturn(ResponseUserDto.builder() + .name(testUser.getName()) + .height(testUser.getHeight()) + .weight(testUser.getWeight()) + .age(testUser.getAge()) + .build()); } @DisplayName("회원 기본정보 조회") @@ -65,12 +86,18 @@ void setUp() { void testGetSimpleUserInfo() throws Exception { // Given ApiResponse expectedResponse = ApiResponse.success( - ResponseSimpleUserDto.of(testUser.getName(), testUser.getImage()), ResponseCode.USER_CREATE_SUCCESS.getMessage()); + ResponseSimpleUserDto.builder() + .name(testUser.getName()) + .image(testUser.getImage()) + .build() + , ResponseCode.USER_CREATE_SUCCESS.getMessage()); // When & Then - mockMvc.perform( MockMvcRequestBuilders - .get("/api/user/1/info/simple", 1L) - .accept(MediaType.APPLICATION_JSON)) + mockMvc.perform(MockMvcRequestBuilders + .get("/api/user/info/simple") + .header("accessToken", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE3MDQ0MzgxMDQsImV4cCI6MTczNTk3NDEwNCwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5hbWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.ApqSkkS8DqNG_H9abjJMRrzxONDj59cVGugJxPM_nBg") + .accept(MediaType.APPLICATION_JSON) + .with(authentication(authentication))) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) @@ -84,12 +111,20 @@ void testGetSimpleUserInfo() throws Exception { void getUserInfo() throws Exception { // Given ApiResponse expectedResponse = ApiResponse.success( - ResponseUserDto.from(testUser), ResponseCode.USER_CREATE_SUCCESS.getMessage()); + ResponseUserDto.builder() + .name(testUser.getName()) + .height(testUser.getHeight()) + .weight(testUser.getWeight()) + .age(testUser.getAge()) + .build() + , ResponseCode.USER_CREATE_SUCCESS.getMessage()); // When & Then - mockMvc.perform( MockMvcRequestBuilders - .get("/api/user/1/info", 1L) - .accept(MediaType.APPLICATION_JSON)) + mockMvc.perform(MockMvcRequestBuilders + .get("/api/user/info") + .header("accessToken", "test") + .accept(MediaType.APPLICATION_JSON) + .with(authentication(authentication))) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) @@ -109,7 +144,7 @@ void updateUser() throws Exception { String json = mapper.writeValueAsString(user); // When & Then - mockMvc.perform( MockMvcRequestBuilders + mockMvc.perform(MockMvcRequestBuilders .put("/api/user/update") .contentType(MediaType.APPLICATION_JSON) .content(json) @@ -129,12 +164,12 @@ void updateUserFail() throws Exception { String json = mapper.writeValueAsString(user); // When & Then - mockMvc.perform( MockMvcRequestBuilders + mockMvc.perform(MockMvcRequestBuilders .put("/api/user/update") .contentType(MediaType.APPLICATION_JSON) .content(json) .accept(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isBadRequest()) + .andExpect(MockMvcResultMatchers.status().isBadRequest()) .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(HttpStatus.BAD_REQUEST.value())) .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(ResponseCode.BAD_REQUEST.getMessage())) .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(ResponseCode.BAD_REQUEST.getMessage())) @@ -148,25 +183,36 @@ void updateUserFail() throws Exception { @WithMockUser("test") void getUserNutrition() throws Exception { // Given - when(userService.getUserNutrition(testUserId)).thenReturn(ResponseUserNutritionDto.of(2000, 300, 300, 80, 1000, 200, 200, 60)); + when(userService.getUserNutrition(any(Long.class))).thenReturn( + ResponseUserNutritionDto.builder() + .calorie(2000) + .protein(300) + .fat(300) + .carbohydrate(80) + .build() + ); ApiResponse expectedResponse = ApiResponse.success( - ResponseUserNutritionDto.of(2000, 300, 300, 80, 1000, 200, 200, 60), ResponseCode.USER_READ_SUCCESS.getMessage()); + ResponseUserNutritionDto.builder() + .calorie(2000) + .protein(300) + .fat(300) + .carbohydrate(80) + .build(), + ResponseCode.USER_READ_SUCCESS.getMessage()); // When & Then - mockMvc.perform( MockMvcRequestBuilders - .get("/api/user/1/nutrition", 1L) - .accept(MediaType.APPLICATION_JSON)) + mockMvc.perform(MockMvcRequestBuilders + .get("/api/user/info/nutrition") + .header("accessToken", "test") + .accept(MediaType.APPLICATION_JSON) + .with(authentication(authentication))) .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.calorie").value(expectedResponse.getData().getCalorie())) .andExpect(MockMvcResultMatchers.jsonPath("$.data.protein").value(expectedResponse.getData().getProtein())) .andExpect(MockMvcResultMatchers.jsonPath("$.data.fat").value(expectedResponse.getData().getFat())) - .andExpect(MockMvcResultMatchers.jsonPath("$.data.carbohydrate").value(expectedResponse.getData().getCarbohydrate())) - .andExpect(MockMvcResultMatchers.jsonPath("$.data.defaultCalorie").value(expectedResponse.getData().getDefaultCalorie())) - .andExpect(MockMvcResultMatchers.jsonPath("$.data.defaultProtein").value(expectedResponse.getData().getDefaultProtein())) - .andExpect(MockMvcResultMatchers.jsonPath("$.data.defaultFat").value(expectedResponse.getData().getDefaultFat())) - .andExpect(MockMvcResultMatchers.jsonPath("$.data.defaultCarbohydrate").value(expectedResponse.getData().getDefaultCarbohydrate())); + .andExpect(MockMvcResultMatchers.jsonPath("$.data.carbohydrate").value(expectedResponse.getData().getCarbohydrate())); } @DisplayName("회원 기준섭취량 직접 수정") @@ -179,11 +225,12 @@ void updateUserNutrition() throws Exception { String json = mapper.writeValueAsString(nutrition); // When & Then - mockMvc.perform( MockMvcRequestBuilders - .put("/api/user/1/nutrition") + mockMvc.perform(MockMvcRequestBuilders + .put("/api/user/info/nutrition") .contentType(MediaType.APPLICATION_JSON) .content(json) - .accept(MediaType.APPLICATION_JSON)) + .accept(MediaType.APPLICATION_JSON) + .with(authentication(authentication))) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(expectedResponse.getHeader().getMessage())) @@ -199,12 +246,13 @@ void updateUserNutritionFail() throws Exception { String json = mapper.writeValueAsString(nutrition); // When & Then - mockMvc.perform( MockMvcRequestBuilders - .put("/api/user/1/nutrition") + mockMvc.perform(MockMvcRequestBuilders + .put("/api/user/info/nutrition") .contentType(MediaType.APPLICATION_JSON) .content(json) - .accept(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isBadRequest()) + .accept(MediaType.APPLICATION_JSON) + .with(authentication(authentication))) + .andExpect(MockMvcResultMatchers.status().isBadRequest()) .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(HttpStatus.BAD_REQUEST.value())) .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(ResponseCode.BAD_REQUEST.getMessage())) .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(ResponseCode.BAD_REQUEST.getMessage())) @@ -213,19 +261,33 @@ void updateUserNutritionFail() throws Exception { .andExpect(MockMvcResultMatchers.jsonPath("$.data.fat").value(MessageUtil.FAT_RANGE)) .andExpect(MockMvcResultMatchers.jsonPath("$.data.carbohydrate").value(MessageUtil.CARBOHYDRATE_RANGE)); } + @DisplayName("회원의 친구 검색 결과 조회") @Test @WithMockUser("test") void searchUser() throws Exception { // Given - when(userService.searchUser(testUserId, "test")).thenReturn(List.of(ResponseSearchUserDto.of(2L, "test2", "test2", true))); + when(userService.searchUser(testUserId, "test")) + .thenReturn(List.of(ResponseSearchUserDto.builder() + .userId(2L) + .name("test2") + .image("test2") + .follow(true) + .build())); ApiResponse> expectedResponse = ApiResponse.success( - List.of(ResponseSearchUserDto.of(2L, "test2", "test2", true)), ResponseCode.USER_SEARCH_SUCCESS.getMessage()); + List.of(ResponseSearchUserDto.builder() + .userId(2L) + .name("test2") + .image("test2") + .follow(true) + .build() + ), + ResponseCode.USER_SEARCH_SUCCESS.getMessage()); SearchUserDto searchDto = SearchUserDto.of(testUserId, "test"); String json = mapper.writeValueAsString(searchDto); // When & Then - mockMvc.perform( MockMvcRequestBuilders + mockMvc.perform(MockMvcRequestBuilders .post("/api/user/search") .contentType(MediaType.APPLICATION_JSON) .content(json) @@ -248,12 +310,13 @@ void searchUserFail() throws Exception { String json = mapper.writeValueAsString(searchDto); // When & Then - mockMvc.perform( MockMvcRequestBuilders + mockMvc.perform(MockMvcRequestBuilders .post("/api/user/search") + .header("accessToken", "test") .contentType(MediaType.APPLICATION_JSON) .content(json) .accept(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isBadRequest()) + .andExpect(MockMvcResultMatchers.status().isBadRequest()) .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(HttpStatus.BAD_REQUEST.value())) .andExpect(MockMvcResultMatchers.jsonPath("$.header.message").value(ResponseCode.BAD_REQUEST.getMessage())) .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value(ResponseCode.BAD_REQUEST.getMessage())) @@ -268,9 +331,9 @@ void followUser() throws Exception { ApiResponse expectedResponse = ApiResponse.success(null, ResponseCode.USER_FOLLOW_SUCCESS.getMessage()); // When & Then - mockMvc.perform( MockMvcRequestBuilders - .post("/api/user/1/follow/2") - //.delete("/api/user/1/follow/2") + mockMvc.perform(MockMvcRequestBuilders + .post("/api/user/follow/2") + .header("accessToken", "test") .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) From ac2d1ba794c4dcf1975f8b10050c1028880b084a Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 5 Jan 2024 12:36:17 +0000 Subject: [PATCH 339/371] :construction_worker: chore: Update deployment to 4f1c4fc06bdbb7fe52248b6bf3038c382155ec18 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index e23c648..c135dec 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 768f7c1d + newTag: 4f1c4fc0 From 94a194d38d78752ae7781f1d41c5a1b13a2ab00b Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sat, 6 Jan 2024 21:16:53 +0900 Subject: [PATCH 340/371] =?UTF-8?q?:sparkles:=20feat:=20AuditingEntityList?= =?UTF-8?q?ener=EC=9D=84=20=ED=86=B5=ED=95=B4=20=EC=9D=8C=EC=8B=9D=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1=20=EC=8B=9C=EA=B0=84=20=EC=9E=90=EB=8F=99=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1=20(#140)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/DiareatApplication.java | 2 ++ src/main/java/com/diareat/diareat/food/domain/Food.java | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/DiareatApplication.java b/src/main/java/com/diareat/diareat/DiareatApplication.java index 77eece4..11a071c 100644 --- a/src/main/java/com/diareat/diareat/DiareatApplication.java +++ b/src/main/java/com/diareat/diareat/DiareatApplication.java @@ -3,11 +3,13 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import javax.annotation.PostConstruct; import java.util.TimeZone; @EnableCaching +@EnableJpaAuditing @SpringBootApplication public class DiareatApplication { 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 3eeb200..13f0aac 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -5,6 +5,8 @@ import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import java.time.LocalDate; @@ -13,6 +15,7 @@ @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @Entity +@EntityListeners(AuditingEntityListener.class) public class Food { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -33,6 +36,7 @@ public class Food { private LocalDate date; + @CreatedDate @Column(name = "added_time") //테이블과 매핑 private LocalDateTime addedTime; //클라이언트에서 추가하도록 요청 보낸 timestamp @@ -44,7 +48,6 @@ public static Food createFood(String name, User user, BaseNutrition baseNutritio food.name = name; food.user = user; food.date = LocalDate.of(year, month, day); - food.addedTime = LocalDateTime.now(); food.baseNutrition = baseNutrition; return food; From 254eec2260f5d96303f764f1b91d7443a51d0dde Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 7 Jan 2024 00:25:21 +0900 Subject: [PATCH 341/371] =?UTF-8?q?:recycle:=20refactor:=20Builder=20?= =?UTF-8?q?=ED=8C=A8=ED=84=B4=20=EC=A0=81=EC=9A=A9=20(#140)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/food/domain/Food.java | 1 + .../diareat/food/dto/ResponseAnalysisDto.java | 2 + .../food/dto/ResponseFavoriteFoodDto.java | 2 + .../diareat/food/dto/ResponseFoodDto.java | 2 + .../diareat/food/dto/ResponseFoodRankDto.java | 2 + .../dto/ResponseNutritionSumByDateDto.java | 2 + .../food/dto/ResponseScoreBestWorstDto.java | 2 + .../food/dto/ResponseSimpleFoodDto.java | 2 + .../diareat/food/service/FoodService.java | 107 +++++++++++++++--- 9 files changed, 105 insertions(+), 17 deletions(-) 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 13f0aac..fa9ab46 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -3,6 +3,7 @@ import com.diareat.diareat.user.domain.BaseNutrition; import com.diareat.diareat.user.domain.User; import lombok.AccessLevel; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import org.springframework.data.annotation.CreatedDate; diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java index 7d94a36..8780f35 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseAnalysisDto.java @@ -1,6 +1,7 @@ package com.diareat.diareat.food.dto; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @@ -9,6 +10,7 @@ import java.util.Map; @Getter +@Builder @NoArgsConstructor @AllArgsConstructor public class ResponseAnalysisDto { // 그래프 + 점수에 사용되는 DTO 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 5e4c41f..90c0f67 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFavoriteFoodDto.java @@ -3,10 +3,12 @@ import com.diareat.diareat.food.domain.FavoriteFood; import com.diareat.diareat.user.domain.BaseNutrition; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @Getter +@Builder @NoArgsConstructor @AllArgsConstructor public class ResponseFavoriteFoodDto { diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java index 6c01c5b..91a6878 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java @@ -3,6 +3,7 @@ import com.diareat.diareat.food.domain.Food; import com.diareat.diareat.user.domain.BaseNutrition; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @@ -10,6 +11,7 @@ import java.time.LocalTime; @Getter +@Builder @AllArgsConstructor @NoArgsConstructor public class ResponseFoodDto { 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 d54b8d0..a55a648 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java @@ -1,6 +1,7 @@ package com.diareat.diareat.food.dto; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @@ -8,6 +9,7 @@ import java.util.List; @Getter +@Builder @NoArgsConstructor @AllArgsConstructor public class ResponseFoodRankDto { diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java index 17e7dd3..9eb8630 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseNutritionSumByDateDto.java @@ -2,6 +2,7 @@ import com.diareat.diareat.user.domain.BaseNutrition; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @@ -9,6 +10,7 @@ import java.time.LocalDate; @Getter +@Builder @NoArgsConstructor @AllArgsConstructor public class ResponseNutritionSumByDateDto implements Serializable { diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java index 7f12af0..3a5bea1 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java @@ -1,12 +1,14 @@ package com.diareat.diareat.food.dto; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import java.util.List; @Getter +@Builder @NoArgsConstructor @AllArgsConstructor public class ResponseScoreBestWorstDto { // 일기 분석 자세히보기에 사용되는 DTO diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java index 2160e67..d3cfedb 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java @@ -2,12 +2,14 @@ import com.diareat.diareat.food.domain.Food; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import java.time.LocalDate; @Getter +@Builder @NoArgsConstructor @AllArgsConstructor public class ResponseSimpleFoodDto { // Best 3 and Worst 3에 사용될 객체 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 ec4dcae..fb7f21e 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -51,7 +51,16 @@ public List getFoodListByDate(Long userId, LocalDate date){ List foodList = foodRepository.findAllByUserIdAndDateOrderByAddedTimeAsc(userId, date); log.info(date.toString() + "의 "+ userId + "에게 조회된 음식 개수: " + foodList.size() + "개"); return foodList.stream() - .map(food -> ResponseFoodDto.of(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite(), food.getAddedTime().getHour(), food.getAddedTime().getMinute())).collect(Collectors.toList()); + .map(food -> ResponseFoodDto.builder() + .foodId(food.getId()) + .userId(food.getUser().getId()) + .name(food.getName()) + .baseNutrition(food.getBaseNutrition()) + .favoriteChecked(food.isFavorite()) + .hour(food.getAddedTime().getHour()) + .minute(food.getAddedTime().getMinute()) + .build()) + .collect(Collectors.toList()); } // 음식 정보 수정 @@ -101,8 +110,13 @@ public List getFavoriteFoodList(Long userId){ List foodList = favoriteFoodRepository.findAllByUserId(userId); log.info(userId + "의 즐겨찾기 음식 개수: " + foodList.size() + "개 조회 완료"); return foodList.stream() - .map(favoriteFood -> ResponseFavoriteFoodDto.of(favoriteFood.getId(),favoriteFood.getName(), - favoriteFood.getBaseNutrition(), favoriteFood.getCount())).collect(Collectors.toList()); + .map(favoriteFood -> ResponseFavoriteFoodDto.builder() + .favoriteFoodId(favoriteFood.getId()) + .name(favoriteFood.getName()) + .baseNutrition(favoriteFood.getBaseNutrition()) + .count(favoriteFood.getCount()) + .build()) + .collect(Collectors.toList()); } // 즐겨찾기 음식 수정 @@ -171,10 +185,22 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId, int year, int month, i // ** Best 3 기준 논의 필요 ** 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); + .map(food -> ResponseSimpleFoodDto.builder() + .name(food.getName()) + .calorie(food.getBaseNutrition().getKcal()) + .carbohydrate(food.getBaseNutrition().getCarbohydrate()) + .protein(food.getBaseNutrition().getProtein()) + .fat(food.getBaseNutrition().getFat()) + .date(food.getDate()) + .build()) + .collect(Collectors.toList()); + + return ResponseFoodRankDto.builder() + .userId(userId) + .rankFoodList(top3FoodsDtoList) + .startDate(endDate.minusWeeks(1)) + .isBest(true) + .build(); } @Transactional(readOnly = true) @@ -195,10 +221,22 @@ public ResponseFoodRankDto getWorstFoodByWeek(Long userId, int year, int month, // 우선 임시로 지방 비율을 높게 설정 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); + .map(food -> ResponseSimpleFoodDto.builder() + .name(food.getName()) + .calorie(food.getBaseNutrition().getKcal()) + .carbohydrate(food.getBaseNutrition().getCarbohydrate()) + .protein(food.getBaseNutrition().getProtein()) + .fat(food.getBaseNutrition().getFat()) + .date(food.getDate()) + .build()) + .collect(Collectors.toList()); + + return ResponseFoodRankDto.builder() + .userId(userId) + .rankFoodList(worst3FoodDtoList) + .startDate(endDate.minusWeeks(1)) + .isBest(false) + .build(); } // 잔여 기능 구현 부분 @@ -228,7 +266,14 @@ public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId List simpleBestFoodList = getBestFoodByWeek(userId, year, month, day).getRankFoodList(); List simpleWorstFoodList = getWorstFoodByWeek(userId, year, month, day).getRankFoodList(); - return ResponseScoreBestWorstDto.of(kcalScore, carbohydrateScore, proteinScore, fatScore, totalScore, simpleBestFoodList, simpleWorstFoodList); + return ResponseScoreBestWorstDto.builder() + .totalScore(totalScore) + .carbohydrateScore(carbohydrateScore) + .proteinScore(proteinScore) + .fatScore(fatScore) + .best(simpleBestFoodList) + .worst(simpleWorstFoodList) + .build(); } @@ -300,7 +345,17 @@ public ResponseAnalysisDto getAnalysisOfUser(Long userId, int year, int month, i totalWeekScore = Math.round(totalWeekScore * 100.0) / 100.0; - return ResponseAnalysisDto.of(totalWeekScore, calorieLastSevenDays, calorieLastFourWeek, carbohydrateLastSevenDays, carbohydrateLastFourWeek, proteinLastSevenDays, proteinLastFourWeek, fatLastSevenDays, fatLastFourWeek); + return ResponseAnalysisDto.builder() + .totalScore(totalWeekScore) + .calorieLastSevenDays(calorieLastSevenDays) + .calorieLastFourWeek(calorieLastFourWeek) + .carbohydrateLastSevenDays(carbohydrateLastSevenDays) + .carbohydrateLastFourWeek(carbohydrateLastFourWeek) + .proteinLastSevenDays(proteinLastSevenDays) + .proteinLastFourWeek(proteinLastFourWeek) + .fatLastSevenDays(fatLastSevenDays) + .fatLastFourWeek(fatLastFourWeek) + .build(); } @@ -374,7 +429,14 @@ private ResponseRankUserDto calculateUserScoreThisWeek(User targetUser, LocalDat kcalScore += calculateNutriRatioAndScore(totalKcal, targetUser.getBaseNutrition().getKcal(), 1); } totalScore = (kcalScore + carbohydrateScore + proteinScore + fatScore); - return ResponseRankUserDto.of(targetUser.getId(), targetUser.getName(), targetUser.getImage(), kcalScore, carbohydrateScore, proteinScore, fatScore, totalScore); + return ResponseRankUserDto.builder() + .userId(targetUser.getId()) + .totalScore(totalScore) + .calorieScore(kcalScore) + .carbohydrateScore(carbohydrateScore) + .proteinScore(proteinScore) + .fatScore(fatScore) + .build(); } private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, List foodList, LocalDate checkDate, int nutritionSumType, @@ -398,9 +460,20 @@ private ResponseNutritionSumByDateDto calculateNutritionSumAndRatio(Long userId, double ratioProtein = Math.round((((double) totalProtein / (double) targetUser.getBaseNutrition().getProtein()) * 100.0) * 10.0) / 10.0; double ratioFat = Math.round((((double) totalFat / (double) targetUser.getBaseNutrition().getFat()) * 100.0) * 10.0) / 10.0; - return ResponseNutritionSumByDateDto.of(userId, checkDate, nutritionSumType, totalKcal, - totalCarbohydrate, totalProtein, totalFat, ratioKcal, - ratioCarbohydrate, ratioProtein, ratioFat, targetUser.getBaseNutrition(), isEmpty); + return ResponseNutritionSumByDateDto.builder() + .userId(userId) + .nutritionSumType(nutritionSumType) + .totalKcal(totalKcal) + .totalCarbohydrate(totalCarbohydrate) + .totalProtein(totalProtein) + .totalFat(totalFat) + .ratioKcal(ratioKcal) + .ratioCarbohydrate(ratioCarbohydrate) + .ratioProtein(ratioProtein) + .ratioFat(ratioFat) + .baseNutrition(targetUser.getBaseNutrition()) + .isEmpty(isEmpty) + .build(); } private void validateUser(Long userId) { From 785533528b44e43f6473f4ad857283aac2fe94d4 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Sun, 7 Jan 2024 22:45:44 +0900 Subject: [PATCH 342/371] =?UTF-8?q?:recycle:=20refactor:=20responseSimpleF?= =?UTF-8?q?oodDto=20=EC=82=AD=EC=A0=9C=20=EB=B0=8F=20=EA=B8=B0=EC=A1=B4=20?= =?UTF-8?q?Dto=EB=A1=9C=20=ED=86=B5=ED=95=A9=20(#140)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/dto/ResponseFoodDto.java | 20 ++++++++++-- .../diareat/food/dto/ResponseFoodRankDto.java | 4 +-- .../food/dto/ResponseScoreBestWorstDto.java | 6 ++-- .../food/dto/ResponseSimpleFoodDto.java | 32 ------------------- .../diareat/food/service/FoodService.java | 24 +++++--------- 5 files changed, 31 insertions(+), 55 deletions(-) delete mode 100644 src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java index 91a6878..ca0ee26 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodDto.java @@ -25,10 +25,26 @@ public class ResponseFoodDto { private int minute; public static ResponseFoodDto of(Long foodId, Long userId, String name, BaseNutrition baseNutrition, boolean favoriteChecked, int hour, int minute) { - return new ResponseFoodDto(foodId, userId, name, baseNutrition, favoriteChecked, hour, minute); + return ResponseFoodDto.builder() + .foodId(foodId) + .userId(userId) + .name(name) + .baseNutrition(baseNutrition) + .favoriteChecked(favoriteChecked) + .hour(hour) + .minute(minute) + .build(); } public static ResponseFoodDto from(Food food) { - return new ResponseFoodDto(food.getId(), food.getUser().getId(), food.getName(), food.getBaseNutrition(), food.isFavorite(), food.getAddedTime().getHour(), food.getAddedTime().getMinute()); + return ResponseFoodDto.builder() + .foodId(food.getId()) + .userId(food.getUser().getId()) + .name(food.getName()) + .baseNutrition(food.getBaseNutrition()) + .favoriteChecked(food.isFavorite()) + .hour(food.getAddedTime().getHour()) + .minute(food.getAddedTime().getMinute()) + .build(); } } 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 a55a648..29fcf45 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseFoodRankDto.java @@ -15,11 +15,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/dto/ResponseScoreBestWorstDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java index 3a5bea1..aa03997 100644 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java +++ b/src/main/java/com/diareat/diareat/food/dto/ResponseScoreBestWorstDto.java @@ -18,10 +18,10 @@ public class ResponseScoreBestWorstDto { // 일기 분석 자세히보기에 사 private double proteinScore; private double fatScore; private double totalScore; - private List best; - private List worst; + private List best; + private List worst; - public static ResponseScoreBestWorstDto of(double calorieScore, double carbohydrateScore, double proteinScore, double fatScore, double totalScore, List best, List worst) { + public static ResponseScoreBestWorstDto of(double calorieScore, double carbohydrateScore, double proteinScore, double fatScore, double totalScore, List best, List worst) { return new ResponseScoreBestWorstDto(calorieScore, carbohydrateScore, proteinScore, fatScore, totalScore, best, worst); } } diff --git a/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java b/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java deleted file mode 100644 index d3cfedb..0000000 --- a/src/main/java/com/diareat/diareat/food/dto/ResponseSimpleFoodDto.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.diareat.diareat.food.dto; - -import com.diareat.diareat.food.domain.Food; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; - -import java.time.LocalDate; - -@Getter -@Builder -@NoArgsConstructor -@AllArgsConstructor -public class ResponseSimpleFoodDto { // Best 3 and Worst 3에 사용될 객체 - - private String name; - private double calorie; - private double carbohydrate; - private double protein; - private double fat; - private LocalDate date; - - public static ResponseSimpleFoodDto of(String name, double calorie, double carbohydrate, double protein, double fat, LocalDate date) { - return new ResponseSimpleFoodDto(name, calorie, carbohydrate, protein, fat, date); - } - - public static ResponseSimpleFoodDto from(Food food) { - return new ResponseSimpleFoodDto(food.getName(), food.getBaseNutrition().getKcal(), food.getBaseNutrition().getCarbohydrate(), - food.getBaseNutrition().getProtein(), food.getBaseNutrition().getFat(), food.getDate()); - } -} 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 fb7f21e..4bd28c0 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -184,14 +184,10 @@ public ResponseFoodRankDto getBestFoodByWeek(Long userId, int year, int month, i //사용한 기준은, 고단백과 저지방의 점수 반영 비율을 7:3으로 측정하고, 단백질량이 높을 수록, 지방량이 낮을 수록 점수가 높음. 이후, 내림차순 정렬 // ** Best 3 기준 논의 필요 ** - List top3FoodsDtoList = top3Foods.stream() - .map(food -> ResponseSimpleFoodDto.builder() + List top3FoodsDtoList = top3Foods.stream() + .map(food -> ResponseFoodDto.builder() .name(food.getName()) - .calorie(food.getBaseNutrition().getKcal()) - .carbohydrate(food.getBaseNutrition().getCarbohydrate()) - .protein(food.getBaseNutrition().getProtein()) - .fat(food.getBaseNutrition().getFat()) - .date(food.getDate()) + .baseNutrition(food.getBaseNutrition()) .build()) .collect(Collectors.toList()); @@ -220,14 +216,10 @@ public ResponseFoodRankDto getWorstFoodByWeek(Long userId, int year, int month, // ** 이점은 논의가 필요할 듯? ** // 우선 임시로 지방 비율을 높게 설정 - List worst3FoodDtoList = worst3Foods.stream() - .map(food -> ResponseSimpleFoodDto.builder() + List worst3FoodDtoList = worst3Foods.stream() + .map(food -> ResponseFoodDto.builder() .name(food.getName()) - .calorie(food.getBaseNutrition().getKcal()) - .carbohydrate(food.getBaseNutrition().getCarbohydrate()) - .protein(food.getBaseNutrition().getProtein()) - .fat(food.getBaseNutrition().getFat()) - .date(food.getDate()) + .baseNutrition(food.getBaseNutrition()) .build()) .collect(Collectors.toList()); @@ -263,8 +255,8 @@ public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId //Dto의 형식에 맞게 Best3와 Worst3 음식 계산 - List simpleBestFoodList = getBestFoodByWeek(userId, year, month, day).getRankFoodList(); - List simpleWorstFoodList = getWorstFoodByWeek(userId, year, month, day).getRankFoodList(); + List simpleBestFoodList = getBestFoodByWeek(userId, year, month, day).getRankFoodList(); + List simpleWorstFoodList = getWorstFoodByWeek(userId, year, month, day).getRankFoodList(); return ResponseScoreBestWorstDto.builder() .totalScore(totalScore) From b2eb9381ac1cf6b03284cd0d04b0bcd6b632bdd5 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 8 Jan 2024 00:06:41 +0900 Subject: [PATCH 343/371] =?UTF-8?q?:bug:=20fix:=20Builder=20=ED=8C=A8?= =?UTF-8?q?=ED=84=B4=20=EC=A4=91=20=EB=88=84=EB=9D=BD=EB=90=9C=20=EC=9A=94?= =?UTF-8?q?=EC=86=8C=20=EC=B6=94=EA=B0=80=20(#140)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/food/service/FoodService.java | 2 ++ 1 file changed, 2 insertions(+) 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 4bd28c0..a45454e 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -260,6 +260,7 @@ public ResponseScoreBestWorstDto getScoreOfUserWithBestAndWorstFoods(Long userId return ResponseScoreBestWorstDto.builder() .totalScore(totalScore) + .calorieScore(kcalScore) .carbohydrateScore(carbohydrateScore) .proteinScore(proteinScore) .fatScore(fatScore) @@ -423,6 +424,7 @@ private ResponseRankUserDto calculateUserScoreThisWeek(User targetUser, LocalDat totalScore = (kcalScore + carbohydrateScore + proteinScore + fatScore); return ResponseRankUserDto.builder() .userId(targetUser.getId()) + .name(targetUser.getName()) .totalScore(totalScore) .calorieScore(kcalScore) .carbohydrateScore(carbohydrateScore) From bd552537124eeaf0f1b734bd3022ad9a2aef34ce Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 8 Jan 2024 00:10:55 +0900 Subject: [PATCH 344/371] =?UTF-8?q?:bug:=20fix:=20WebMvcTest=EB=A1=9C=20?= =?UTF-8?q?=EC=9D=B8=ED=95=B4=20JpaAuditingConfig=20=EB=B6=84=EB=A6=AC=20(?= =?UTF-8?q?#140)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/DiareatApplication.java | 1 - .../com/diareat/diareat/config/JpaAuditingConfig.java | 9 +++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/diareat/diareat/config/JpaAuditingConfig.java diff --git a/src/main/java/com/diareat/diareat/DiareatApplication.java b/src/main/java/com/diareat/diareat/DiareatApplication.java index 11a071c..bb6db32 100644 --- a/src/main/java/com/diareat/diareat/DiareatApplication.java +++ b/src/main/java/com/diareat/diareat/DiareatApplication.java @@ -9,7 +9,6 @@ import java.util.TimeZone; @EnableCaching -@EnableJpaAuditing @SpringBootApplication public class DiareatApplication { diff --git a/src/main/java/com/diareat/diareat/config/JpaAuditingConfig.java b/src/main/java/com/diareat/diareat/config/JpaAuditingConfig.java new file mode 100644 index 0000000..c4aac34 --- /dev/null +++ b/src/main/java/com/diareat/diareat/config/JpaAuditingConfig.java @@ -0,0 +1,9 @@ +package com.diareat.diareat.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@Configuration +@EnableJpaAuditing +public class JpaAuditingConfig { +} From ceaf9a194fa883800f7460cd799506340cdaaea2 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 8 Jan 2024 00:12:35 +0900 Subject: [PATCH 345/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20fix:=20Respons?= =?UTF-8?q?eSimpleFoodDto=20=EC=82=AD=EC=A0=9C=EB=A1=9C=20=EC=9D=B8?= =?UTF-8?q?=ED=95=B4=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EB=B3=80=EA=B2=BD=20(#140)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/controller/FoodControllerTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index cbfe8ed..c0c3a50 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -389,12 +389,12 @@ void testGetNutritionSumByMonth() throws Exception { void testGetScoreOfUserWithBestAndWorstFoods() throws Exception{ //Given LocalDate date = LocalDate.of(2021, 10, 10); - ResponseSimpleFoodDto food1 = ResponseSimpleFoodDto.of("test1", 100, 100, 100, 100, date); - ResponseSimpleFoodDto food2 = ResponseSimpleFoodDto.of("test", 100, 100, 100, 100, date); - ResponseSimpleFoodDto food3 = ResponseSimpleFoodDto.of("test", 100, 100, 100, 100, date); - ResponseSimpleFoodDto food4 = ResponseSimpleFoodDto.of("test4", 100, 100, 100, 100, date); - ResponseSimpleFoodDto food5 = ResponseSimpleFoodDto.of("test", 100, 100, 100, 100, date); - ResponseSimpleFoodDto food6 = ResponseSimpleFoodDto.of("test", 100, 100, 100, 100, date); + ResponseFoodDto food1 = ResponseFoodDto.builder().name("test").baseNutrition(BaseNutrition.createNutrition(100, 100, 100, 100)).build(); + ResponseFoodDto food2 = ResponseFoodDto.builder().name("test").baseNutrition(BaseNutrition.createNutrition(100, 100, 100, 100)).build(); + ResponseFoodDto food3 = ResponseFoodDto.builder().name("test").baseNutrition(BaseNutrition.createNutrition(100, 100, 100, 100)).build(); + ResponseFoodDto food4 = ResponseFoodDto.builder().name("test").baseNutrition(BaseNutrition.createNutrition(100, 100, 100, 100)).build(); + ResponseFoodDto food5 = ResponseFoodDto.builder().name("test").baseNutrition(BaseNutrition.createNutrition(100, 100, 100, 100)).build(); + ResponseFoodDto food6 = ResponseFoodDto.builder().name("test").baseNutrition(BaseNutrition.createNutrition(100, 100, 100, 100)).build(); ResponseScoreBestWorstDto responseScoreBestWorstDto = ResponseScoreBestWorstDto.of(testUserId, 100, 80 , 60, 240, List.of(food1, food2,food3), List.of(food4, food5, food6)); From bf4b9368147735183121daa19d7d9ccd11d950de Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Mon, 8 Jan 2024 00:13:21 +0900 Subject: [PATCH 346/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20fix:=20?= =?UTF-8?q?=EC=A0=91=EA=B7=BC=20=EB=AA=BB=ED=95=98=EB=8A=94=20private=20Fi?= =?UTF-8?q?eld=EB=8A=94=20set()=20=EB=8C=80=EC=8B=A0=20Reflect=EB=A5=BC=20?= =?UTF-8?q?=EC=9D=B4=EC=9A=A9=ED=95=98=EC=97=AC=20=EC=A0=91=EA=B7=BC=20(#1?= =?UTF-8?q?40)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/food/domain/FavoriteFood.java | 4 - .../com/diareat/diareat/food/domain/Food.java | 4 - .../controller/FoodControllerTest.java | 14 +- .../diareat/service/FoodServiceTest.java | 131 ++++++++++++------ 4 files changed, 98 insertions(+), 55 deletions(-) diff --git a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java index a6d139c..4f69dbd 100644 --- a/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java +++ b/src/main/java/com/diareat/diareat/food/domain/FavoriteFood.java @@ -62,8 +62,4 @@ public static Food createFoodFromFavoriteFood(FavoriteFood favoriteFood) { LocalDate createdDate = LocalDate.now(); return Food.createFood(favoriteFood.getName(), favoriteFood.getUser(), favoriteFood.getBaseNutrition(), createdDate.getYear(), createdDate.getMonthValue(), createdDate.getDayOfMonth()); } - - public void setId(Long id) { - this.id = id; - } } 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 fa9ab46..b491c2f 100644 --- a/src/main/java/com/diareat/diareat/food/domain/Food.java +++ b/src/main/java/com/diareat/diareat/food/domain/Food.java @@ -64,10 +64,6 @@ public boolean isFavorite() { return this.favoriteFood != null; } - public void setId(long id) {this.id = id;} - - public void setDate(LocalDate date) {this.date = date;} //food test를 위한 date - public void setFavoriteFood(FavoriteFood favoriteFood){ this.favoriteFood = favoriteFood; } diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index c0c3a50..8ac9947 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -28,6 +28,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import java.lang.reflect.Field; import java.time.LocalDate; import java.time.LocalTime; import java.util.List; @@ -59,11 +60,18 @@ class FoodControllerTest { private final BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(500, 50, 30, 10); @BeforeEach - void setUp() { + void setUp() throws NoSuchFieldException, IllegalAccessException { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); testUser.setId(testUserId); - testFood.setId(testFoodId); - testFavoriteFood.setId(testFavoriteFoodId); + + Field foodId = Food.class.getDeclaredField("id"); + foodId.setAccessible(true); + foodId.set(testFood, testFoodId); + + Field favoriteId = FavoriteFood.class.getDeclaredField("id"); + favoriteId.setAccessible(true); + favoriteId.set(testFavoriteFood, testFavoriteFoodId); + mapper.registerModule(new JavaTimeModule()); } diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index a92fb82..8b3c2d6 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -14,12 +14,14 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.data.domain.Sort; +import java.lang.reflect.Field; import java.time.DayOfWeek; import java.time.LocalDate; import java.util.List; @@ -54,7 +56,7 @@ class FoodServiceTest { @DisplayName("음식 정보 저장") @Test - void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리스트 불러오기 + void testSaveAndGetFood() throws NoSuchFieldException, IllegalAccessException { // 음식 정보 저장 및 해당 날짜 음식 리스트 불러오기 // given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); User user = User.createUser("testUser", "testImage","testPassword", 1,180, 80,18, testBaseNutrition); @@ -62,7 +64,15 @@ void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리 CreateFoodDto createFoodDto = CreateFoodDto.of(user.getId(), "testFood", testBaseNutrition, 2010,1,1); Food food = Food.createFood("testFood", user, testBaseNutrition, 2010,1,1); - food.setId(2L); + + Field f_id = Food.class.getDeclaredField("id"); + f_id.setAccessible(true); + f_id.set(food, 2L); + + //addedTime에 접근할 수 없으므로 Reflection 통한 값 설정 + Field addedTime = Food.class.getDeclaredField("addedTime"); + addedTime.setAccessible(true); + addedTime.set(food, LocalDate.of(2010,1,1).atTime(0,0)); given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); given(userRepository.existsById(user.getId())).willReturn(true); @@ -80,12 +90,15 @@ void testSaveAndGetFood() { // 음식 정보 저장 및 해당 날짜 음식 리 } @Test - void testUpdateFood() { + void testUpdateFood() throws NoSuchFieldException, IllegalAccessException { //given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); User user = User.createUser("testUser", "testImage","tessPassword", 1, 180, 80, 18, testBaseNutrition); Food food = Food.createFood("testFood", user, testBaseNutrition, 2010,1,1); - food.setId(1L); + + Field foodId = Food.class.getDeclaredField("id"); + foodId.setAccessible(true); + foodId.set(food, 2L); given(foodRepository.findById(food.getId())).willReturn(Optional.of(food)); @@ -103,12 +116,15 @@ void testUpdateFood() { } // @Test - void testDeleteFood() { + void testDeleteFood() throws NoSuchFieldException, IllegalAccessException { //given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); User user = User.createUser("testUser", "testImage","tessPassword", 1, 180, 80, 18, testBaseNutrition); Food food = Food.createFood("testFood", user, testBaseNutrition, 2010,1,1); - food.setId(1L); + + Field foodId = Food.class.getDeclaredField("id"); + foodId.setAccessible(true); + foodId.set(food, 2L); given(foodRepository.existsById(food.getId())).willReturn(true); given(foodRepository.existsByIdAndUserId(food.getId(), 1L)).willReturn(true); @@ -120,14 +136,20 @@ void testDeleteFood() { } @Test - void testSaveAndGetFavoriteFood() { + void testSaveAndGetFavoriteFood() throws NoSuchFieldException, IllegalAccessException { BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); User user = User.createUser("testUser", "testImage","testPassword", 1,180, 80,18, testBaseNutrition); Food food = Food.createFood("testFood", user, testBaseNutrition, 2010,1,1); FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("testFavoriteFood", user,food, testBaseNutrition); user.setId(1L); - food.setId(2L); - favoriteFood.setId(3L); + + Field foodId = Food.class.getDeclaredField("id"); + foodId.setAccessible(true); + foodId.set(food, 2L); + + Field fav_Id = FavoriteFood.class.getDeclaredField("id"); + fav_Id.setAccessible(true); + fav_Id.set(favoriteFood, 3L); CreateFavoriteFoodDto createFavoriteFoodDto = CreateFavoriteFoodDto.of(food.getId(), user.getId(),"testFood", testBaseNutrition); @@ -149,13 +171,16 @@ void testSaveAndGetFavoriteFood() { verify(favoriteFoodRepository, times(1)).save(any(FavoriteFood.class)); } @Test - void testUpdateFavoriteFood() { + void testUpdateFavoriteFood() throws NoSuchFieldException, IllegalAccessException { //given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); User user = User.createUser("testUser", "testImage","tessPassword", 1, 180, 80, 18, testBaseNutrition); Food food = Food.createFood("testFood", user, testBaseNutrition, 2010,1,1); FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("testFavoriteFood", user, food,testBaseNutrition); - favoriteFood.setId(1L); + + Field fav_Id = FavoriteFood.class.getDeclaredField("id"); + fav_Id.setAccessible(true); + fav_Id.set(favoriteFood, 3L); given(favoriteFoodRepository.findById(favoriteFood.getId())).willReturn(Optional.of(favoriteFood)); @@ -172,14 +197,17 @@ void testUpdateFavoriteFood() { } // @Test - void testDeleteFavoriteFood() { + void testDeleteFavoriteFood() throws NoSuchFieldException, IllegalAccessException { //given BaseNutrition testBaseNutrition = BaseNutrition.createNutrition(1,1,1,1); User user = User.createUser("testUser", "testImage","tessPassword", 1, 180, 80, 18, testBaseNutrition); Food food = Food.createFood("testFood", user, testBaseNutrition, 2010,1,1); FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("testFood", user, food, testBaseNutrition); food.setFavoriteFood(favoriteFood); - favoriteFood.setId(1L); + + Field fav_Id = FavoriteFood.class.getDeclaredField("id"); + fav_Id.setAccessible(true); + fav_Id.set(favoriteFood, 3L); given(favoriteFoodRepository.existsById(favoriteFood.getId())).willReturn(true); given(favoriteFoodRepository.existsByIdAndUserId(favoriteFood.getId(), 1L)).willReturn(true); @@ -192,13 +220,16 @@ void testDeleteFavoriteFood() { } // @Test - void testNutritionSumByDate(){ + void testNutritionSumByDate() throws NoSuchFieldException, IllegalAccessException { //given BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); User user = User.createUser("testUser", "testImage","testPassword",1, 180, 80, 18, BaseNutrition.createNutrition(2000,300,80,80)); user.setId(1L); Food food = Food.createFood("testFood", user, testFoodNutrition, 2010,1,1); - food.setId(2L); + + Field foodId = Food.class.getDeclaredField("id"); + foodId.setAccessible(true); + foodId.set(food, 2L); given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); @@ -219,13 +250,16 @@ void testNutritionSumByDate(){ } // @Test - void testNutritionSumByWeek(){ + void testNutritionSumByWeek() throws NoSuchFieldException, IllegalAccessException { //given BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); User user = User.createUser("testUser", "testImage","testPassword",1, 180, 80, 18, BaseNutrition.createNutrition(2000,300,80,80)); user.setId(1L); Food food = Food.createFood("testFood", user, testFoodNutrition, 2010,1,1); - food.setId(2L); + + Field foodId = Food.class.getDeclaredField("id"); + foodId.setAccessible(true); + foodId.set(food, 2L); given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); @@ -248,13 +282,16 @@ void testNutritionSumByWeek(){ } @Test - void testNutritionSumByMonth(){ + void testNutritionSumByMonth() throws NoSuchFieldException, IllegalAccessException { //given BaseNutrition testFoodNutrition = BaseNutrition.createNutrition(1400,150,200,250); User user = User.createUser("testUser", "testImage","testPassword",1, 180, 80, 18, BaseNutrition.createNutrition(2000,300,80,80)); user.setId(1L); Food food = Food.createFood("testFood", user, testFoodNutrition, 2010,1,1); - food.setId(2L); + + Field foodId = Food.class.getDeclaredField("id"); + foodId.setAccessible(true); + foodId.set(food, 2L); given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.findById(user.getId())).willReturn(Optional.of(user)); @@ -294,7 +331,7 @@ void getBest3FoodTest() { // when ResponseFoodRankDto response = foodService.getBestFoodByWeek(user.getId(), 2010,1,1); - List top3Foods = response.getRankFoodList(); + List top3Foods = response.getRankFoodList(); // then assertEquals(3, top3Foods.size()); @@ -321,7 +358,7 @@ void getWorst3FoodsTest() { // when ResponseFoodRankDto response = foodService.getWorstFoodByWeek(user.getId(), 2010,1,1); - List top3Foods = response.getRankFoodList(); + List top3Foods = response.getRankFoodList(); // then assertEquals(3, top3Foods.size()); @@ -371,7 +408,7 @@ void getUserRankByWeek() { } @Test - void testGetScoreOfUserWithBestAndWorstFoods(){ + void testGetScoreOfUserWithBestAndWorstFoods() throws NoSuchFieldException, IllegalAccessException { // 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), 2010,1,1); @@ -382,10 +419,12 @@ void testGetScoreOfUserWithBestAndWorstFoods(){ LocalDate fixedDate = LocalDate.of(2010, 1, 1); - food1.setDate(fixedDate); - food1_1.setDate(fixedDate); - food2.setDate(fixedDate.minusDays(2)); - food3.setDate(fixedDate.minusDays(3)); + Field date = Food.class.getDeclaredField("date"); + date.setAccessible(true); + date.set(food1, fixedDate); + date.set(food1_1, fixedDate); + date.set(food2, fixedDate.minusDays(2)); + date.set(food3, fixedDate.minusDays(3)); List foodList = List.of(food1, food1_1, food2, food3); @@ -395,8 +434,8 @@ void testGetScoreOfUserWithBestAndWorstFoods(){ // when ResponseScoreBestWorstDto response = foodService.getScoreOfUserWithBestAndWorstFoods(user.getId(), 2010, 1, 1); - List top3Foods = response.getBest(); - List worst3Foods = response.getWorst(); + List top3Foods = response.getBest(); + List worst3Foods = response.getWorst(); double totalScore = response.getTotalScore(); double calorieScore = response.getCalorieScore(); double carbohydrateScore = response.getCarbohydrateScore(); @@ -414,7 +453,7 @@ void testGetScoreOfUserWithBestAndWorstFoods(){ } @Test - void testGetAnalysisOfUser(){ + void testGetAnalysisOfUser() throws NoSuchFieldException, IllegalAccessException { // 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), 2010,1,1); @@ -427,22 +466,19 @@ void testGetAnalysisOfUser(){ LocalDate fixedDate = LocalDate.of(2010, 5, 1); - food1.setDate(fixedDate); - food1_1.setDate(fixedDate); - food2.setDate(fixedDate.minusDays(2)); - food3.setDate(fixedDate.minusDays(3)); - food4.setDate(fixedDate.minusWeeks(1)); - food5.setDate(fixedDate.minusWeeks(2)); - - + Field date = Food.class.getDeclaredField("date"); + date.setAccessible(true); + date.set(food1, fixedDate); + date.set(food1_1, fixedDate); + date.set(food2, fixedDate.minusDays(2)); + date.set(food3, fixedDate.minusDays(3)); + date.set(food4, fixedDate.minusWeeks(1)); + date.set(food5, fixedDate.minusWeeks(2)); List foodListOfWeek = List.of(food1,food1_1, food2, food3); List foodListOfMonth = List.of(food1, food1_1,food2, food3, food4, food5); Sort sort = Sort.by(Sort.Direction.DESC, "added_time"); - - - given(userRepository.existsById(user.getId())).willReturn(true); given(userRepository.getReferenceById(any(Long.class))).willReturn(user); given(foodRepository.findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(user.getId(), fixedDate.minusWeeks(1).plusDays(1), fixedDate.plusDays(1))).willReturn(foodListOfWeek); @@ -473,16 +509,23 @@ void testGetAnalysisOfUser(){ } @Test - void testCreateFoodFromFavoriteFood() { + void testCreateFoodFromFavoriteFood() throws NoSuchFieldException, IllegalAccessException { // given User user = User.createUser("testUser", "testImage","testPassword", 1, 180, 80, 18, BaseNutrition.createNutrition(2000,400,100,50)); Food food = Food.createFood( "Food", user, BaseNutrition.createNutrition(100, 100 ,10, 1), 2010,1,1); FavoriteFood favoriteFood = FavoriteFood.createFavoriteFood("FavoriteFood", user, food, BaseNutrition.createNutrition(100, 100 ,10, 1)); Food newFood = Food.createFood("FoodFromFavorite", user, BaseNutrition.createNutrition(100, 100 ,10, 1), 2010,1,1); user.setId(1L); - food.setId(2L); - favoriteFood.setId(3L); - newFood.setId(4L); + + Field f_id = Food.class.getDeclaredField("id"); + f_id.setAccessible(true); + f_id.set(food, 2L); + f_id.set(newFood, 4L); + + Field fav_id = FavoriteFood.class.getDeclaredField("id"); + fav_id.setAccessible(true); + fav_id.set(favoriteFood, 3L); + CreateFoodFromFavoriteFoodDto createFoodFromFavoriteFoodDto = CreateFoodFromFavoriteFoodDto.of(user.getId(), favoriteFood.getId()); From 9dbd5e4d534248bc692792e4429c06d23c81552f Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 8 Jan 2024 01:17:32 +0000 Subject: [PATCH 347/371] :construction_worker: chore: Update deployment to 3050d5a7c8f0bd28c5df02deb2cf8fbf3c511ca4 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index c135dec..4acb578 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 4f1c4fc0 + newTag: 3050d5a7 From 3d36d63f60523d2696f2a31f4029530e62cf319e Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 16 Jan 2024 14:53:30 +0900 Subject: [PATCH 348/371] =?UTF-8?q?:art:=20Refactor:=20=EC=A6=90=EC=B0=BE?= =?UTF-8?q?=EC=9D=8C=EC=8B=9D=20=ED=95=B4=EC=A0=9C=20=EC=8B=9C=20=ED=8C=8C?= =?UTF-8?q?=EC=83=9D=EB=90=9C=20=EC=9D=8C=EC=8B=9D=EB=93=A4=EC=9D=98=20?= =?UTF-8?q?=EC=A6=90=EC=B0=BE=EC=83=81=ED=83=9C=20=EC=BF=BC=EB=A6=AC?= =?UTF-8?q?=EB=A1=9C=20=ED=95=B4=EC=A0=9C=ED=95=98=EB=8F=84=EB=A1=9D=20?= =?UTF-8?q?=EA=B0=9C=ED=8E=B8=20(#142)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/food/repository/FoodRepository.java | 8 ++++++-- .../com/diareat/diareat/food/service/FoodService.java | 3 +-- 2 files changed, 7 insertions(+), 4 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 db42ed6..41a01cb 100644 --- a/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java +++ b/src/main/java/com/diareat/diareat/food/repository/FoodRepository.java @@ -1,15 +1,19 @@ package com.diareat.diareat.food.repository; import com.diareat.diareat.food.domain.Food; -import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import java.time.LocalDate; import java.util.List; public interface FoodRepository extends JpaRepository { boolean existsByIdAndUserId(Long id, Long userId); // 유저가 먹은 음식인지 확인 - boolean existsByName(String name); List findAllByUserIdAndDateOrderByAddedTimeAsc(Long userId, LocalDate date); //유저가 특정 날짜에 먹은 음식 반환 List findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(Long userId, LocalDate startDate, LocalDate endDate); // 유저가 특정 기간 내에 먹은 음식 반환 + + // 특정 즐겨찾기 음식으로부터 태어난 음식 데이터의, 즐겨찾기 음식과의 연관관계를 해제 + @Query(value = "UPDATE Food f set f.favoriteFood = null where f.favoriteFood.id = :id") + void updateFoodRelationShipWithFavoriteFood(@Param("id")Long favoriteFoodId); } 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 a45454e..85527cf 100644 --- a/src/main/java/com/diareat/diareat/food/service/FoodService.java +++ b/src/main/java/com/diareat/diareat/food/service/FoodService.java @@ -134,9 +134,8 @@ public void updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto) { @Transactional public void deleteFavoriteFood(Long favoriteFoodId, Long userId) { validateFavoriteFood(favoriteFoodId, userId); - FavoriteFood favoriteFood = getFavoriteFoodById(favoriteFoodId); - favoriteFood.getFoods().forEach(food -> food.setFavoriteFood(null)); // 즐겨찾기 음식으로부터 태어난 음식들의 즐겨찾기 정보를 null로 초기화 favoriteFoodRepository.deleteById(favoriteFoodId); + foodRepository.updateFoodRelationShipWithFavoriteFood(favoriteFoodId); log.info("즐겨찾기 음식 해제 완료: " + favoriteFoodId); } From b0336590930f33d80f72fed4a866c405561dd55d Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 16 Jan 2024 14:59:26 +0900 Subject: [PATCH 349/371] =?UTF-8?q?:sparkles:=20Feat:=20User=20=EA=B0=9D?= =?UTF-8?q?=EC=B2=B4=EC=97=90=20=EA=B0=80=EC=9E=85=EC=9D=BC=EC=9E=90=20cre?= =?UTF-8?q?atedTime=20=EC=86=8D=EC=84=B1=20=EC=B6=94=EA=B0=80=20(#142)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/user/domain/User.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index 3bb31b7..32d2c1b 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -11,6 +11,7 @@ import reactor.util.annotation.Nullable; import javax.persistence.*; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -44,6 +45,8 @@ public class User implements UserDetails { private int type; // 성별과 연령에 따른 유저 타입 (1~12) + private LocalDateTime createdTime; // 회원가입 시간 + private BaseNutrition baseNutrition; // 기준영양소 @OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) // 유저가 탈퇴하면 촬영한 음식도 삭제 @@ -108,6 +111,7 @@ public static User createUser(String name, String image, String keyCode, int hei user.age = age; user.baseNutrition = baseNutrition; user.type = UserTypeUtil.decideUserType(gender, age); + user.createdTime = LocalDateTime.now(); return user; } From 39e4697c738f0e34c8b586dfe14bfb816ee9adcd Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 16 Jan 2024 15:30:28 +0900 Subject: [PATCH 350/371] =?UTF-8?q?:art:=20Refactor:=20BaseNutrition=20?= =?UTF-8?q?=EB=B6=88=ED=95=84=EC=9A=94=20=EB=A9=94=EC=84=9C=EB=93=9C=20?= =?UTF-8?q?=EC=A0=9C=EA=B1=B0=20(#142)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/user/domain/BaseNutrition.java | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/domain/BaseNutrition.java b/src/main/java/com/diareat/diareat/user/domain/BaseNutrition.java index 86719f9..ad0706f 100644 --- a/src/main/java/com/diareat/diareat/user/domain/BaseNutrition.java +++ b/src/main/java/com/diareat/diareat/user/domain/BaseNutrition.java @@ -25,23 +25,4 @@ public static BaseNutrition createNutrition(int kcal, int carbohydrate, int prot baseNutrition.fat = fat; return baseNutrition; } - - // 생성 메서드 by 개인정보 (성별, 나이, 키, 몸무게로 기준영양소 자동 계산 기능) - public static BaseNutrition calculateNutrition(int gender, int age, int height, int weight) { - BaseNutrition baseNutrition = new BaseNutrition(); - - // 임의의 식으로 기초대사량 계산하였으며, 추후 식약처 및 관련 기관에서 제공하는 공식으로 변경할 예정 - baseNutrition.kcal = (int) (66.47 + (13.75 * weight) + (5 * height) - (6.76 * age)); // 기초대사량 계산식 - baseNutrition.carbohydrate = (int) (baseNutrition.kcal * 0.65 / 4); // 탄수화물 65% - baseNutrition.protein = (int) (baseNutrition.kcal * 0.1 / 4); // 단백질 10% - baseNutrition.fat = (int) (baseNutrition.kcal * 0.25 / 9); - - if(gender == 1) { // 여성일 경우 - baseNutrition.kcal -= 161; - baseNutrition.carbohydrate -= 40; - baseNutrition.protein -= 5; - baseNutrition.fat -= 10; - } - return baseNutrition; - } } From 4373f75ed2f45bad080db5d06f46eb5fdd61883c Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 16 Jan 2024 15:31:07 +0900 Subject: [PATCH 351/371] =?UTF-8?q?:art:=20Refactor:=20=EC=9C=A0=EC=A0=80?= =?UTF-8?q?=20=EA=B2=80=EC=83=89=20=EA=B8=B0=EB=8A=A5=20JPA=20N+1=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C=20=ED=95=B4=EA=B2=B0=20(#142)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/user/domain/User.java | 2 +- .../com/diareat/diareat/user/repository/UserRepository.java | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index 32d2c1b..e8e8a54 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -57,7 +57,7 @@ public class User implements UserDetails { // Jwt 전용 설정 (UserDetails 인터페이스 구현) - @ElementCollection(fetch = FetchType.EAGER) //roles 컬렉션 + @ElementCollection(fetch = FetchType.LAZY) //roles 컬렉션 private List roles = new ArrayList<>(); @Override //사용자의 권한 목록 리턴 diff --git a/src/main/java/com/diareat/diareat/user/repository/UserRepository.java b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java index 03b4e66..2010047 100644 --- a/src/main/java/com/diareat/diareat/user/repository/UserRepository.java +++ b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java @@ -1,13 +1,17 @@ package com.diareat.diareat.user.repository; import com.diareat.diareat.user.domain.User; +import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.Optional; public interface UserRepository extends JpaRepository { + + @EntityGraph(attributePaths = {"roles"}) List findAllByNameContaining(String name); // 회원이 팔로우를 위해 검색한 유저 목록 조회 + boolean existsByName(String name); // 회원가입 시 닉네임 중복 확인 boolean existsByKeyCode(String keyCode); // 카카오 회원가입 시 중복 확인 Optional findByKeyCode(String keyCode); // 카카오 회원가입 시 중복 확인 From 0a43a0d23b1f9ec64f0c043d1df20bc83c42f278 Mon Sep 17 00:00:00 2001 From: CHAE Date: Tue, 16 Jan 2024 16:13:21 +0900 Subject: [PATCH 352/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20Refactor:=20?= =?UTF-8?q?=EC=A6=90=EC=B0=BE=EC=9D=8C=EC=8B=9D=20=EA=B4=80=EA=B3=84=20?= =?UTF-8?q?=EB=8B=A8=EC=A0=88=20=EA=B4=80=EB=A0=A8=20=EC=9D=BC=EB=B6=80=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=EC=BD=94=EB=93=9C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=20(#142)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/com/diareat/diareat/service/FoodServiceTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java index 8b3c2d6..1afd799 100644 --- a/src/test/java/com/diareat/diareat/service/FoodServiceTest.java +++ b/src/test/java/com/diareat/diareat/service/FoodServiceTest.java @@ -211,7 +211,6 @@ void testDeleteFavoriteFood() throws NoSuchFieldException, IllegalAccessExceptio given(favoriteFoodRepository.existsById(favoriteFood.getId())).willReturn(true); given(favoriteFoodRepository.existsByIdAndUserId(favoriteFood.getId(), 1L)).willReturn(true); - given(favoriteFoodRepository.findById(favoriteFood.getId())).willReturn(Optional.of(favoriteFood)); //when foodService.deleteFavoriteFood(favoriteFood.getId(), 1L); From ae777f4322f0ce2473c6d154e25fdb30cde4319e Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 16 Jan 2024 07:17:55 +0000 Subject: [PATCH 353/371] :construction_worker: chore: Update deployment to 94530d3b8ca2bc6d046aec92e7d48f9eb1ef31df --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 4acb578..62f7ab7 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 3050d5a7 + newTag: 94530d3b From a5e13811404e4261512151f78c716ba4245dce9f Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 22 Jan 2024 16:35:11 +0900 Subject: [PATCH 354/371] =?UTF-8?q?:art:=20Refactor:=20FoodController=20us?= =?UTF-8?q?erId=20jwtToken=EC=9C=BC=EB=A1=9C=EB=B6=80=ED=84=B0=20=EA=B0=84?= =?UTF-8?q?=EC=A0=91=EC=A0=81=EC=9C=BC=EB=A1=9C=20=EC=B6=94=EC=B6=9C=20(#1?= =?UTF-8?q?45)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../food/controller/FoodController.java | 135 ++++++++++-------- 1 file changed, 73 insertions(+), 62 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 2d36b9e..b682b75 100644 --- a/src/main/java/com/diareat/diareat/food/controller/FoodController.java +++ b/src/main/java/com/diareat/diareat/food/controller/FoodController.java @@ -1,5 +1,6 @@ package com.diareat.diareat.food.controller; +import com.diareat.diareat.auth.component.JwtTokenProvider; import com.diareat.diareat.food.dto.*; import com.diareat.diareat.food.service.FoodService; import com.diareat.diareat.user.dto.response.ResponseRankUserDto; @@ -21,145 +22,155 @@ public class FoodController { private final FoodService foodService; + private final JwtTokenProvider jwtTokenProvider; //음식 정보 저장 @Operation(summary = "[음식] 음식 정보 저장", description = "촬영한 음식 정보를 저장합니다.") @PostMapping("/save") - public ApiResponse saveFood(@RequestBody @Valid CreateFoodDto createFoodDto){ - return ApiResponse.success(foodService.saveFood(createFoodDto),ResponseCode.FOOD_CREATE_SUCCESS.getMessage()); + public ApiResponse saveFood(@RequestBody @Valid CreateFoodDto createFoodDto) { + return ApiResponse.success(foodService.saveFood(createFoodDto), ResponseCode.FOOD_CREATE_SUCCESS.getMessage()); } //특정 날짜에 먹은 음식 반환 - @Operation(summary = "[음식] 특정 날짜에 먹은 음식 목록 조회",description = "유저의 특정 날짜에 먹은 음식 목록을 조회합니다.") - @GetMapping("/{userId}") - public ApiResponse> getFoodListByDate(@PathVariable Long userId, + @Operation(summary = "[음식] 특정 날짜에 먹은 음식 목록 조회", description = "유저의 특정 날짜에 먹은 음식 목록을 조회합니다.") + @GetMapping + public ApiResponse> getFoodListByDate(@RequestHeader String accessToken, @RequestParam int yy, @RequestParam int mm, - @RequestParam int dd) - { - LocalDate date = LocalDate.of(yy,mm,dd); - return ApiResponse.success(foodService.getFoodListByDate(userId,date),ResponseCode.FOOD_READ_SUCCESS.getMessage()); + @RequestParam int dd) { + Long userId = jwtTokenProvider.getUserPk(accessToken); + LocalDate date = LocalDate.of(yy, mm, dd); + return ApiResponse.success(foodService.getFoodListByDate(userId, date), ResponseCode.FOOD_READ_SUCCESS.getMessage()); } //음식 정보 수정 - @Operation(summary = "[음식] 음식 정보 수정",description = "음식에 대한 정보를 수정합니다.") + @Operation(summary = "[음식] 음식 정보 수정", description = "음식에 대한 정보를 수정합니다.") @PostMapping("/update") public ApiResponse updateFood(@RequestBody @Valid UpdateFoodDto updateFoodDto, @RequestParam int yy, @RequestParam int mm, - @RequestParam int dd){ - LocalDate date = LocalDate.of(yy,mm,dd); + @RequestParam int dd) { + LocalDate date = LocalDate.of(yy, mm, dd); foodService.updateFood(updateFoodDto, date); - return ApiResponse.success(null,ResponseCode.FOOD_UPDATE_SUCCESS.getMessage()); + return ApiResponse.success(null, ResponseCode.FOOD_UPDATE_SUCCESS.getMessage()); } + //음식 삭제 - @Operation(summary = "[음식] 음식 정보 삭제",description = "음식에 대한 정보를 삭제합니다.") + @Operation(summary = "[음식] 음식 정보 삭제", description = "음식에 대한 정보를 삭제합니다.") @DeleteMapping("/{foodId}/delete") - public ApiResponse deleteFood(@PathVariable Long foodId, @RequestHeader Long userId, + public ApiResponse deleteFood(@PathVariable Long foodId, @RequestHeader String accessToken, @RequestParam int yy, @RequestParam int mm, - @RequestParam int dd){ - LocalDate date = LocalDate.of(yy,mm,dd); + @RequestParam int dd) { + Long userId = jwtTokenProvider.getUserPk(accessToken); + LocalDate date = LocalDate.of(yy, mm, dd); foodService.deleteFood(foodId, userId, date); return ApiResponse.success(null, ResponseCode.FOOD_DELETE_SUCCESS.getMessage()); } //즐겨찾기에 음식 저장 - @Operation(summary = "[즐겨찾기] 즐겨찾기에 저장",description = "유저의 즐겨찾기에 음식을 저장합니다.") + @Operation(summary = "[즐겨찾기] 즐겨찾기에 저장", description = "유저의 즐겨찾기에 음식을 저장합니다.") @PostMapping("/favorite") - public ApiResponse saveFavoriteFood(@RequestBody @Valid CreateFavoriteFoodDto createFavoriteFoodDto){ - return ApiResponse.success(foodService.saveFavoriteFood(createFavoriteFoodDto),ResponseCode.FOOD_FAVORITE_CREATE_SUCCESS.getMessage()); + public ApiResponse saveFavoriteFood(@RequestBody @Valid CreateFavoriteFoodDto createFavoriteFoodDto) { + return ApiResponse.success(foodService.saveFavoriteFood(createFavoriteFoodDto), ResponseCode.FOOD_FAVORITE_CREATE_SUCCESS.getMessage()); } //즐겨찾기 음식 리스트 반환 - @Operation(summary = "[즐겨찾기] 즐겨찾기 목록 조회",description = "유저의 즐겨찾기에 등록된 음식 목록을 조회합니다.") - @GetMapping("/favorite/{userId}") - public ApiResponse> getFavoriteFoodList(@PathVariable Long userId){ + @Operation(summary = "[즐겨찾기] 즐겨찾기 목록 조회", description = "유저의 즐겨찾기에 등록된 음식 목록을 조회합니다.") + @GetMapping("/favorite") + public ApiResponse> getFavoriteFoodList(@RequestHeader String accessToken) { + Long userId = jwtTokenProvider.getUserPk(accessToken); return ApiResponse.success(foodService.getFavoriteFoodList(userId), ResponseCode.FOOD_FAVORITE_READ_SUCCESS.getMessage()); } //즐겨찾기 음식 수정 - @Operation(summary = "[즐겨찾기] 즐겨찾기 수정",description = "유저의 즐겨찾기에 등록된 음식의 정보를 수정합니다.") + @Operation(summary = "[즐겨찾기] 즐겨찾기 수정", description = "유저의 즐겨찾기에 등록된 음식의 정보를 수정합니다.") @PostMapping("/favorite/update") - public ApiResponse updateFavoriteFood(@RequestBody @Valid UpdateFavoriteFoodDto updateFavoriteFoodDto){ + public ApiResponse updateFavoriteFood(@RequestBody @Valid UpdateFavoriteFoodDto updateFavoriteFoodDto) { foodService.updateFavoriteFood(updateFavoriteFoodDto); return ApiResponse.success(null, ResponseCode.FOOD_FAVORITE_UPDATE_SUCCESS.getMessage()); } //즐겨찾기 음식 해제 - @Operation(summary = "[즐겨찾기] 즐겨찾기 해제",description = "유저의 즐겨찾기에 등록된 음식을 해제합니다.") + @Operation(summary = "[즐겨찾기] 즐겨찾기 해제", description = "유저의 즐겨찾기에 등록된 음식을 해제합니다.") @DeleteMapping("/favorite/{favoriteFoodId}") - public ApiResponse deleteFavoriteFood(@PathVariable Long favoriteFoodId, @RequestHeader Long userId){ + public ApiResponse deleteFavoriteFood(@PathVariable Long favoriteFoodId, @RequestHeader String accessToken) { + Long userId = jwtTokenProvider.getUserPk(accessToken); foodService.deleteFavoriteFood(favoriteFoodId, userId); return ApiResponse.success(null, ResponseCode.FOOD_FAVORITE_DELETE_SUCCESS.getMessage()); } //특정 날짜에 먹은 음식들의 영양성분별 총합 조회 - @Operation(summary = "[음식] 특정 날짜에 먹은 음식들의 영양성분 총합 조회",description = "특정 날짜에 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") - @GetMapping("/{userId}/nutrition") - public ApiResponse getNutritionSumByDate(@PathVariable Long userId, + @Operation(summary = "[음식] 특정 날짜에 먹은 음식들의 영양성분 총합 조회", description = "특정 날짜에 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") + @GetMapping("/nutrition") + public ApiResponse getNutritionSumByDate(@RequestHeader String accessToken, @RequestParam int yy, @RequestParam int mm, - @RequestParam int dd){ - LocalDate date = LocalDate.of(yy,mm,dd); - return ApiResponse.success(foodService.getNutritionSumByDate(userId,date),ResponseCode.FOOD_READ_SUCCESS.getMessage()); + @RequestParam int dd) { + Long userId = jwtTokenProvider.getUserPk(accessToken); + LocalDate date = LocalDate.of(yy, mm, dd); + 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, + @Operation(summary = "[음식] 최근 7일간 먹은 음식들의 영양성분 총합 조회", description = "최근 7일 간 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") + @GetMapping("/nutrition/recentWeek") + public ApiResponse getNutritionSumByWeek(@RequestHeader String accessToken, @RequestParam int yy, @RequestParam int mm, - @RequestParam int dd){ - return ApiResponse.success(foodService.getNutritionSumByWeek(userId, yy, mm, dd),ResponseCode.FOOD_READ_SUCCESS.getMessage()); + @RequestParam int dd) { + Long userId = jwtTokenProvider.getUserPk(accessToken); + return ApiResponse.success(foodService.getNutritionSumByWeek(userId, yy, mm, dd), ResponseCode.FOOD_READ_SUCCESS.getMessage()); } //"" 30일간 (1달간) 총합 조회 - @Operation(summary = "[음식] 최근 한달 간 먹은 음식들의 영양성분 총합 조회",description = "최근 한달 간 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") - @GetMapping("/{userId}/nutrition/recentMonth") - public ApiResponse getNutritionSumByMonth(@PathVariable Long userId, + @Operation(summary = "[음식] 최근 한달 간 먹은 음식들의 영양성분 총합 조회", description = "최근 한달 간 유저가 먹은 음식들의 영양성분별 총합 및 권장섭취량에 대한 비율을 조회합니다.") + @GetMapping("/nutrition/recentMonth") + public ApiResponse getNutritionSumByMonth(@RequestHeader String accessToken, @RequestParam int yy, @RequestParam int mm, - @RequestParam int dd){ - return ApiResponse.success(foodService.getNutritionSumByMonth(userId, yy, mm, dd),ResponseCode.FOOD_READ_SUCCESS.getMessage()); - + @RequestParam int dd) { + Long userId = jwtTokenProvider.getUserPk(accessToken); + return ApiResponse.success(foodService.getNutritionSumByMonth(userId, yy, mm, dd), ResponseCode.FOOD_READ_SUCCESS.getMessage()); } //유저의 주간 식습관 점수와 best3, worst3 음식 조회 - @Operation(summary = "[음식] 유저의 주간 식습관 점수와 best3, worst3 음식 조회",description = "유저의 주간 식습관 점수와 best3, worst3 음식을 조회합니다.") - @GetMapping("/{userId}/score") - public ApiResponse getScoreOfUserWithBestAndWorstFoods(@PathVariable Long userId, + @Operation(summary = "[음식] 유저의 주간 식습관 점수와 best3, worst3 음식 조회", description = "유저의 주간 식습관 점수와 best3, worst3 음식을 조회합니다.") + @GetMapping("/score") + public ApiResponse getScoreOfUserWithBestAndWorstFoods(@RequestHeader String accessToken, @RequestParam int yy, @RequestParam int mm, @RequestParam int dd - ){ - return ApiResponse.success(foodService.getScoreOfUserWithBestAndWorstFoods(userId, yy, mm, dd),ResponseCode.FOOD_READ_SUCCESS.getMessage()); + ) { + Long userId = jwtTokenProvider.getUserPk(accessToken); + return ApiResponse.success(foodService.getScoreOfUserWithBestAndWorstFoods(userId, yy, mm, dd), ResponseCode.FOOD_READ_SUCCESS.getMessage()); } //유저의 일기 분석 그래프 데이터 및 식습관 totalScore 조회 - @Operation(summary = "[음식] 유저의 일기 분석 그래프 데이터 및 주간 식습관 점수 조회",description = "유저의 일기 분석 그래프 데이터 및 식습관 점수를 조회합니다.") - @GetMapping("/{userId}/analysis") - public ApiResponse getAnalysisOfUser(@PathVariable Long userId, + @Operation(summary = "[음식] 유저의 일기 분석 그래프 데이터 및 주간 식습관 점수 조회", description = "유저의 일기 분석 그래프 데이터 및 식습관 점수를 조회합니다.") + @GetMapping("/analysis") + public ApiResponse getAnalysisOfUser(@RequestHeader String accessToken, @RequestParam int yy, @RequestParam int mm, - @RequestParam int dd){ - return ApiResponse.success(foodService.getAnalysisOfUser(userId, yy, mm, dd),ResponseCode.FOOD_READ_SUCCESS.getMessage()); + @RequestParam int dd) { + Long userId = jwtTokenProvider.getUserPk(accessToken); + return ApiResponse.success(foodService.getAnalysisOfUser(userId, yy, mm, dd), ResponseCode.FOOD_READ_SUCCESS.getMessage()); } //유저의 식습관 점수를 기반으로 한 주간 랭킹 조회 - @Operation(summary = "[음식] 유저의 식습관 점수를 기반으로 한 주간 랭킹 조회",description = "유저의 식습관 점수를 기반으로 한 주간 랭킹을 조회합니다. (팔로잉 상대 기반)") - @GetMapping("/{userId}/rank") - public ApiResponse> getUserRankByWeek(@PathVariable Long userId, + @Operation(summary = "[음식] 유저의 식습관 점수를 기반으로 한 주간 랭킹 조회", description = "유저의 식습관 점수를 기반으로 한 주간 랭킹을 조회합니다. (팔로잉 상대 기반)") + @GetMapping("/rank") + public ApiResponse> getUserRankByWeek(@RequestHeader String accessToken, @RequestParam int yy, @RequestParam int mm, - @RequestParam int dd){ - return ApiResponse.success(foodService.getUserRankByWeek(userId, yy, mm, dd),ResponseCode.FOOD_RANK_READ_SUCCESS.getMessage()); + @RequestParam int dd) { + Long userId = jwtTokenProvider.getUserPk(accessToken); + return ApiResponse.success(foodService.getUserRankByWeek(userId, yy, mm, dd), ResponseCode.FOOD_RANK_READ_SUCCESS.getMessage()); } - @Operation(summary = "[음식] 즐겨찾기 음식으로 음식 생성",description = "즐겨찾기 음식으로 음식을 생성합니다.") + @Operation(summary = "[음식] 즐겨찾기 음식으로 음식 생성", description = "즐겨찾기 음식으로 음식을 생성합니다.") @PostMapping("/favorite/createfrom") - public ApiResponse createFoodFromFavoriteFood(@RequestBody @Valid CreateFoodFromFavoriteFoodDto createFoodFromFavoriteFoodDto){ - return ApiResponse.success(foodService.createFoodFromFavoriteFood(createFoodFromFavoriteFoodDto),ResponseCode.FOOD_CREATE_SUCCESS.getMessage()); + public ApiResponse createFoodFromFavoriteFood(@RequestBody @Valid CreateFoodFromFavoriteFoodDto createFoodFromFavoriteFoodDto) { + return ApiResponse.success(foodService.createFoodFromFavoriteFood(createFoodFromFavoriteFoodDto), ResponseCode.FOOD_CREATE_SUCCESS.getMessage()); } } From b38aaf65db8f1c24a43d249185b2d0e6ae874d57 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 22 Jan 2024 16:36:06 +0900 Subject: [PATCH 355/371] =?UTF-8?q?:white=5Fcheck=5Fmark:=20Refactor:=20Fo?= =?UTF-8?q?odControllerTest=20=EA=B0=9C=ED=8E=B8=EC=82=AC=ED=95=AD=20?= =?UTF-8?q?=EB=B0=98=EC=98=81=20=EB=B0=8F=20UserControllerTest=20=EC=9D=BC?= =?UTF-8?q?=EB=B6=80=20=EC=88=98=EC=A0=95=20(#145)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/FoodControllerTest.java | 35 +++++++++++++------ .../controller/UserControllerTest.java | 4 ++- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index 8ac9947..f1c88c3 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -1,5 +1,6 @@ package com.diareat.diareat.controller; +import com.diareat.diareat.auth.component.JwtTokenProvider; import com.diareat.diareat.food.controller.FoodController; import com.diareat.diareat.food.domain.FavoriteFood; import com.diareat.diareat.food.domain.Food; @@ -49,6 +50,9 @@ class FoodControllerTest { @MockBean private FoodService foodService; + @MockBean + private JwtTokenProvider jwtTokenProvider; + private final Long testUserId = 1L; private final Long testFoodId = 2L; private final Long testFavoriteFoodId = 3L; @@ -63,6 +67,8 @@ class FoodControllerTest { void setUp() throws NoSuchFieldException, IllegalAccessException { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); testUser.setId(testUserId); + when(jwtTokenProvider.validateToken(any(String.class))).thenReturn(true); + when(jwtTokenProvider.getUserPk(any(String.class))).thenReturn(testUserId); Field foodId = Food.class.getDeclaredField("id"); foodId.setAccessible(true); @@ -119,7 +125,8 @@ void testGetFoodListByDate() throws Exception { //When & Then mockMvc.perform(MockMvcRequestBuilders - .get("/api/food/{userId}", testUserId) + .get("/api/food") + .header("accessToken", "test") .param("yy", String.valueOf(date.getYear())) .param("mm", String.valueOf(date.getMonthValue())) .param("dd", String.valueOf(date.getDayOfMonth())) @@ -153,6 +160,7 @@ void testUpdateFood() throws Exception { mockMvc.perform(MockMvcRequestBuilders .post("/api/food/update") + .header("accessToken", "test") .param("yy", String.valueOf(date.getYear())) .param("mm", String.valueOf(date.getMonthValue())) .param("dd", String.valueOf(date.getDayOfMonth())) @@ -180,10 +188,10 @@ void testDeleteFood() throws Exception { mockMvc.perform(MockMvcRequestBuilders .delete("/api/food/{foodId}/delete", testFoodId) + .header("accessToken", "test") .param("yy", String.valueOf(date.getYear())) .param("mm", String.valueOf(date.getMonthValue())) .param("dd", String.valueOf(date.getDayOfMonth())) - .header("userId", testUserId) .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) @@ -225,7 +233,8 @@ void testGetFavoriteFoodList() throws Exception { //When & Then mockMvc.perform(MockMvcRequestBuilders - .get("/api/food/favorite/{userId}", testUserId) + .get("/api/food/favorite") + .header("accessToken", "test") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) @@ -268,7 +277,7 @@ void testDeleteFavoriteFood() throws Exception { mockMvc.perform(MockMvcRequestBuilders .delete("/api/food/favorite/{favoriteFoodId}", testFavoriteFoodId) - .header("userId", testUserId) + .header("accessToken", "test") .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.header.code").value(expectedResponse.getHeader().getCode())) @@ -292,7 +301,8 @@ void testGetNutritionSumByDate() throws Exception{ //When mockMvc.perform(MockMvcRequestBuilders - .get("/api/food/{userId}/nutrition", testUserId) + .get("/api/food/nutrition") + .header("accessToken", "test") .param("yy", String.valueOf(date.getYear())) .param("mm", String.valueOf(date.getMonthValue())) .param("dd", String.valueOf(date.getDayOfMonth()))) @@ -330,7 +340,8 @@ void testGetNutritionSumByWeek() throws Exception { //When mockMvc.perform(MockMvcRequestBuilders - .get("/api/food/{userId}/nutrition/recentWeek", testUserId) + .get("/api/food/nutrition/recentWeek") + .header("accessToken", "test") .param("yy", String.valueOf(date.getYear())) .param("mm", String.valueOf(date.getMonthValue())) .param("dd", String.valueOf(date.getDayOfMonth()))) @@ -368,7 +379,8 @@ void testGetNutritionSumByMonth() throws Exception { //When mockMvc.perform(MockMvcRequestBuilders - .get("/api/food/{userId}/nutrition/recentMonth", testUserId ) + .get("/api/food/nutrition/recentMonth") + .header("accessToken", "test") .param("yy", String.valueOf(date.getYear())) .param("mm", String.valueOf(date.getMonthValue())) .param("dd", String.valueOf(date.getDayOfMonth()))) @@ -412,7 +424,8 @@ void testGetScoreOfUserWithBestAndWorstFoods() throws Exception{ //When mockMvc.perform(MockMvcRequestBuilders - .get("/api/food/{userId}/score", testUserId, date.getYear(), date.getMonthValue(), date.getDayOfMonth()) + .get("/api/food/score") + .header("accessToken", "test") .param("yy", String.valueOf(date.getYear())) .param("mm", String.valueOf(date.getMonthValue())) .param("dd", String.valueOf(date.getDayOfMonth()))) @@ -444,7 +457,8 @@ void testGetAnalysisOfUser() throws Exception { //When mockMvc.perform(MockMvcRequestBuilders - .get("/api/food/{userId}/analysis", testUserId) + .get("/api/food/analysis") + .header("accessToken", "test") .param("yy", String.valueOf(2021)) .param("mm", String.valueOf(10)) .param("dd", String.valueOf(10))) @@ -479,7 +493,8 @@ void testGetUserRankByWeek() throws Exception{ //When mockMvc.perform(MockMvcRequestBuilders - .get("/api/food/{userId}/rank", testUserId) + .get("/api/food/rank") + .header("accessToken", "test") .param("yy", String.valueOf(2021)) .param("mm", String.valueOf(10)) .param("dd", String.valueOf(10))) diff --git a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java index 76247a4..d66e452 100644 --- a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java @@ -66,6 +66,8 @@ class UserControllerTest { void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); testUser.setId(testUserId); + when(jwtTokenProvider.validateToken(any(String.class))).thenReturn(true); + when(jwtTokenProvider.getUserPk(any(String.class))).thenReturn(testUserId); when(userService.getSimpleUserInfo(any(Long.class))) .thenReturn(ResponseSimpleUserDto.builder() .name(testUser.getName()) @@ -95,7 +97,7 @@ void testGetSimpleUserInfo() throws Exception { // When & Then mockMvc.perform(MockMvcRequestBuilders .get("/api/user/info/simple") - .header("accessToken", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE3MDQ0MzgxMDQsImV4cCI6MTczNTk3NDEwNCwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5hbWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.ApqSkkS8DqNG_H9abjJMRrzxONDj59cVGugJxPM_nBg") + .header("accessToken", "test") .accept(MediaType.APPLICATION_JSON) .with(authentication(authentication))) .andExpect(MockMvcResultMatchers.status().isOk()) From e22c47fdbb0500d5eceba76484d235383e32b8c9 Mon Sep 17 00:00:00 2001 From: CHAE Date: Mon, 22 Jan 2024 16:36:51 +0900 Subject: [PATCH 356/371] =?UTF-8?q?:wrench:=20Chore:=20SwaggerConfig=20jwt?= =?UTF-8?q?=20=EB=B3=B4=EC=95=88=EC=82=AC=ED=95=AD=20=EC=B6=94=EA=B0=80=20?= =?UTF-8?q?(#145)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/config/SwaggerConfig.java | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/config/SwaggerConfig.java b/src/main/java/com/diareat/diareat/config/SwaggerConfig.java index 3f108ca..99bf20f 100644 --- a/src/main/java/com/diareat/diareat/config/SwaggerConfig.java +++ b/src/main/java/com/diareat/diareat/config/SwaggerConfig.java @@ -7,10 +7,17 @@ import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.ApiKey; +import springfox.documentation.service.AuthorizationScope; +import springfox.documentation.service.SecurityReference; import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; +import java.util.Collections; +import java.util.List; + @Configuration @EnableSwagger2 public class SwaggerConfig implements WebMvcConfigurer { @@ -22,14 +29,31 @@ public Docket api() { .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() - .apiInfo(apiInfo()); + .apiInfo(apiInfo()) + .securityContexts(Collections.singletonList(securityContext())) + .securitySchemes(List.of(apiKey())); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Diareat API") .description("Diareat API 설명서") - .version("1.0") + .version("1.1") .build(); } + + private ApiKey apiKey() { + return new ApiKey("JWT", "Authorization", "header"); + } + + private SecurityContext securityContext() { + return SecurityContext.builder().securityReferences(defaultAuth()).build(); + } + + private List defaultAuth() { + AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEveryThing"); + AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; + authorizationScopes[0] = authorizationScope; + return List.of(new SecurityReference("JWT", authorizationScopes)); + } } From d4dd22bf34eb95867459f18efc89999634563347 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 23 Jan 2024 17:57:45 +0000 Subject: [PATCH 357/371] :construction_worker: chore: Update deployment to 40a11b5203fc67586023c3a7c7db0928a8f3bd8a --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 62f7ab7..c9acbf4 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 94530d3b + newTag: 40a11b52 From e01db150fe87b8d47619e070db3e8e4a6b405902 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 24 Jan 2024 17:46:11 +0900 Subject: [PATCH 358/371] =?UTF-8?q?:bug:=20fix:=20ddl=20=EC=97=85=EB=8D=B0?= =?UTF-8?q?=EC=9D=B4=ED=8A=B8=20(#147)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/application-db.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/application-db.properties b/src/main/resources/application-db.properties index c46d63d..50a99ea 100644 --- a/src/main/resources/application-db.properties +++ b/src/main/resources/application-db.properties @@ -1,5 +1,5 @@ spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver -spring.jpa.hibernate.ddl-auto=none +spring.jpa.hibernate.ddl-auto=update # Remote DB spring.datasource.url=${DB_ENDPOINT} From f4508ea61b5483f10240a452ac0a74ff71e0878a Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 24 Jan 2024 08:48:12 +0000 Subject: [PATCH 359/371] :construction_worker: chore: Update deployment to a1bd5bdccf7db95fc18b9caf0c29dc0781f118e6 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index c9acbf4..699b45a 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 40a11b52 + newTag: a1bd5bdc From d27afbb75c57da433ff422e487cf80362f0e2743 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 24 Jan 2024 18:34:05 +0900 Subject: [PATCH 360/371] =?UTF-8?q?:sparkles:=20feat:=20AccessToken=20&=20?= =?UTF-8?q?RefreshToken=20=EC=9D=B4=EB=B6=84=ED=99=94=20(#144)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/component/JwtTokenProvider.java | 28 +++++++++++++++++-- .../auth/controller/AuthController.java | 4 +-- .../auth/service/CustomUserDetailService.java | 1 + .../diareat/user/service/UserService.java | 3 +- 4 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java index 9bb6aaf..d64c936 100644 --- a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java +++ b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java @@ -6,6 +6,7 @@ import io.jsonwebtoken.SignatureAlgorithm; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; @@ -16,6 +17,7 @@ import javax.servlet.http.HttpServletRequest; import java.util.Base64; import java.util.Date; +import java.util.concurrent.TimeUnit; @RequiredArgsConstructor @Component @@ -26,6 +28,8 @@ public class JwtTokenProvider { private final UserDetailsService userDetailsService; + private final RedisTemplate redisTemplate; + // 객체 초기화, secretKey를 Base64로 인코딩 @PostConstruct protected void init() { @@ -33,17 +37,37 @@ protected void init() { } // 토큰 생성 - public String createToken(String userPk) { + public String createAccessToken(String userPk) { Claims claims = Jwts.claims().setSubject(userPk); // JWT payload 에 저장되는 정보단위 Date now = new Date(); return Jwts.builder() .setClaims(claims) // 정보 저장 .setIssuedAt(now) // 토큰 발행 시간 정보 - .setExpiration(new Date(now.getTime() + (720 * 60 * 1000L))) // 토큰 유효시각 설정 (12시간) + .setExpiration(new Date(now.getTime() + (60 * 60 * 1000L))) // 토큰 유효시각 설정 (1시간) .signWith(SignatureAlgorithm.HS256, secretKey) // 암호화 알고리즘과, secret 값 .compact(); } + public String createRefreshToken(String userPk) { + Claims claims = Jwts.claims().setSubject(userPk); // JWT payload 에 저장되는 정보단위 + Date now = new Date(); + String refreshToken = Jwts.builder() + .setClaims(claims) // 정보 저장 + .setIssuedAt(now) // 토큰 발행 시간 정보 + .setExpiration(new Date(now.getTime() + (7 * 24 * 60 * 60 * 1000L))) // 토큰 유효시각 설정 (1주일) + .signWith(SignatureAlgorithm.HS256, secretKey) + .compact(); + + redisTemplate.opsForValue().set( + userPk, + refreshToken, + 7 * 24 * 60 * 60 * 1000L, + TimeUnit.MILLISECONDS + ); + + return refreshToken; + } + // 인증 정보 조회 public Authentication getAuthentication(String token) { UserDetails userDetails = userDetailsService.loadUserByUsername(String.valueOf(this.getUserPk(token))); diff --git a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java index 78a5e8c..e44ef7f 100644 --- a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java +++ b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java @@ -29,7 +29,7 @@ public class AuthController { @PostMapping("/login") public ApiResponse authCheck(@RequestHeader String accessToken) { Long userId = kakaoAuthService.isSignedUp(accessToken); // 유저 고유번호 추출 - String jwt = (userId == null) ? null : jwtTokenProvider.createToken(userId.toString()); // 고유번호가 null이 아니라면 Jwt 토큰 발급 + String jwt = (userId == null) ? null : jwtTokenProvider.createAccessToken(userId.toString()); // 고유번호가 null이 아니라면 Jwt 토큰 발급 return ApiResponse.success(ResponseJwtDto.of(userId, jwt), ResponseCode.USER_LOGIN_SUCCESS.getMessage()); } @@ -38,7 +38,7 @@ public ApiResponse authCheck(@RequestHeader String accessToken) @PostMapping("/join") public ApiResponse saveUser(@Valid @RequestBody JoinUserDto joinUserDto) { Long userId = userService.saveUser(kakaoAuthService.createUserDto(joinUserDto)); - String jwt = jwtTokenProvider.createToken(userId.toString()); + String jwt = jwtTokenProvider.createAccessToken(userId.toString()); return ApiResponse.success(ResponseJwtDto.of(userId, jwt), ResponseCode.USER_CREATE_SUCCESS.getMessage()); } diff --git a/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java b/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java index f74e6fd..fd5b14b 100644 --- a/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java +++ b/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java @@ -16,6 +16,7 @@ public class CustomUserDetailService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException { + return userRepository.findById(Long.parseLong(id)) .orElseThrow(() -> new UsernameNotFoundException(ResponseCode.USER_NOT_FOUND.getMessage())); } diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 259b749..965e9c7 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -42,7 +42,8 @@ public Long saveUser(CreateUserDto createUserDto) { throw new UserException(ResponseCode.USER_NAME_ALREADY_EXIST); } if (userRepository.existsByKeyCode(createUserDto.getKeyCode())) { - log.info("이미 존재하는 키코드입니다 by {}", createUserDto.getKeyCode()); + log.info("이미 존재하는 " + + "con키코드입니다 by {}", createUserDto.getKeyCode()); throw new UserException(ResponseCode.USER_ALREADY_EXIST); } From 35e95b81d8a33bf82691858bafd41b96a68c6721 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 24 Jan 2024 18:55:18 +0900 Subject: [PATCH 361/371] =?UTF-8?q?:sparkles:=20feat:=20refreshToken=20?= =?UTF-8?q?=EC=9E=AC=EB=B0=9C=EA=B8=89=20=EB=A1=9C=EC=A7=81=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84=20(#144)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/auth/component/JwtAuthFilter.java | 2 +- .../auth/component/JwtTokenProvider.java | 11 +++++- .../auth/controller/AuthController.java | 36 +++++++++++++++---- .../diareat/auth/dto/ResponseJwtDto.java | 10 +++--- .../diareat/util/api/ResponseCode.java | 2 ++ 5 files changed, 47 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/diareat/diareat/auth/component/JwtAuthFilter.java b/src/main/java/com/diareat/diareat/auth/component/JwtAuthFilter.java index e90b21a..e0f61e5 100644 --- a/src/main/java/com/diareat/diareat/auth/component/JwtAuthFilter.java +++ b/src/main/java/com/diareat/diareat/auth/component/JwtAuthFilter.java @@ -23,7 +23,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha String token = jwtTokenProvider.resolveToken((HttpServletRequest) request); // 토큰이 유효하다면 - if (token != null && jwtTokenProvider.validateToken(token)) { + if (token != null && jwtTokenProvider.validateAccessToken(token)) { // 토큰으로부터 유저 정보를 받아 Authentication authentication = jwtTokenProvider.getAuthentication(token); // SecurityContext 에 객체 저장 diff --git a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java index d64c936..eaf4ddf 100644 --- a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java +++ b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java @@ -1,5 +1,7 @@ package com.diareat.diareat.auth.component; +import com.diareat.diareat.util.api.ResponseCode; +import com.diareat.diareat.util.exception.BaseException; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; @@ -80,7 +82,7 @@ public Long getUserPk(String token) { } // 토큰 유효성, 만료일자 확인 - public boolean validateToken(String jwtToken) { + public boolean validateAccessToken(String jwtToken) { try { Jws claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken); return !claims.getBody().getExpiration().before(new Date()); @@ -89,6 +91,13 @@ public boolean validateToken(String jwtToken) { } } + public void validateRefreshToken(Long userPK, String refreshToken) { + String redisRefreshToken = redisTemplate.opsForValue().get(String.valueOf(userPK)); + if (redisRefreshToken == null || !redisRefreshToken.equals(refreshToken)) { + throw new BaseException(ResponseCode.REFRESH_TOKEN_VALIDATION_FAILURE); + } + } + // Request의 Header에서 token 값 가져오기 public String resolveToken(HttpServletRequest request) { return request.getHeader("accessToken"); diff --git a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java index e44ef7f..96fde04 100644 --- a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java +++ b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java @@ -29,8 +29,13 @@ public class AuthController { @PostMapping("/login") public ApiResponse authCheck(@RequestHeader String accessToken) { Long userId = kakaoAuthService.isSignedUp(accessToken); // 유저 고유번호 추출 - String jwt = (userId == null) ? null : jwtTokenProvider.createAccessToken(userId.toString()); // 고유번호가 null이 아니라면 Jwt 토큰 발급 - return ApiResponse.success(ResponseJwtDto.of(userId, jwt), ResponseCode.USER_LOGIN_SUCCESS.getMessage()); + + ResponseJwtDto responseJwtDto = (userId == null) ? null : ResponseJwtDto.builder() + .accessToken(jwtTokenProvider.createAccessToken(userId.toString())) + .refreshToken(jwtTokenProvider.createRefreshToken(userId.toString())) + .build(); + + return ApiResponse.success(responseJwtDto, ResponseCode.USER_LOGIN_SUCCESS.getMessage()); } // 회원가입 (성공 시 Jwt 토큰 발급) @@ -38,14 +43,33 @@ public ApiResponse authCheck(@RequestHeader String accessToken) @PostMapping("/join") public ApiResponse saveUser(@Valid @RequestBody JoinUserDto joinUserDto) { Long userId = userService.saveUser(kakaoAuthService.createUserDto(joinUserDto)); - String jwt = jwtTokenProvider.createAccessToken(userId.toString()); - return ApiResponse.success(ResponseJwtDto.of(userId, jwt), ResponseCode.USER_CREATE_SUCCESS.getMessage()); + + ResponseJwtDto responseJwtDto = (userId == null) ? null : ResponseJwtDto.builder() + .accessToken(jwtTokenProvider.createAccessToken(userId.toString())) + .refreshToken(jwtTokenProvider.createRefreshToken(userId.toString())) + .build(); + + return ApiResponse.success(responseJwtDto, ResponseCode.USER_CREATE_SUCCESS.getMessage()); } // 토큰 검증 (Jwt 토큰을 서버에 전송하여, 서버가 유효한 토큰인지 확인하고 True 혹은 예외 반환) @Operation(summary = "[토큰 검증] 토큰 검증", description = "클라이언트가 가지고 있던 Jwt 토큰을 서버에 전송하여, 서버가 유효한 토큰인지 확인하고 OK 혹은 예외를 반환합니다.") @GetMapping("/token") - public ApiResponse tokenCheck(@RequestHeader String jwtToken) { - return ApiResponse.success(jwtTokenProvider.validateToken(jwtToken), ResponseCode.TOKEN_CHECK_SUCCESS.getMessage()); + public ApiResponse tokenCheck(@RequestHeader String accessToken) { + return ApiResponse.success(jwtTokenProvider.validateAccessToken(accessToken), ResponseCode.TOKEN_CHECK_SUCCESS.getMessage()); + } + + @Operation(summary = "[토큰 재발급] 토큰 재발급", description = "클라이언트가 가지고 있던 Refresh 토큰을 서버에 전송하여, 서버가 유효한 토큰인지 확인하고 OK 혹은 예외를 반환합니다.") + @PostMapping("/reissue") + public ApiResponse reissueToken(@RequestHeader String refreshToken) { + Long userId = jwtTokenProvider.getUserPk(refreshToken); + jwtTokenProvider.validateRefreshToken(userId, refreshToken); + + ResponseJwtDto responseJwtDto = (userId == null) ? null : ResponseJwtDto.builder() + .accessToken(jwtTokenProvider.createAccessToken(userId.toString())) + .refreshToken(jwtTokenProvider.createRefreshToken(userId.toString())) + .build(); + + return ApiResponse.success(responseJwtDto, ResponseCode.TOKEN_REISSUE_SUCCESS.getMessage()); } } diff --git a/src/main/java/com/diareat/diareat/auth/dto/ResponseJwtDto.java b/src/main/java/com/diareat/diareat/auth/dto/ResponseJwtDto.java index b26e30e..41df37b 100644 --- a/src/main/java/com/diareat/diareat/auth/dto/ResponseJwtDto.java +++ b/src/main/java/com/diareat/diareat/auth/dto/ResponseJwtDto.java @@ -1,16 +1,14 @@ package com.diareat.diareat.auth.dto; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; @Getter +@Builder @AllArgsConstructor public class ResponseJwtDto { - private Long id; - private String jwt; - - public static ResponseJwtDto of(Long id, String jwt) { - return new ResponseJwtDto(id, jwt); - } + private String accessToken; + private String refreshToken; } 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 ae34056..5943e1d 100644 --- a/src/main/java/com/diareat/diareat/util/api/ResponseCode.java +++ b/src/main/java/com/diareat/diareat/util/api/ResponseCode.java @@ -14,6 +14,7 @@ public enum ResponseCode { // 401 Unauthorized TOKEN_VALIDATION_FAILURE(HttpStatus.UNAUTHORIZED, false, "토큰 검증 실패"), + REFRESH_TOKEN_VALIDATION_FAILURE(HttpStatus.UNAUTHORIZED, false, "Refresh 토큰 검증 실패"), // 403 Forbidden FORBIDDEN(HttpStatus.FORBIDDEN, false, "권한이 없습니다."), @@ -56,6 +57,7 @@ public enum ResponseCode { FOOD_RANK_READ_SUCCESS(HttpStatus.OK, true, "식습관 점수 기반 랭킹 조회 성공"), TOKEN_CHECK_SUCCESS(HttpStatus.OK, true, "토큰 검증 완료"), + TOKEN_REISSUE_SUCCESS(HttpStatus.OK, true, "토큰 재발급 완료"), // 201 Created From da1e49fdc67dbb2b76645e3ae2f5b082944974bb Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 24 Jan 2024 20:17:47 +0900 Subject: [PATCH 362/371] =?UTF-8?q?:ambulance:=20hotfix:=20=EB=A9=94?= =?UTF-8?q?=EC=86=8C=EB=93=9C=20=EC=9D=B4=EB=A6=84=20=EB=B3=80=EA=B2=BD?= =?UTF-8?q?=EC=97=90=20=EC=9D=98=ED=95=B4=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=EC=BD=94=EB=93=9C=20=EC=88=98=EC=A0=95=20(#150)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/diareat/diareat/controller/FoodControllerTest.java | 2 +- .../java/com/diareat/diareat/controller/UserControllerTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java index f1c88c3..992a01e 100644 --- a/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/FoodControllerTest.java @@ -67,7 +67,7 @@ class FoodControllerTest { void setUp() throws NoSuchFieldException, IllegalAccessException { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); testUser.setId(testUserId); - when(jwtTokenProvider.validateToken(any(String.class))).thenReturn(true); + when(jwtTokenProvider.validateAccessToken(any(String.class))).thenReturn(true); when(jwtTokenProvider.getUserPk(any(String.class))).thenReturn(testUserId); Field foodId = Food.class.getDeclaredField("id"); diff --git a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java index d66e452..cb26ebc 100644 --- a/src/test/java/com/diareat/diareat/controller/UserControllerTest.java +++ b/src/test/java/com/diareat/diareat/controller/UserControllerTest.java @@ -66,7 +66,7 @@ class UserControllerTest { void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); testUser.setId(testUserId); - when(jwtTokenProvider.validateToken(any(String.class))).thenReturn(true); + when(jwtTokenProvider.validateAccessToken(any(String.class))).thenReturn(true); when(jwtTokenProvider.getUserPk(any(String.class))).thenReturn(testUserId); when(userService.getSimpleUserInfo(any(Long.class))) .thenReturn(ResponseSimpleUserDto.builder() From 5a887a67774fa0805cc40e54b0c1b13eb86cbdab Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 24 Jan 2024 11:24:32 +0000 Subject: [PATCH 363/371] :construction_worker: chore: Update deployment to 74743a8533623ac9f666b97fca4bdfe0a9cbd88b --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 699b45a..1ea297e 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: a1bd5bdc + newTag: 74743a85 From ad22c1c2bcde5a91bde9d14e4610ebd837fd5ee9 Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 25 Jan 2024 14:46:05 +0900 Subject: [PATCH 364/371] =?UTF-8?q?:sparkles:=20Fix:=20ResponseJwtDto?= =?UTF-8?q?=EC=97=90=20userId=20=EC=B6=94=EA=B0=80=20(#152)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/auth/controller/AuthController.java | 10 +++------- .../com/diareat/diareat/auth/dto/ResponseJwtDto.java | 1 + 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java index 96fde04..bd1396c 100644 --- a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java +++ b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java @@ -31,6 +31,7 @@ public ApiResponse authCheck(@RequestHeader String accessToken) Long userId = kakaoAuthService.isSignedUp(accessToken); // 유저 고유번호 추출 ResponseJwtDto responseJwtDto = (userId == null) ? null : ResponseJwtDto.builder() + .userId(userId) .accessToken(jwtTokenProvider.createAccessToken(userId.toString())) .refreshToken(jwtTokenProvider.createRefreshToken(userId.toString())) .build(); @@ -45,6 +46,7 @@ public ApiResponse saveUser(@Valid @RequestBody JoinUserDto join Long userId = userService.saveUser(kakaoAuthService.createUserDto(joinUserDto)); ResponseJwtDto responseJwtDto = (userId == null) ? null : ResponseJwtDto.builder() + .userId(userId) .accessToken(jwtTokenProvider.createAccessToken(userId.toString())) .refreshToken(jwtTokenProvider.createRefreshToken(userId.toString())) .build(); @@ -52,13 +54,6 @@ public ApiResponse saveUser(@Valid @RequestBody JoinUserDto join return ApiResponse.success(responseJwtDto, ResponseCode.USER_CREATE_SUCCESS.getMessage()); } - // 토큰 검증 (Jwt 토큰을 서버에 전송하여, 서버가 유효한 토큰인지 확인하고 True 혹은 예외 반환) - @Operation(summary = "[토큰 검증] 토큰 검증", description = "클라이언트가 가지고 있던 Jwt 토큰을 서버에 전송하여, 서버가 유효한 토큰인지 확인하고 OK 혹은 예외를 반환합니다.") - @GetMapping("/token") - public ApiResponse tokenCheck(@RequestHeader String accessToken) { - return ApiResponse.success(jwtTokenProvider.validateAccessToken(accessToken), ResponseCode.TOKEN_CHECK_SUCCESS.getMessage()); - } - @Operation(summary = "[토큰 재발급] 토큰 재발급", description = "클라이언트가 가지고 있던 Refresh 토큰을 서버에 전송하여, 서버가 유효한 토큰인지 확인하고 OK 혹은 예외를 반환합니다.") @PostMapping("/reissue") public ApiResponse reissueToken(@RequestHeader String refreshToken) { @@ -66,6 +61,7 @@ public ApiResponse reissueToken(@RequestHeader String refreshTok jwtTokenProvider.validateRefreshToken(userId, refreshToken); ResponseJwtDto responseJwtDto = (userId == null) ? null : ResponseJwtDto.builder() + .userId(userId) .accessToken(jwtTokenProvider.createAccessToken(userId.toString())) .refreshToken(jwtTokenProvider.createRefreshToken(userId.toString())) .build(); diff --git a/src/main/java/com/diareat/diareat/auth/dto/ResponseJwtDto.java b/src/main/java/com/diareat/diareat/auth/dto/ResponseJwtDto.java index 41df37b..25d74d7 100644 --- a/src/main/java/com/diareat/diareat/auth/dto/ResponseJwtDto.java +++ b/src/main/java/com/diareat/diareat/auth/dto/ResponseJwtDto.java @@ -9,6 +9,7 @@ @AllArgsConstructor public class ResponseJwtDto { + private Long userId; private String accessToken; private String refreshToken; } From b9494c44eb1831a724bf2d06c240a26ee0619473 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 25 Jan 2024 05:50:12 +0000 Subject: [PATCH 365/371] :construction_worker: chore: Update deployment to 197334145e17a09a53fc8b69a74bec9803f4122d --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 1ea297e..80587d5 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 74743a85 + newTag: "19733414" From 8811977e077cee31dd8d63286669ded7a0dc4036 Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 25 Jan 2024 15:15:55 +0900 Subject: [PATCH 366/371] =?UTF-8?q?:sparkles:=20Fix:=20Jwt=20=EC=9D=BC?= =?UTF-8?q?=EB=B6=80=20=EC=BD=94=EB=93=9C=20=EB=B3=B5=EA=B5=AC=20=EB=B0=8F?= =?UTF-8?q?=20RefreshToken=20=EB=A7=8C=EB=A3=8C=20=EA=B4=80=EB=A0=A8=20?= =?UTF-8?q?=EC=98=88=EC=99=B8=EC=B2=98=EB=A6=AC=20=EB=B0=98=EC=98=81=20(#1?= =?UTF-8?q?52)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diareat/diareat/auth/component/JwtTokenProvider.java | 4 ++-- .../diareat/diareat/auth/controller/AuthController.java | 7 +++++++ .../diareat/util/exception/GlobalExceptionHandler.java | 7 +++++++ .../diareat/diareat/util/exception/ValidException.java | 9 +++++++++ 4 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/diareat/diareat/util/exception/ValidException.java diff --git a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java index eaf4ddf..a446dcf 100644 --- a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java +++ b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java @@ -1,7 +1,7 @@ package com.diareat.diareat.auth.component; import com.diareat.diareat.util.api.ResponseCode; -import com.diareat.diareat.util.exception.BaseException; +import com.diareat.diareat.util.exception.ValidException; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; @@ -94,7 +94,7 @@ public boolean validateAccessToken(String jwtToken) { public void validateRefreshToken(Long userPK, String refreshToken) { String redisRefreshToken = redisTemplate.opsForValue().get(String.valueOf(userPK)); if (redisRefreshToken == null || !redisRefreshToken.equals(refreshToken)) { - throw new BaseException(ResponseCode.REFRESH_TOKEN_VALIDATION_FAILURE); + throw new ValidException(ResponseCode.REFRESH_TOKEN_VALIDATION_FAILURE); } } diff --git a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java index bd1396c..fb2f744 100644 --- a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java +++ b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java @@ -54,6 +54,13 @@ public ApiResponse saveUser(@Valid @RequestBody JoinUserDto join return ApiResponse.success(responseJwtDto, ResponseCode.USER_CREATE_SUCCESS.getMessage()); } + // 토큰 검증 (Jwt 토큰을 서버에 전송하여, 서버가 유효한 토큰인지 확인하고 True 혹은 예외 반환) + @Operation(summary = "[토큰 검증] 토큰 검증", description = "클라이언트가 가지고 있던 Jwt 토큰을 서버에 전송하여, 서버가 유효한 토큰인지 확인하고 OK 혹은 예외를 반환합니다.") + @GetMapping("/token") + public ApiResponse tokenCheck(@RequestHeader String accessToken) { + return ApiResponse.success(jwtTokenProvider.validateAccessToken(accessToken), ResponseCode.TOKEN_CHECK_SUCCESS.getMessage()); + } + @Operation(summary = "[토큰 재발급] 토큰 재발급", description = "클라이언트가 가지고 있던 Refresh 토큰을 서버에 전송하여, 서버가 유효한 토큰인지 확인하고 OK 혹은 예외를 반환합니다.") @PostMapping("/reissue") public ApiResponse reissueToken(@RequestHeader String refreshToken) { diff --git a/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java b/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java index 856271e..56f64f1 100644 --- a/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/diareat/diareat/util/exception/GlobalExceptionHandler.java @@ -46,4 +46,11 @@ public ApiResponse> handleInValidRequestException(MethodArgu }); return ApiResponse.fail(ResponseCode.BAD_REQUEST, errors); } + + @ExceptionHandler(ValidException.class) // jwt 토큰 만료 관련 예외처리 + @ResponseStatus(HttpStatus.UNAUTHORIZED) + public ApiResponse handleValidException(ValidException e) { + log.info("Invalid Jwt Token: {}", e.getMessage()); + return ApiResponse.fail(e.getResponseCode(), null); + } } diff --git a/src/main/java/com/diareat/diareat/util/exception/ValidException.java b/src/main/java/com/diareat/diareat/util/exception/ValidException.java new file mode 100644 index 0000000..df30754 --- /dev/null +++ b/src/main/java/com/diareat/diareat/util/exception/ValidException.java @@ -0,0 +1,9 @@ +package com.diareat.diareat.util.exception; + +import com.diareat.diareat.util.api.ResponseCode; + +public class ValidException extends BaseException { + public ValidException(ResponseCode responseCode) { + super(responseCode); + } +} From 51051184e8062e33b8c1f21abdf09ade385f63df Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 25 Jan 2024 06:22:35 +0000 Subject: [PATCH 367/371] :construction_worker: chore: Update deployment to 1b57aeeb0d7da1670e70d50a1d85578bafc26382 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 80587d5..84b5c96 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: "19733414" + newTag: 1b57aeeb From a2fa690371d3e5fbcd20d1f7496b9d95d0e77ea4 Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 25 Jan 2024 15:37:43 +0900 Subject: [PATCH 368/371] =?UTF-8?q?:sparkles:=20Fix:=20UserRepository=20en?= =?UTF-8?q?tityGraph=20=EA=B4=80=EB=A0=A8=20=EC=98=A4=EB=A5=98=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=20(#152)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/diareat/diareat/user/repository/UserRepository.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/com/diareat/diareat/user/repository/UserRepository.java b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java index 2010047..d9eac11 100644 --- a/src/main/java/com/diareat/diareat/user/repository/UserRepository.java +++ b/src/main/java/com/diareat/diareat/user/repository/UserRepository.java @@ -1,7 +1,6 @@ package com.diareat.diareat.user.repository; import com.diareat.diareat.user.domain.User; -import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; @@ -9,7 +8,6 @@ public interface UserRepository extends JpaRepository { - @EntityGraph(attributePaths = {"roles"}) List findAllByNameContaining(String name); // 회원이 팔로우를 위해 검색한 유저 목록 조회 boolean existsByName(String name); // 회원가입 시 닉네임 중복 확인 From d39f966ea2f11a5a4eadd05b470c8d533531d1ac Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 25 Jan 2024 06:55:02 +0000 Subject: [PATCH 369/371] :construction_worker: chore: Update deployment to 03de22cd160c39bd41c05872393c1c3d6f57fb7c --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 84b5c96..9672313 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 1b57aeeb + newTag: 03de22cd From eaa2aea6e618c190d647c74de46d67ab7c63b3f0 Mon Sep 17 00:00:00 2001 From: CHAE Date: Thu, 25 Jan 2024 16:07:17 +0900 Subject: [PATCH 370/371] =?UTF-8?q?:sparkles:=20Fix:=20user=EA=B0=9D?= =?UTF-8?q?=EC=B2=B4=20roles=20=EC=A7=80=EC=97=B0=EB=A1=9C=EB=94=A9=20?= =?UTF-8?q?=EC=82=AD=EC=A0=9C(#152)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/diareat/diareat/user/domain/User.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/diareat/diareat/user/domain/User.java b/src/main/java/com/diareat/diareat/user/domain/User.java index e8e8a54..32d2c1b 100644 --- a/src/main/java/com/diareat/diareat/user/domain/User.java +++ b/src/main/java/com/diareat/diareat/user/domain/User.java @@ -57,7 +57,7 @@ public class User implements UserDetails { // Jwt 전용 설정 (UserDetails 인터페이스 구현) - @ElementCollection(fetch = FetchType.LAZY) //roles 컬렉션 + @ElementCollection(fetch = FetchType.EAGER) //roles 컬렉션 private List roles = new ArrayList<>(); @Override //사용자의 권한 목록 리턴 From 8d38984fa3869840518ff78e6361e50ed386b05e Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 25 Jan 2024 07:16:05 +0000 Subject: [PATCH 371/371] :construction_worker: chore: Update deployment to 19305c8372817992f1af0638ef5cd5d66b5ae5b4 --- k8s/kustomization.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml index 9672313..f1f514b 100644 --- a/k8s/kustomization.yaml +++ b/k8s/kustomization.yaml @@ -5,4 +5,4 @@ resources: images: - name: synoti21/diareat-backend newName: synoti21/diareat-backend - newTag: 03de22cd + newTag: 19305c83