From 59c7074dbb82d34d6f4d55ca3b1e9f51f78580b2 Mon Sep 17 00:00:00 2001 From: psyeon1120 Date: Tue, 9 Jul 2024 23:48:47 +0900 Subject: [PATCH 1/9] =?UTF-8?q?#327=20refactor:=20fridge=20exception=20?= =?UTF-8?q?=EA=B5=AC=EC=A1=B0=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cart/service/CartServiceImpl.java | 10 +- .../food/entity/FoodCategory.java | 4 +- .../food/entity/FoodDeleteStatus.java | 4 +- .../fridge/dto/assembler/FridgeAssembler.java | 15 +-- .../dto/response/GetFridgesMainRes.java | 6 +- .../CannotDeleteFridgeException.java | 6 - .../FridgeFoodNotFoundException.java | 7 -- .../exception/FridgeNameEmptyException.java | 7 -- .../exception/FridgeNotFoundException.java | 7 -- .../exception/FridgeRemoveException.java | 5 - .../FridgeUserNotFoundException.java | 7 -- .../InvalidFridgeUserRoleException.java | 7 -- .../exception/PermissionDeniedException.java | 5 - .../fridge/service/FridgeServiceImpl.java | 105 +++++++++--------- .../global/exception/ReturnCode.java | 46 ++++---- .../user/service/UserServiceImpl.java | 7 +- 16 files changed, 95 insertions(+), 153 deletions(-) delete mode 100644 src/main/java/com/example/icebutler_server/fridge/exception/CannotDeleteFridgeException.java delete mode 100644 src/main/java/com/example/icebutler_server/fridge/exception/FridgeFoodNotFoundException.java delete mode 100644 src/main/java/com/example/icebutler_server/fridge/exception/FridgeNameEmptyException.java delete mode 100644 src/main/java/com/example/icebutler_server/fridge/exception/FridgeNotFoundException.java delete mode 100644 src/main/java/com/example/icebutler_server/fridge/exception/FridgeRemoveException.java delete mode 100644 src/main/java/com/example/icebutler_server/fridge/exception/FridgeUserNotFoundException.java delete mode 100644 src/main/java/com/example/icebutler_server/fridge/exception/InvalidFridgeUserRoleException.java delete mode 100644 src/main/java/com/example/icebutler_server/fridge/exception/PermissionDeniedException.java diff --git a/src/main/java/com/example/icebutler_server/cart/service/CartServiceImpl.java b/src/main/java/com/example/icebutler_server/cart/service/CartServiceImpl.java index 7bb7e957..d102099e 100644 --- a/src/main/java/com/example/icebutler_server/cart/service/CartServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/cart/service/CartServiceImpl.java @@ -12,8 +12,6 @@ import com.example.icebutler_server.food.entity.FoodCategory; import com.example.icebutler_server.food.repository.FoodRepository; import com.example.icebutler_server.fridge.entity.Fridge; -import com.example.icebutler_server.fridge.exception.FridgeNotFoundException; -import com.example.icebutler_server.fridge.exception.FridgeUserNotFoundException; import com.example.icebutler_server.fridge.repository.FridgeRepository; import com.example.icebutler_server.fridge.repository.FridgeUserRepository; import com.example.icebutler_server.global.exception.BaseException; @@ -29,9 +27,7 @@ import java.util.List; import java.util.stream.Collectors; -import static com.example.icebutler_server.global.exception.ReturnCode.NOT_FOUND_CART; -import static com.example.icebutler_server.global.exception.ReturnCode.NOT_FOUND_USER; - +import static com.example.icebutler_server.global.exception.ReturnCode.*; @RequiredArgsConstructor @Transactional(readOnly = true) @@ -105,8 +101,8 @@ public void deleteCartFoods(Long fridgeIdx, RemoveFoodFromCartRequest request, L private Cart getCart(Long userIdx, Long fridgeIdx) { User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(FridgeNotFoundException::new); - fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(FridgeUserNotFoundException::new); + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); return cartRepository.findByFridge_IdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_CART)); } } diff --git a/src/main/java/com/example/icebutler_server/food/entity/FoodCategory.java b/src/main/java/com/example/icebutler_server/food/entity/FoodCategory.java index 3e7a5228..ab068cee 100644 --- a/src/main/java/com/example/icebutler_server/food/entity/FoodCategory.java +++ b/src/main/java/com/example/icebutler_server/food/entity/FoodCategory.java @@ -5,7 +5,7 @@ import java.util.Arrays; -import static com.example.icebutler_server.global.exception.ReturnCode.NOT_FOUND_FOOD_CATEGORY; +import static com.example.icebutler_server.global.exception.ReturnCode.INVALID_FOOD_CATEGORY; import static com.example.icebutler_server.global.util.Constant.Food.ICON_EXTENSION; import static com.example.icebutler_server.global.util.Constant.Food.IMG_FOLDER; @@ -34,7 +34,7 @@ public String getImage() { public static FoodCategory getFoodCategoryByName(String name){ return Arrays.stream(FoodCategory.values()) .filter(r -> r.getName().equals(name)) - .findAny().orElseThrow(() -> new BaseException(NOT_FOUND_FOOD_CATEGORY)); + .findAny().orElseThrow(() -> new BaseException(INVALID_FOOD_CATEGORY)); } } diff --git a/src/main/java/com/example/icebutler_server/food/entity/FoodDeleteStatus.java b/src/main/java/com/example/icebutler_server/food/entity/FoodDeleteStatus.java index 46faa532..755ce428 100644 --- a/src/main/java/com/example/icebutler_server/food/entity/FoodDeleteStatus.java +++ b/src/main/java/com/example/icebutler_server/food/entity/FoodDeleteStatus.java @@ -5,7 +5,7 @@ import java.util.Arrays; -import static com.example.icebutler_server.global.exception.ReturnCode.NOT_FOUND_FOOD_DELETE_STATUS; +import static com.example.icebutler_server.global.exception.ReturnCode.INVALID_FOOD_DELETE_STATUS; @Getter public enum FoodDeleteStatus { @@ -21,6 +21,6 @@ private FoodDeleteStatus(String name) { public static FoodDeleteStatus getFoodDeleteStatusByName(String name){ return Arrays.stream(FoodDeleteStatus.values()) .filter(r -> r.getName().equals(name)) - .findAny().orElseThrow(() -> new BaseException(NOT_FOUND_FOOD_DELETE_STATUS)); + .findAny().orElseThrow(() -> new BaseException(INVALID_FOOD_DELETE_STATUS)); } } diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeAssembler.java b/src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeAssembler.java index e5cf9bac..e122a68c 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeAssembler.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeAssembler.java @@ -5,9 +5,8 @@ import com.example.icebutler_server.fridge.entity.Fridge; import com.example.icebutler_server.fridge.entity.FridgeFood; import com.example.icebutler_server.fridge.entity.FridgeUser; -import com.example.icebutler_server.fridge.exception.FridgeRemoveException; -import com.example.icebutler_server.fridge.exception.PermissionDeniedException; import com.example.icebutler_server.global.entity.FridgeRole; +import com.example.icebutler_server.global.exception.BaseException; import com.example.icebutler_server.user.entity.User; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; @@ -15,6 +14,9 @@ import java.util.ArrayList; import java.util.List; +import static com.example.icebutler_server.global.exception.ReturnCode.NO_PERMISSION; +import static com.example.icebutler_server.global.exception.ReturnCode.STILL_MEMBER_EXIST; + @Component @RequiredArgsConstructor public class FridgeAssembler { @@ -64,14 +66,9 @@ public UpdateMembersRes toUpdateFridgeMembers(List newMembers, List searchFridgeFood(List fridgeFoods, String keyword) { -// -// return null; -// } - public void removeFridge(FridgeUser owner, Fridge fridge, List fridgeUsers, List fridgeFoods) { - if (owner.getRole() != FridgeRole.OWNER) throw new PermissionDeniedException(); - if(fridgeUsers.size() > 1) throw new FridgeRemoveException(); + if (owner.getRole() != FridgeRole.OWNER) throw new BaseException(NO_PERMISSION); + if(fridgeUsers.size() > 1) throw new BaseException(STILL_MEMBER_EXIST); fridgeUsers.forEach(FridgeUser::remove); // fridgeFoods.forEach(FridgeFood::remove); diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/GetFridgesMainRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/GetFridgesMainRes.java index 39e4797d..6798531c 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/GetFridgesMainRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/GetFridgesMainRes.java @@ -1,7 +1,7 @@ package com.example.icebutler_server.fridge.dto.response; import com.example.icebutler_server.fridge.entity.FridgeUser; -import com.example.icebutler_server.fridge.exception.FridgeUserNotFoundException; +import com.example.icebutler_server.global.exception.BaseException; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Builder; @@ -11,6 +11,8 @@ import java.util.List; import java.util.stream.Collectors; +import static com.example.icebutler_server.global.exception.ReturnCode.NOT_FOUND_FRIDGE_USER; + @Data @Builder @AllArgsConstructor @@ -23,7 +25,7 @@ public class GetFridgesMainRes { public static GetFridgesMainRes toDto(List> fridgeUserListList, Long userIdx) { GetFridgesMainRes getFridgesMainRes = new GetFridgesMainRes(); - List fridgeUsers = fridgeUserListList.stream().map(m -> m.stream().filter(f -> f.getUser().getId().equals(userIdx)).findAny().orElseThrow(FridgeUserNotFoundException::new)).collect(Collectors.toList()); + List fridgeUsers = fridgeUserListList.stream().map(m -> m.stream().filter(f -> f.getUser().getId().equals(userIdx)).findAny().orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER))).collect(Collectors.toList()); getFridgesMainRes.fridgeList = fridgeUsers.stream().map(m -> FridgeRes.toDto(m.getFridge(), fridgeUserListList)).collect(Collectors.toList()); return getFridgesMainRes; diff --git a/src/main/java/com/example/icebutler_server/fridge/exception/CannotDeleteFridgeException.java b/src/main/java/com/example/icebutler_server/fridge/exception/CannotDeleteFridgeException.java deleted file mode 100644 index 07153764..00000000 --- a/src/main/java/com/example/icebutler_server/fridge/exception/CannotDeleteFridgeException.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.example.icebutler_server.fridge.exception; - -public class CannotDeleteFridgeException extends RuntimeException { - public CannotDeleteFridgeException() { super("해당 냉장고에 멤버가 있어서 삭제할 수 없습니다."); - } -} diff --git a/src/main/java/com/example/icebutler_server/fridge/exception/FridgeFoodNotFoundException.java b/src/main/java/com/example/icebutler_server/fridge/exception/FridgeFoodNotFoundException.java deleted file mode 100644 index e7108edd..00000000 --- a/src/main/java/com/example/icebutler_server/fridge/exception/FridgeFoodNotFoundException.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.example.icebutler_server.fridge.exception; - -public class FridgeFoodNotFoundException extends RuntimeException { - public FridgeFoodNotFoundException(){ - super("요청한 idx를 가진 냉장고 내 식품을 찾을 수 없습니다."); - } -} diff --git a/src/main/java/com/example/icebutler_server/fridge/exception/FridgeNameEmptyException.java b/src/main/java/com/example/icebutler_server/fridge/exception/FridgeNameEmptyException.java deleted file mode 100644 index 6a3638ac..00000000 --- a/src/main/java/com/example/icebutler_server/fridge/exception/FridgeNameEmptyException.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.example.icebutler_server.fridge.exception; - -public class FridgeNameEmptyException extends RuntimeException { - public FridgeNameEmptyException(){ - super("냉장고 이름를 입력하지 않았습니다."); - } -} diff --git a/src/main/java/com/example/icebutler_server/fridge/exception/FridgeNotFoundException.java b/src/main/java/com/example/icebutler_server/fridge/exception/FridgeNotFoundException.java deleted file mode 100644 index 7d1b8067..00000000 --- a/src/main/java/com/example/icebutler_server/fridge/exception/FridgeNotFoundException.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.example.icebutler_server.fridge.exception; - -public class FridgeNotFoundException extends RuntimeException { - public FridgeNotFoundException(){ - super("요청한 idx를 가진 냉장고를 찾을 수 없습니다."); - } -} diff --git a/src/main/java/com/example/icebutler_server/fridge/exception/FridgeRemoveException.java b/src/main/java/com/example/icebutler_server/fridge/exception/FridgeRemoveException.java deleted file mode 100644 index 554f93e3..00000000 --- a/src/main/java/com/example/icebutler_server/fridge/exception/FridgeRemoveException.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.example.icebutler_server.fridge.exception; - -public class FridgeRemoveException extends RuntimeException { - public FridgeRemoveException(){super("올바르지 않은 냉장고 삭제 조건입니다.");} -} diff --git a/src/main/java/com/example/icebutler_server/fridge/exception/FridgeUserNotFoundException.java b/src/main/java/com/example/icebutler_server/fridge/exception/FridgeUserNotFoundException.java deleted file mode 100644 index f4126c0a..00000000 --- a/src/main/java/com/example/icebutler_server/fridge/exception/FridgeUserNotFoundException.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.example.icebutler_server.fridge.exception; - -public class FridgeUserNotFoundException extends RuntimeException { - public FridgeUserNotFoundException(){ - super("냉장고의 멤버가 아닙니다."); - } -} diff --git a/src/main/java/com/example/icebutler_server/fridge/exception/InvalidFridgeUserRoleException.java b/src/main/java/com/example/icebutler_server/fridge/exception/InvalidFridgeUserRoleException.java deleted file mode 100644 index e3eba49d..00000000 --- a/src/main/java/com/example/icebutler_server/fridge/exception/InvalidFridgeUserRoleException.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.example.icebutler_server.fridge.exception; - -public class InvalidFridgeUserRoleException extends RuntimeException { - public InvalidFridgeUserRoleException(){ - super("냉장고를 생성한 유저가 아닙니다."); - } -} diff --git a/src/main/java/com/example/icebutler_server/fridge/exception/PermissionDeniedException.java b/src/main/java/com/example/icebutler_server/fridge/exception/PermissionDeniedException.java deleted file mode 100644 index 8089c47f..00000000 --- a/src/main/java/com/example/icebutler_server/fridge/exception/PermissionDeniedException.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.example.icebutler_server.fridge.exception; - -public class PermissionDeniedException extends RuntimeException { - public PermissionDeniedException() {super("올바르지 않은 접근 권한입니다.");} -} diff --git a/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java b/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java index 7865a8e0..874d3199 100644 --- a/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java @@ -14,7 +14,6 @@ import com.example.icebutler_server.fridge.entity.Fridge; import com.example.icebutler_server.fridge.entity.FridgeFood; import com.example.icebutler_server.fridge.entity.FridgeUser; -import com.example.icebutler_server.fridge.exception.*; import com.example.icebutler_server.fridge.repository.FridgeFood.FridgeFoodRepository; import com.example.icebutler_server.fridge.repository.FridgeRepository; import com.example.icebutler_server.fridge.repository.FridgeUserRepository; @@ -36,19 +35,19 @@ import java.util.Map; import java.util.stream.Collectors; -import static com.example.icebutler_server.global.exception.ReturnCode.NOT_FOUND_USER; +import static com.example.icebutler_server.global.exception.ReturnCode.*; @Transactional(readOnly = true) @Service @RequiredArgsConstructor public class FridgeServiceImpl implements FridgeService { - private final FridgeRepository fridgeRepository; - private final FridgeUserRepository fridgeUserRepository; - private final UserRepository userRepository; - private final FridgeFoodRepository fridgeFoodRepository; - private final FoodRepository foodRepository; - private final CartRepository cartRepository; + private final FridgeRepository fridgeRepository; + private final FridgeUserRepository fridgeUserRepository; + private final UserRepository userRepository; + private final FridgeFoodRepository fridgeFoodRepository; + private final FoodRepository foodRepository; + private final CartRepository cartRepository; private final FridgeAssembler fridgeAssembler; private final FridgeFoodAssembler fridgeFoodAssembler; @@ -59,7 +58,7 @@ public class FridgeServiceImpl implements FridgeService { @Override public FridgeMainRes getFoods(Long fridgeIdx, Long userIdx, String category) { User user = this.userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(FridgeNotFoundException::new); + Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); if (category == null) { // 값이 없으면 전체 조회 @@ -73,7 +72,7 @@ public FridgeMainRes getFoods(Long fridgeIdx, Long userIdx, String category) { @Override @Transactional public Long registerFridge(FridgeRegisterReq registerFridgeReq, Long ownerIdx) { - if (!StringUtils.hasText(registerFridgeReq.getFridgeName())) throw new FridgeNameEmptyException(); + if (!StringUtils.hasText(registerFridgeReq.getFridgeName())) throw new BaseException(INVALID_PARAM); Fridge fridge = fridgeAssembler.toEntity(registerFridgeReq); fridgeRepository.save(fridge); @@ -106,17 +105,17 @@ public Long registerFridge(FridgeRegisterReq registerFridgeReq, Long ownerIdx) { @Transactional public void modifyFridge(Long fridgeIdx, FridgeModifyReq updateFridgeReq, Long userIdx) { User user = this.userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(FridgeNotFoundException::new); - FridgeUser owner = this.fridgeUserRepository.findByFridgeAndUserAndRoleAndIsEnable(fridge, user, FridgeRole.OWNER, true).orElseThrow(InvalidFridgeUserRoleException::new); + Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + FridgeUser owner = this.fridgeUserRepository.findByFridgeAndUserAndRoleAndIsEnable(fridge, user, FridgeRole.OWNER, true).orElseThrow(() -> new BaseException(NO_PERMISSION)); // 오너 업데이트 if (!owner.getUser().getId().equals(updateFridgeReq.getNewOwnerIdx())) { - FridgeUser newOwner = this.fridgeUserRepository.findByFridgeAndUser_IdAndRoleAndIsEnableAndUser_IsEnable(fridge, updateFridgeReq.getNewOwnerIdx(), FridgeRole.MEMBER, true, true).orElseThrow(FridgeUserNotFoundException::new); + FridgeUser newOwner = this.fridgeUserRepository.findByFridgeAndUser_IdAndRoleAndIsEnableAndUser_IsEnable(fridge, updateFridgeReq.getNewOwnerIdx(), FridgeRole.MEMBER, true, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); this.fridgeAssembler.toUpdateFridgeOwner(owner, newOwner); } - // 냉장고 정보 (이름, 설명) 업데이트 - if (!StringUtils.hasText(updateFridgeReq.getFridgeName())) throw new FridgeNameEmptyException(); + // 냉장고 정보 (이름, 설명) 업데이트 + if (!StringUtils.hasText(updateFridgeReq.getFridgeName())) throw new BaseException(INVALID_PARAM); // 멤버 업데이트 if (updateFridgeReq.getMembers() != null) { @@ -152,8 +151,8 @@ public void modifyFridge(Long fridgeIdx, FridgeModifyReq updateFridgeReq, Long u @Transactional public Long removeFridge(Long fridgeIdx, Long userId) { User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(FridgeNotFoundException::new); - FridgeUser owner = (FridgeUser) fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(FridgeUserNotFoundException::new); + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + FridgeUser owner = (FridgeUser) fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); List fridgeUsers = fridgeUserRepository.findByFridgeAndIsEnable(fridge, true); List fridgeFoods = fridgeFoodRepository.findByFridgeAndIsEnableOrderByShelfLife(fridge, true); @@ -168,10 +167,10 @@ public Long removeFridge(Long fridgeIdx, Long userId) { @Transactional public Long removeFridgeUser(Long fridgeIdx, Long userIdx) { User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(FridgeNotFoundException::new); - FridgeUser fridgeUser = (FridgeUser) fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(FridgeUserNotFoundException::new); + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + FridgeUser fridgeUser = (FridgeUser) fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); - if (fridgeUser.getRole() == FridgeRole.OWNER) throw new PermissionDeniedException(); + if (fridgeUser.getRole() == FridgeRole.OWNER) throw new BaseException(NO_PERMISSION); fridgeUser.remove(); return fridge.getId(); @@ -179,7 +178,7 @@ public Long removeFridgeUser(Long fridgeIdx, Long userIdx) { @Override public List searchFridgeFood(Long fridgeIdx, Long userIdx, String keyword) { - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(FridgeNotFoundException::new); + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); List searchFoods = fridgeFoodRepository.findByFoodDetailNameContainingAndFridgeAndIsEnable(keyword, fridge, true); return searchFoods.stream().map(FridgeFoodsRes::toDto).collect(Collectors.toList()); } @@ -187,9 +186,9 @@ public List searchFridgeFood(Long fridgeIdx, Long userIdx, Strin @Override public FridgeFoodRes getFridgeFood(Long fridgeIdx, Long fridgeFoodIdx, Long userIdx) { User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(FridgeNotFoundException::new); - fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(FridgeUserNotFoundException::new); - FridgeFood fridgeFood = fridgeFoodRepository.findByIdAndFridgeAndIsEnable(fridgeFoodIdx, fridge, true).orElseThrow(FridgeFoodNotFoundException::new); + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); + FridgeFood fridgeFood = fridgeFoodRepository.findByIdAndFridgeAndIsEnable(fridgeFoodIdx, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_FOOD)); return FridgeFoodRes.toDto(fridgeFood); } @@ -198,15 +197,15 @@ public FridgeFoodRes getFridgeFood(Long fridgeIdx, Long fridgeFoodIdx, Long user @Transactional public void addFridgeFood(FridgeFoodsReq fridgeFoodsReq, Long fridgeIdx, Long userIdx) { User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(FridgeNotFoundException::new); - fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(FridgeUserNotFoundException::new); + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); List fridgeFoods = new ArrayList<>(); for (FridgeFoodReq fridgeFoodReq : fridgeFoodsReq.getFridgeFoods()) { User owner = null; if (fridgeFoodReq.getOwnerIdx() != null) { owner = userRepository.findByIdAndIsEnable(fridgeFoodReq.getOwnerIdx(), true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - fridgeUserRepository.findByUserAndFridgeAndIsEnable(owner, fridge, true).orElseThrow(FridgeUserNotFoundException::new); + fridgeUserRepository.findByUserAndFridgeAndIsEnable(owner, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); } Food food = foodRepository.findByFoodName(fridgeFoodReq.getFoodName()) .orElseGet(() -> { @@ -226,11 +225,11 @@ public void modifyFridgeFood(Long fridgeIdx, Long fridgeFoodIdx, FridgeFoodReq f User user = this.userRepository.findByIdAndIsEnable(userIdx, true) .orElseThrow(() -> new BaseException(NOT_FOUND_USER)); Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true) - .orElseThrow(FridgeNotFoundException::new); + .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, user, true) - .orElseThrow(FridgeUserNotFoundException::new); + .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); FridgeFood modifyFridgeFood = this.fridgeFoodRepository.findByIdAndFridgeAndIsEnable(fridgeFoodIdx, fridge, true) - .orElseThrow(FridgeFoodNotFoundException::new); + .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_FOOD)); if (!modifyFridgeFood.getFood().getFoodName().equals(fridgeFoodReq.getFoodName())) { Food food = this.foodRepository.findByFoodName(fridgeFoodReq.getFoodName()) @@ -250,7 +249,7 @@ public void modifyFridgeFood(Long fridgeIdx, Long fridgeFoodIdx, FridgeFoodReq f User newOwner = this.userRepository.findByIdAndIsEnable(fridgeFoodReq.getOwnerIdx(), true) .orElseThrow(() -> new BaseException(NOT_FOUND_USER)); this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, newOwner, true) - .orElseThrow(FridgeUserNotFoundException::new); + .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); if (!newOwner.equals(modifyFridgeFood.getOwner())) this.fridgeFoodAssembler.toUpdateFridgeFoodOwner(modifyFridgeFood, newOwner); } @@ -263,31 +262,31 @@ public void deleteFridgeFood(DeleteFridgeFoodsReq deleteFridgeFoodsReq, String t User user = this.userRepository.findByIdAndIsEnable(userIdx, true) .orElseThrow(() -> new BaseException(NOT_FOUND_USER)); Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true) - .orElseThrow(FridgeNotFoundException::new); + .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, user, true) - .orElseThrow(FridgeUserNotFoundException::new); + .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); List deleteFridgeFoods = deleteFridgeFoodsReq.getDeleteFoods().stream() .map(foodIdx -> this.fridgeFoodRepository.findByIdAndFridgeAndIsEnable(foodIdx, fridge, true) - .orElseThrow(FridgeFoodNotFoundException::new)) + .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_FOOD))) .collect(Collectors.toList()); deleteFridgeFoods.forEach(food -> food.removeWithStatus(deleteStatus)); } - @Override - //냉장고 내 유저 조회 - public FridgeUserMainRes searchMembers(Long fridgeIdx, Long userIdx){ - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true) - .orElseThrow(FridgeNotFoundException::new); - return FridgeUserMainRes.doDto(fridgeUserRepository.findByFridgeAndIsEnable(fridge,true)); - } + @Override + //냉장고 내 유저 조회 + public FridgeUserMainRes searchMembers(Long fridgeIdx, Long userIdx) { + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true) + .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + return FridgeUserMainRes.doDto(fridgeUserRepository.findByFridgeAndIsEnable(fridge, true)); + } @Override public FridgeFoodsStatistics getFridgeFoodStatistics(Long fridgeIdx, String deleteCategory, Long userIdx, Integer year, Integer month) { User user = this.userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(FridgeNotFoundException::new); - this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, user, true).orElseThrow(FridgeUserNotFoundException::new); + Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, user, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); Map deleteStatusList = new HashMap<>(); @@ -299,30 +298,30 @@ public FridgeFoodsStatistics getFridgeFoodStatistics(Long fridgeIdx, String dele return this.fridgeFoodAssembler.toFoodStatisticsByDeleteStatus(deleteStatusList); } - public SelectFridgesMainRes selectFridges(Long userIdx) { - User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - return SelectFridgesMainRes.toDto(fridgeUserRepository.findByUserAndIsEnable(user, true)); - } + public SelectFridgesMainRes selectFridges(Long userIdx) { + User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + return SelectFridgesMainRes.toDto(fridgeUserRepository.findByUserAndIsEnable(user, true)); + } public GetFridgesMainRes myFridge(Long userIdx) { User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); // 가정용 냉장고 조회 List fridgeUsers = fridgeUserRepository.findByUserAndIsEnable(user, true); - List fridges = fridgeUsers.stream().map(m -> fridgeRepository.findByIdAndIsEnable(m.getFridge().getId(), true).orElseThrow(FridgeNotFoundException::new)).collect(Collectors.toList()); + List fridges = fridgeUsers.stream().map(m -> fridgeRepository.findByIdAndIsEnable(m.getFridge().getId(), true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE))).collect(Collectors.toList()); List> fridgeUserListList = fridges.stream().map(m -> fridgeUserRepository.findByFridgeAndIsEnableOrderByRoleDesc(m, true)).collect(Collectors.toList()); - return GetFridgesMainRes.toDto(fridgeUserListList, userIdx); + return GetFridgesMainRes.toDto(fridgeUserListList, userIdx); - } + } // 사용자가 속한 가정용/공용 냉장고 food list public RecipeFridgeFoodListsRes getFridgeUserFoodList(Long fridgeIdx, Long userIdx) { User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(FridgeNotFoundException::new); - this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, user, true).orElseThrow(FridgeUserNotFoundException::new); + Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, user, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); return RecipeFridgeFoodListsRes.toDto(this.fridgeFoodRepository.findByUserForFridgeRecipeFoodList(fridge)); } @@ -337,7 +336,7 @@ public void notifyFridgeFood() { try { alarmService.sendShelfLifeAlarm(user.getUser(), food.getFridge().getFridgeName(), food.getFood().getFoodName()); } catch (IOException e) { - throw new FridgeNameEmptyException(); //todo: 예외처리 바꾸기 + throw new BaseException(INTERNAL_SERVER_ERROR); //todo: 예외처리 바꾸기 } }); }); diff --git a/src/main/java/com/example/icebutler_server/global/exception/ReturnCode.java b/src/main/java/com/example/icebutler_server/global/exception/ReturnCode.java index 52eb057d..5e420526 100644 --- a/src/main/java/com/example/icebutler_server/global/exception/ReturnCode.java +++ b/src/main/java/com/example/icebutler_server/global/exception/ReturnCode.java @@ -12,37 +12,37 @@ public enum ReturnCode { // 성공 SUCCESS("S0000", HttpStatus.OK, "요청에 성공했습니다."), - // Auth - EXPIRED_TOKEN("A0001", HttpStatus.UNAUTHORIZED, "만료된 토큰입니다. 다시 발급해주세요."), - + // Global + INVALID_PARAM("G0000", HttpStatus.BAD_REQUEST, "잘못된 파라미터입니다."), + NO_PERMISSION("G0001", HttpStatus.FORBIDDEN, "권한이 없습니다."), + // Auth + EXPIRED_TOKEN("A0000", HttpStatus.UNAUTHORIZED, "만료된 토큰입니다. 다시 발급해주세요."), - // User - INVALID_PROVIDER("U0000", HttpStatus.BAD_REQUEST, "부적절한 소셜로그인 provider 입력입니다."), - UNAUTHORIZED_USER("U0001", HttpStatus.UNAUTHORIZED, "관리자에 의해 서비스 이용이 제한되었습니다."), - NOT_FOUND_EMAIL("U0002", HttpStatus.NOT_FOUND, "사용자 이메일 값을 찾아올 수 없습니다."), - ALREADY_WITHDRAWN_USER("U0003", HttpStatus.NOT_FOUND, "이미 탈퇴한 회원입니다."), - INVALID_NICKNAME("U0004", HttpStatus.BAD_REQUEST, "올바르지 않은 닉네임 형식입니다."), - NOT_FOUND_USER("U0005", HttpStatus.NOT_FOUND, "해당 유저를 찾을 수 없습니다."), + // Cart + NOT_FOUND_CART("C0000", HttpStatus.NOT_FOUND, "존재하지 않는 장바구니입니다."), + // 서버 에러 + INTERNAL_SERVER_ERROR("E0000", HttpStatus.INTERNAL_SERVER_ERROR, "서버 에러입니다."), // Food - NOT_FOUND_FOOD_CATEGORY("F0000", HttpStatus.NOT_FOUND, "존재하지 않는 카테고리입니다."), + INVALID_FOOD_CATEGORY("F0000", HttpStatus.BAD_REQUEST, "존재하지 않는 카테고리입니다."), NOT_FOUND_BARCODE_FOOD("F0001", HttpStatus.NOT_FOUND, "해당 바코드의 상품을 찾을 수 없습니다."), - ALREADY_EXIST_FOOD_NAME("F0002", HttpStatus.CONFLICT, "중복된 음식 이름입니다."), - NOT_FOUND_FOOD_DELETE_STATUS("F0003", HttpStatus.NOT_FOUND, "존재하지 않는 식품삭제 타입입니다."), - - // Cart - NOT_FOUND_CART("C0000", HttpStatus.NOT_FOUND, "장바구니를 찾을 수 없습니다."), + ALREADY_EXIST_FOOD_NAME("F0002", HttpStatus.CONFLICT, "이미 존재하는 식품명입니다."), + INVALID_FOOD_DELETE_STATUS("F0003", HttpStatus.BAD_REQUEST, "존재하지 않는 식품삭제 타입입니다."), + // Fridge(Refrigerator) + NOT_FOUND_FRIDGE("R0000", HttpStatus.CONFLICT, "존재하지 않는 냉장고입니다."), + STILL_MEMBER_EXIST("R0001", HttpStatus.CONFLICT, "해당 냉장고에 사용자가 존재합니다."), + NOT_FOUND_FRIDGE_FOOD("R0002", HttpStatus.NOT_FOUND, "해당 냉장고에 존재하지 않는 식품입니다."), + NOT_FOUND_FRIDGE_USER("R0003", HttpStatus.NOT_FOUND, "해당 냉장고에 존재하지 않는 사용자입니다."), - - - - - - // 서버 에러 - INTERNAL_SERVER_ERROR("E0000", HttpStatus.INTERNAL_SERVER_ERROR, "서버 에러입니다."), + // User + NOT_FOUND_USER("U0000", HttpStatus.NOT_FOUND, "존재하지 않는 사용자입니다."), + ALREADY_WITHDRAWN_USER("U0001", HttpStatus.NOT_FOUND, "이미 탈퇴한 회원입니다."), + BLOCKED_USER("U0002", HttpStatus.FORBIDDEN, "관리자에 의해 서비스 이용이 제한되었습니다."), + INVALID_PROVIDER("U0003", HttpStatus.BAD_REQUEST, "부적절한 소셜로그인 provider 입력입니다."), + INVALID_NICKNAME("U0004", HttpStatus.BAD_REQUEST, "올바르지 않은 닉네임 형식입니다."), ; public final String code; diff --git a/src/main/java/com/example/icebutler_server/user/service/UserServiceImpl.java b/src/main/java/com/example/icebutler_server/user/service/UserServiceImpl.java index 394bf17d..76fbf50e 100644 --- a/src/main/java/com/example/icebutler_server/user/service/UserServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/user/service/UserServiceImpl.java @@ -3,7 +3,6 @@ import com.example.icebutler_server.alarm.repository.PushNotificationRepository; import com.example.icebutler_server.fridge.entity.Fridge; import com.example.icebutler_server.fridge.entity.FridgeUser; -import com.example.icebutler_server.fridge.exception.CannotDeleteFridgeException; import com.example.icebutler_server.fridge.repository.FridgeRepository; import com.example.icebutler_server.fridge.repository.FridgeUserRepository; import com.example.icebutler_server.global.entity.FridgeRole; @@ -54,7 +53,7 @@ public PostUserRes join(PostUserReq postUserReq) { User user = checkUserInfo(postUserReq.getEmail(), postUserReq.getProvider()); if (user == null) user = saveUser(postUserReq); // 정지된 회원은 재가입 불가 - if (user.getIsDenied().equals(true)) throw new BaseException(UNAUTHORIZED_USER); + if (user.getIsDenied().equals(true)) throw new BaseException(BLOCKED_USER); // 자진 탈퇴 회원은 재가입 처리 if (user.getIsEnable().equals(false)) user=saveUser(postUserReq); // 새로운 행 추가 @@ -78,7 +77,7 @@ public PostUserRes login(LoginUserReq loginUserReq) { public User checkUserInfo(String email, String provider) { if (Provider.getProviderByName(provider) == null) throw new BaseException(INVALID_PROVIDER); - if (!StringUtils.hasText(email)) throw new BaseException(NOT_FOUND_EMAIL); + if (!StringUtils.hasText(email)) throw new BaseException(INVALID_PARAM); return userRepository.findByEmailAndProvider(email, Provider.getProviderByName(provider)); } @@ -135,7 +134,7 @@ public void deleteUser(Long userIdx) { Fridge fridge = fridgeOwner.getFridge(); List fridgeMembers = fridgeUserRepository.findByFridgeAndRoleAndIsEnable(fridge, FridgeRole.MEMBER, true); if (fridgeMembers.size() > 0) { - throw new CannotDeleteFridgeException(); + throw new BaseException(STILL_MEMBER_EXIST); } fridgeRepository.delete(fridge); } From 5772a5e243cda4028711bccfb7eafc0b045360ec Mon Sep 17 00:00:00 2001 From: psyeon1120 Date: Tue, 9 Jul 2024 23:49:53 +0900 Subject: [PATCH 2/9] =?UTF-8?q?#327=20remove:=20fridge=20=EA=B4=80?= =?UTF-8?q?=EB=A0=A8=20=ED=95=84=EC=9A=94=EC=97=86=EB=8A=94=20=ED=8C=8C?= =?UTF-8?q?=EC=9D=BC=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../fridge/dto/fridge/response/MultiFridgeRes.java | 0 .../fridge/dto/fridge/response/SelectFridgesMainRes.java | 0 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/main/java/com/example/icebutler_server/fridge/dto/fridge/response/MultiFridgeRes.java delete mode 100644 src/main/java/com/example/icebutler_server/fridge/dto/fridge/response/SelectFridgesMainRes.java diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/fridge/response/MultiFridgeRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/fridge/response/MultiFridgeRes.java deleted file mode 100644 index e69de29b..00000000 diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/fridge/response/SelectFridgesMainRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/fridge/response/SelectFridgesMainRes.java deleted file mode 100644 index e69de29b..00000000 From be5db9cd660923d5184bca8edd850037be3dc2ae Mon Sep 17 00:00:00 2001 From: psyeon1120 Date: Wed, 10 Jul 2024 22:04:19 +0900 Subject: [PATCH 3/9] =?UTF-8?q?#327=20refactor:=20fridge=20assembler=20?= =?UTF-8?q?=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../fridge/dto/assembler/FridgeAssembler.java | 77 ------------------- .../fridge/entity/Fridge.java | 40 ++++++---- .../fridge/service/FridgeServiceImpl.java | 54 +++++++++++-- 3 files changed, 71 insertions(+), 100 deletions(-) delete mode 100644 src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeAssembler.java diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeAssembler.java b/src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeAssembler.java deleted file mode 100644 index e122a68c..00000000 --- a/src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeAssembler.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.example.icebutler_server.fridge.dto.assembler; - -import com.example.icebutler_server.fridge.dto.request.FridgeRegisterReq; -import com.example.icebutler_server.fridge.dto.response.UpdateMembersRes; -import com.example.icebutler_server.fridge.entity.Fridge; -import com.example.icebutler_server.fridge.entity.FridgeFood; -import com.example.icebutler_server.fridge.entity.FridgeUser; -import com.example.icebutler_server.global.entity.FridgeRole; -import com.example.icebutler_server.global.exception.BaseException; -import com.example.icebutler_server.user.entity.User; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -import java.util.ArrayList; -import java.util.List; - -import static com.example.icebutler_server.global.exception.ReturnCode.NO_PERMISSION; -import static com.example.icebutler_server.global.exception.ReturnCode.STILL_MEMBER_EXIST; - -@Component -@RequiredArgsConstructor -public class FridgeAssembler { - - public Fridge toEntity(FridgeRegisterReq createFridgeReq) { - return Fridge.builder() - .fridgeName(createFridgeReq.getFridgeName()) - .fridgeComment(createFridgeReq.getFridgeComment()) - .build(); - } - - public void toUpdateFridgeOwner(FridgeUser owner, FridgeUser newOwner) { - owner.changeFridgeMember(owner.getUser()); - newOwner.changeFridgeOwner(newOwner.getUser()); - } - - public UpdateMembersRes toUpdateFridgeMembers(List newMembers, List fridgeUsers) { - for (FridgeUser member : fridgeUsers) { - member.setIsEnable(false); - } - List checkNewMember = new ArrayList<>(); - List withDrawMember = new ArrayList<>(); - - for (User user : newMembers) { - boolean hasMember = false; - - for (FridgeUser members : fridgeUsers) { - if (user.equals(members.getUser())) { - members.setIsEnable(true); - hasMember = true; - } - if(members.getRole().equals(FridgeRole.OWNER)){ - members.setIsEnable(true); - } - } - if (!hasMember) { - checkNewMember.add(FridgeUser.builder() - .user(user) - .role(FridgeRole.MEMBER) - .fridge(fridgeUsers.get(0).getFridge()) - .build()); - } - } - for (FridgeUser f : fridgeUsers) { - if(!f.getIsEnable()) withDrawMember.add(f); - } - return UpdateMembersRes.toDto(withDrawMember, checkNewMember); - } - - public void removeFridge(FridgeUser owner, Fridge fridge, List fridgeUsers, List fridgeFoods) { - if (owner.getRole() != FridgeRole.OWNER) throw new BaseException(NO_PERMISSION); - if(fridgeUsers.size() > 1) throw new BaseException(STILL_MEMBER_EXIST); - - fridgeUsers.forEach(FridgeUser::remove); -// fridgeFoods.forEach(FridgeFood::remove); - fridge.remove(); - } -} diff --git a/src/main/java/com/example/icebutler_server/fridge/entity/Fridge.java b/src/main/java/com/example/icebutler_server/fridge/entity/Fridge.java index 5be818a4..bc344c73 100644 --- a/src/main/java/com/example/icebutler_server/fridge/entity/Fridge.java +++ b/src/main/java/com/example/icebutler_server/fridge/entity/Fridge.java @@ -1,5 +1,6 @@ package com.example.icebutler_server.fridge.entity; +import com.example.icebutler_server.fridge.dto.request.FridgeRegisterReq; import com.example.icebutler_server.global.entity.BaseEntity; import com.example.icebutler_server.global.entityListener.FridgeEntityListener; import org.hibernate.annotations.SQLDelete; @@ -27,20 +28,27 @@ public class Fridge extends BaseEntity { private String fridgeComment; - @Builder - public Fridge( - String fridgeName, - String fridgeComment) { - this.fridgeName = fridgeName; - this.fridgeComment = fridgeComment; - } - - public void updateBasicFridgeInfo(String fridgeName, String fridgeComment) { - this.fridgeName = fridgeName; - this.fridgeComment = fridgeComment; - } - - public void remove() { - this.setIsEnable(false); - } + @Builder + public Fridge( + String fridgeName, + String fridgeComment) { + this.fridgeName = fridgeName; + this.fridgeComment = fridgeComment; + } + + public void updateBasicFridgeInfo(String fridgeName, String fridgeComment) { + this.fridgeName = fridgeName; + this.fridgeComment = fridgeComment; + } + + public void remove() { + this.setIsEnable(false); + } + + public static Fridge toEntity(FridgeRegisterReq fridgeRegisterReq) { + return Fridge.builder() + .fridgeName(fridgeRegisterReq.getFridgeName()) + .fridgeComment(fridgeRegisterReq.getFridgeComment()) + .build(); + } } diff --git a/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java b/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java index 874d3199..0763e333 100644 --- a/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java @@ -7,7 +7,6 @@ import com.example.icebutler_server.food.entity.FoodCategory; import com.example.icebutler_server.food.entity.FoodDeleteStatus; import com.example.icebutler_server.food.repository.FoodRepository; -import com.example.icebutler_server.fridge.dto.assembler.FridgeAssembler; import com.example.icebutler_server.fridge.dto.assembler.FridgeFoodAssembler; import com.example.icebutler_server.fridge.dto.request.*; import com.example.icebutler_server.fridge.dto.response.*; @@ -48,8 +47,6 @@ public class FridgeServiceImpl implements FridgeService { private final FridgeFoodRepository fridgeFoodRepository; private final FoodRepository foodRepository; private final CartRepository cartRepository; - - private final FridgeAssembler fridgeAssembler; private final FridgeFoodAssembler fridgeFoodAssembler; private final AmazonSQSSender amazonSQSSender; @@ -73,7 +70,7 @@ public FridgeMainRes getFoods(Long fridgeIdx, Long userIdx, String category) { @Transactional public Long registerFridge(FridgeRegisterReq registerFridgeReq, Long ownerIdx) { if (!StringUtils.hasText(registerFridgeReq.getFridgeName())) throw new BaseException(INVALID_PARAM); - Fridge fridge = fridgeAssembler.toEntity(registerFridgeReq); + Fridge fridge = Fridge.toEntity(registerFridgeReq); fridgeRepository.save(fridge); List fridgeUsers = new ArrayList<>(); @@ -111,7 +108,7 @@ public void modifyFridge(Long fridgeIdx, FridgeModifyReq updateFridgeReq, Long u // 오너 업데이트 if (!owner.getUser().getId().equals(updateFridgeReq.getNewOwnerIdx())) { FridgeUser newOwner = this.fridgeUserRepository.findByFridgeAndUser_IdAndRoleAndIsEnableAndUser_IsEnable(fridge, updateFridgeReq.getNewOwnerIdx(), FridgeRole.MEMBER, true, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); - this.fridgeAssembler.toUpdateFridgeOwner(owner, newOwner); + toUpdateFridgeOwner(owner, newOwner); } // 냉장고 정보 (이름, 설명) 업데이트 @@ -122,7 +119,7 @@ public void modifyFridge(Long fridgeIdx, FridgeModifyReq updateFridgeReq, Long u List members = this.fridgeUserRepository.findByFridgeAndIsEnable(fridge, true); List newMembers = updateFridgeReq.getMembers().stream() .map(m -> this.userRepository.findByIdAndIsEnable(m.getUserIdx(), true).orElseThrow(() -> new BaseException(NOT_FOUND_USER))).collect(Collectors.toList()); - UpdateMembersRes updateMembers = this.fridgeAssembler.toUpdateFridgeMembers(newMembers, members); + UpdateMembersRes updateMembers = toUpdateFridgeMembers(newMembers, members); if (!updateMembers.getCheckNewMember().isEmpty()) { this.fridgeUserRepository.saveAll(updateMembers.getCheckNewMember()); @@ -147,6 +144,44 @@ public void modifyFridge(Long fridgeIdx, FridgeModifyReq updateFridgeReq, Long u } } + private UpdateMembersRes toUpdateFridgeMembers(List newMembers, List fridgeUsers) { + for (FridgeUser member : fridgeUsers) { + member.setIsEnable(false); + } + List checkNewMember = new ArrayList<>(); + List withDrawMember = new ArrayList<>(); + + for (User user : newMembers) { + boolean hasMember = false; + + for (FridgeUser members : fridgeUsers) { + if (user.equals(members.getUser())) { + members.setIsEnable(true); + hasMember = true; + } + if(members.getRole().equals(FridgeRole.OWNER)){ + members.setIsEnable(true); + } + } + if (!hasMember) { + checkNewMember.add(FridgeUser.builder() + .user(user) + .role(FridgeRole.MEMBER) + .fridge(fridgeUsers.get(0).getFridge()) + .build()); + } + } + for (FridgeUser f : fridgeUsers) { + if(!f.getIsEnable()) withDrawMember.add(f); + } + return UpdateMembersRes.toDto(withDrawMember, checkNewMember); + } + + private void toUpdateFridgeOwner(FridgeUser owner, FridgeUser newOwner) { + owner.changeFridgeMember(owner.getUser()); + newOwner.changeFridgeOwner(newOwner.getUser()); + } + // 냉장고 자체 삭제 @Transactional public Long removeFridge(Long fridgeIdx, Long userId) { @@ -156,7 +191,12 @@ public Long removeFridge(Long fridgeIdx, Long userId) { List fridgeUsers = fridgeUserRepository.findByFridgeAndIsEnable(fridge, true); List fridgeFoods = fridgeFoodRepository.findByFridgeAndIsEnableOrderByShelfLife(fridge, true); - fridgeAssembler.removeFridge(owner, fridge, fridgeUsers, fridgeFoods); + if (owner.getRole() != FridgeRole.OWNER) throw new BaseException(NO_PERMISSION); + if(fridgeUsers.size() > 1) throw new BaseException(STILL_MEMBER_EXIST); + + fridgeUsers.forEach(FridgeUser::remove); +// fridgeFoods.forEach(FridgeFood::remove); + fridge.remove(); fridgeFoodRepository.removeFridgeFoodByFridge(false, fridge); return fridge.getId(); From 1e414d440ae64de8550c2bbf22e964f1eeb5ad5f Mon Sep 17 00:00:00 2001 From: psyeon1120 Date: Wed, 10 Jul 2024 22:15:16 +0900 Subject: [PATCH 4/9] =?UTF-8?q?#327=20refactor:=20fridgeFood=20assembler?= =?UTF-8?q?=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dto/assembler/FridgeFoodAssembler.java | 67 -------- .../fridge/dto/response/FridgeFoodRes.java | 2 +- .../fridge/dto/response/FridgeFoodsRes.java | 2 +- .../fridge/dto/response/FridgeMainRes.java | 2 +- .../fridge/entity/FridgeFood.java | 143 ++++++++++-------- .../fridge/service/FridgeServiceImpl.java | 37 ++++- .../util}/FridgeUtils.java | 2 +- 7 files changed, 111 insertions(+), 144 deletions(-) delete mode 100644 src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeFoodAssembler.java rename src/main/java/com/example/icebutler_server/{fridge/dto/assembler => global/util}/FridgeUtils.java (87%) diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeFoodAssembler.java b/src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeFoodAssembler.java deleted file mode 100644 index ac805288..00000000 --- a/src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeFoodAssembler.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.example.icebutler_server.fridge.dto.assembler; - -import com.example.icebutler_server.food.entity.Food; -import com.example.icebutler_server.food.entity.FoodCategory; -import com.example.icebutler_server.fridge.dto.request.FridgeFoodReq; -import com.example.icebutler_server.fridge.dto.response.FridgeFoodStatistics; -import com.example.icebutler_server.fridge.dto.response.FridgeFoodsStatistics; -import com.example.icebutler_server.fridge.entity.Fridge; -import com.example.icebutler_server.fridge.entity.FridgeFood; -import com.example.icebutler_server.global.util.AwsS3ImageUrlUtil; -import com.example.icebutler_server.user.entity.User; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -@Component -@RequiredArgsConstructor -public class FridgeFoodAssembler { - public FridgeFood toEntity(User owner, Fridge fridge, Food food, FridgeFoodReq fridgeFoodReq) { - return FridgeFood.builder() - .fridge(fridge) - .food(food) - .foodDetailName(fridgeFoodReq.getFoodDetailName()) - .shelfLife(LocalDate.parse(fridgeFoodReq.getShelfLife())) - .owner(owner) - .memo(fridgeFoodReq.getMemo()) - .fridgeFoodImgKey(fridgeFoodReq.getImgKey()) - .build(); - } - - - public void toUpdateFridgeFoodInfo(FridgeFood modifyFood, Food food){ - modifyFood.updateFridgeFoodInfo(food); - } - - public void toUpdateBasicFridgeFoodInfo(FridgeFood modifyFood, FridgeFoodReq fridgeFoodReq){ - modifyFood.updateFridgeFoodInfo( - fridgeFoodReq.getFoodDetailName(), - fridgeFoodReq.getMemo(), - LocalDate.parse(fridgeFoodReq.getShelfLife()), - fridgeFoodReq.getImgKey() - ); - } - - public void toUpdateFridgeFoodOwner(FridgeFood modifyFridgeFood, User newOwner) { - modifyFridgeFood.updateFridgeFoodOwner(newOwner); - } - - public FridgeFoodsStatistics toFoodStatisticsByDeleteStatus(Map deleteStatusList) { - int sum = 0; - for(Long value : deleteStatusList.values()){ - sum += value.intValue(); - } - List foodStatisticsList = new ArrayList<>(); - - for(Map.Entry deleteStatus: deleteStatusList.entrySet()){ - foodStatisticsList.add(new FridgeFoodStatistics(deleteStatus.getKey().getName(),AwsS3ImageUrlUtil.toUrl(deleteStatus.getKey().getImage()) ,FridgeUtils.calPercentage(deleteStatus.getValue().intValue(), sum), deleteStatus.getValue().intValue())); - } - // sorting - foodStatisticsList.sort((fs1, fs2) -> (fs2.getCount() - fs1.getCount())); - return FridgeFoodsStatistics.toDto(foodStatisticsList); - } -} \ No newline at end of file diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodRes.java index 62a23cab..c53f3907 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodRes.java @@ -1,6 +1,6 @@ package com.example.icebutler_server.fridge.dto.response; -import com.example.icebutler_server.fridge.dto.assembler.FridgeUtils; +import com.example.icebutler_server.global.util.FridgeUtils; import com.example.icebutler_server.fridge.entity.FridgeFood; import com.example.icebutler_server.global.util.AwsS3ImageUrlUtil; import io.swagger.v3.oas.annotations.media.Schema; diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodsRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodsRes.java index 36d56e0b..9eccd9af 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodsRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodsRes.java @@ -1,6 +1,6 @@ package com.example.icebutler_server.fridge.dto.response; -import com.example.icebutler_server.fridge.dto.assembler.FridgeUtils; +import com.example.icebutler_server.global.util.FridgeUtils; import com.example.icebutler_server.fridge.entity.FridgeFood; import com.example.icebutler_server.global.util.AwsS3ImageUrlUtil; import io.swagger.v3.oas.annotations.media.Schema; diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeMainRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeMainRes.java index 5e68ca7b..f96ba185 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeMainRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeMainRes.java @@ -1,6 +1,6 @@ package com.example.icebutler_server.fridge.dto.response; -import com.example.icebutler_server.fridge.dto.assembler.FridgeUtils; +import com.example.icebutler_server.global.util.FridgeUtils; import com.example.icebutler_server.fridge.entity.FridgeFood; import com.example.icebutler_server.global.util.AwsS3ImageUrlUtil; import io.swagger.v3.oas.annotations.media.Schema; diff --git a/src/main/java/com/example/icebutler_server/fridge/entity/FridgeFood.java b/src/main/java/com/example/icebutler_server/fridge/entity/FridgeFood.java index 037e047d..9c4f3da2 100644 --- a/src/main/java/com/example/icebutler_server/fridge/entity/FridgeFood.java +++ b/src/main/java/com/example/icebutler_server/fridge/entity/FridgeFood.java @@ -2,6 +2,7 @@ import com.example.icebutler_server.food.entity.Food; import com.example.icebutler_server.food.entity.FoodDeleteStatus; +import com.example.icebutler_server.fridge.dto.request.FridgeFoodReq; import com.example.icebutler_server.global.entity.BaseEntity; import com.example.icebutler_server.user.entity.User; import lombok.AccessLevel; @@ -18,69 +19,81 @@ @Entity @SQLDelete(sql = "UPDATE fridge_food SET is_enable = false, updated_at = current_timestamp WHERE id = ?") public class FridgeFood extends BaseEntity { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(nullable = false) - private Long id; - - @Column(nullable = false) - private LocalDate shelfLife; - - private String fridgeFoodImgKey; - - private String memo; - - @Column(nullable = false) - private String foodDetailName; - - @Enumerated(EnumType.STRING) - private FoodDeleteStatus foodDeleteStatus; - - @ManyToOne(fetch = FetchType.LAZY, optional = false) - @JoinColumn(name = "food_id") - private Food food; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "user_id") - private User owner; - - @ManyToOne(fetch = FetchType.LAZY, optional = false) - @JoinColumn(name = "fridge_id") - private Fridge fridge; - - @Builder - public FridgeFood(User owner, Food food, Fridge fridge, String foodDetailName, LocalDate shelfLife, String memo, String fridgeFoodImgKey) { - this.shelfLife = shelfLife; - this.fridgeFoodImgKey = fridgeFoodImgKey; - this.memo = memo; - this.foodDetailName = foodDetailName; - this.owner = owner; - this.food = food; - this.fridge = fridge; - this.foodDeleteStatus = null; - } - - public void updateFridgeFoodInfo(Food food) { - this.food = food; - } - - public void updateFridgeFoodInfo(String foodDetailName, String memo, LocalDate shelfLife, String imgUrl) { - this.foodDetailName = foodDetailName; - this.memo = memo; - this.shelfLife = shelfLife; - this.fridgeFoodImgKey = imgUrl; - } - - public void updateFridgeFoodOwner(User newOwner) { - this.owner = newOwner; - } - - public void remove() { - this.setIsEnable(false); - } - - public void removeWithStatus(FoodDeleteStatus deleteStatus) { - this.setIsEnable(false); - this.foodDeleteStatus = deleteStatus; - } + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(nullable = false) + private Long id; + + @Column(nullable = false) + private LocalDate shelfLife; + + private String fridgeFoodImgKey; + + private String memo; + + @Column(nullable = false) + private String foodDetailName; + + @Enumerated(EnumType.STRING) + private FoodDeleteStatus foodDeleteStatus; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "food_id") + private Food food; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User owner; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "fridge_id") + private Fridge fridge; + + @Builder + public FridgeFood(User owner, Food food, Fridge fridge, String foodDetailName, LocalDate shelfLife, String memo, String fridgeFoodImgKey) { + this.shelfLife = shelfLife; + this.fridgeFoodImgKey = fridgeFoodImgKey; + this.memo = memo; + this.foodDetailName = foodDetailName; + this.owner = owner; + this.food = food; + this.fridge = fridge; + this.foodDeleteStatus = null; + } + + public void updateFridgeFoodInfo(Food food) { + this.food = food; + } + + public void updateFridgeFoodInfo(String foodDetailName, String memo, LocalDate shelfLife, String imgUrl) { + this.foodDetailName = foodDetailName; + this.memo = memo; + this.shelfLife = shelfLife; + this.fridgeFoodImgKey = imgUrl; + } + + public void updateFridgeFoodOwner(User newOwner) { + this.owner = newOwner; + } + + public void remove() { + this.setIsEnable(false); + } + + public void removeWithStatus(FoodDeleteStatus deleteStatus) { + this.setIsEnable(false); + this.foodDeleteStatus = deleteStatus; + } + + public static FridgeFood toEntity(User owner, Fridge fridge, Food food, FridgeFoodReq fridgeFoodReq) { + return FridgeFood.builder() + .fridge(fridge) + .food(food) + .foodDetailName(fridgeFoodReq.getFoodDetailName()) + .shelfLife(LocalDate.parse(fridgeFoodReq.getShelfLife())) + .owner(owner) + .memo(fridgeFoodReq.getMemo()) + .fridgeFoodImgKey(fridgeFoodReq.getImgKey()) + .build(); + } } diff --git a/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java b/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java index 0763e333..6695f0bf 100644 --- a/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java @@ -7,7 +7,7 @@ import com.example.icebutler_server.food.entity.FoodCategory; import com.example.icebutler_server.food.entity.FoodDeleteStatus; import com.example.icebutler_server.food.repository.FoodRepository; -import com.example.icebutler_server.fridge.dto.assembler.FridgeFoodAssembler; +import com.example.icebutler_server.global.util.FridgeUtils; import com.example.icebutler_server.fridge.dto.request.*; import com.example.icebutler_server.fridge.dto.response.*; import com.example.icebutler_server.fridge.entity.Fridge; @@ -20,6 +20,7 @@ import com.example.icebutler_server.global.exception.BaseException; import com.example.icebutler_server.global.sqs.AmazonSQSSender; import com.example.icebutler_server.global.sqs.FoodData; +import com.example.icebutler_server.global.util.AwsS3ImageUrlUtil; import com.example.icebutler_server.user.entity.User; import com.example.icebutler_server.user.repository.UserRepository; import lombok.RequiredArgsConstructor; @@ -28,6 +29,7 @@ import org.springframework.util.StringUtils; import java.io.IOException; +import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -47,7 +49,6 @@ public class FridgeServiceImpl implements FridgeService { private final FridgeFoodRepository fridgeFoodRepository; private final FoodRepository foodRepository; private final CartRepository cartRepository; - private final FridgeFoodAssembler fridgeFoodAssembler; private final AmazonSQSSender amazonSQSSender; private final NotificationServiceImpl alarmService; @@ -254,7 +255,7 @@ public void addFridgeFood(FridgeFoodsReq fridgeFoodsReq, Long fridgeIdx, Long us return save; }); - fridgeFoods.add(fridgeFoodAssembler.toEntity(owner, fridge, food, fridgeFoodReq)); + fridgeFoods.add(FridgeFood.toEntity(owner, fridge, food, fridgeFoodReq)); } fridgeFoodRepository.saveAll(fridgeFoods); } @@ -278,20 +279,25 @@ public void modifyFridgeFood(Long fridgeIdx, Long fridgeFoodIdx, FridgeFoodReq f amazonSQSSender.sendMessage(FoodData.toDto(save)); return save; }); - this.fridgeFoodAssembler.toUpdateFridgeFoodInfo(modifyFridgeFood, food); + modifyFridgeFood.updateFridgeFoodInfo(food); } - this.fridgeFoodAssembler.toUpdateBasicFridgeFoodInfo(modifyFridgeFood, fridgeFoodReq); + modifyFridgeFood.updateFridgeFoodInfo( + fridgeFoodReq.getFoodDetailName(), + fridgeFoodReq.getMemo(), + LocalDate.parse(fridgeFoodReq.getShelfLife()), + fridgeFoodReq.getImgKey() + ); if (fridgeFoodReq.getOwnerIdx() == null) - this.fridgeFoodAssembler.toUpdateFridgeFoodOwner(modifyFridgeFood, null); + modifyFridgeFood.updateFridgeFoodOwner(null); else { User newOwner = this.userRepository.findByIdAndIsEnable(fridgeFoodReq.getOwnerIdx(), true) .orElseThrow(() -> new BaseException(NOT_FOUND_USER)); this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, newOwner, true) .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); if (!newOwner.equals(modifyFridgeFood.getOwner())) - this.fridgeFoodAssembler.toUpdateFridgeFoodOwner(modifyFridgeFood, newOwner); + modifyFridgeFood.updateFridgeFoodOwner(newOwner); } } @@ -335,7 +341,22 @@ public FridgeFoodsStatistics getFridgeFoodStatistics(Long fridgeIdx, String dele deleteStatusList.put(category, foodSize); } - return this.fridgeFoodAssembler.toFoodStatisticsByDeleteStatus(deleteStatusList); + return toFoodStatisticsByDeleteStatus(deleteStatusList); + } + + private FridgeFoodsStatistics toFoodStatisticsByDeleteStatus(Map deleteStatusList) { + int sum = 0; + for(Long value : deleteStatusList.values()){ + sum += value.intValue(); + } + List foodStatisticsList = new ArrayList<>(); + + for(Map.Entry deleteStatus: deleteStatusList.entrySet()){ + foodStatisticsList.add(new FridgeFoodStatistics(deleteStatus.getKey().getName(), AwsS3ImageUrlUtil.toUrl(deleteStatus.getKey().getImage()) , FridgeUtils.calPercentage(deleteStatus.getValue().intValue(), sum), deleteStatus.getValue().intValue())); + } + // sorting + foodStatisticsList.sort((fs1, fs2) -> (fs2.getCount() - fs1.getCount())); + return FridgeFoodsStatistics.toDto(foodStatisticsList); } public SelectFridgesMainRes selectFridges(Long userIdx) { diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeUtils.java b/src/main/java/com/example/icebutler_server/global/util/FridgeUtils.java similarity index 87% rename from src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeUtils.java rename to src/main/java/com/example/icebutler_server/global/util/FridgeUtils.java index 59a21332..6e518690 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/assembler/FridgeUtils.java +++ b/src/main/java/com/example/icebutler_server/global/util/FridgeUtils.java @@ -1,4 +1,4 @@ -package com.example.icebutler_server.fridge.dto.assembler; +package com.example.icebutler_server.global.util; import java.time.LocalDate; import java.time.temporal.ChronoUnit; From 0795d390ebbcacf8b7187703e95075bbfd45f329 Mon Sep 17 00:00:00 2001 From: psyeon1120 Date: Wed, 10 Jul 2024 22:17:59 +0900 Subject: [PATCH 5/9] =?UTF-8?q?#327=20refactor:=20notification=20assembler?= =?UTF-8?q?=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dto/assembler/NotificationAssembler.java | 18 ------------------ .../alarm/entity/PushNotification.java | 8 ++++++++ .../alarm/service/NotificationServiceImpl.java | 9 ++++----- 3 files changed, 12 insertions(+), 23 deletions(-) delete mode 100644 src/main/java/com/example/icebutler_server/alarm/dto/assembler/NotificationAssembler.java diff --git a/src/main/java/com/example/icebutler_server/alarm/dto/assembler/NotificationAssembler.java b/src/main/java/com/example/icebutler_server/alarm/dto/assembler/NotificationAssembler.java deleted file mode 100644 index 8195f574..00000000 --- a/src/main/java/com/example/icebutler_server/alarm/dto/assembler/NotificationAssembler.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.example.icebutler_server.alarm.dto.assembler; - -import com.example.icebutler_server.alarm.entity.PushNotification; -import com.example.icebutler_server.user.entity.User; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -@Component -@RequiredArgsConstructor -public class NotificationAssembler { - public PushNotification toEntity(String pushNotificationType, String messageBody, User user) { - return PushNotification.builder() - .pushNotificationType(pushNotificationType) - .notificationInfo(messageBody) - .user(user) - .build(); - } -} diff --git a/src/main/java/com/example/icebutler_server/alarm/entity/PushNotification.java b/src/main/java/com/example/icebutler_server/alarm/entity/PushNotification.java index 85036f3f..420929e0 100644 --- a/src/main/java/com/example/icebutler_server/alarm/entity/PushNotification.java +++ b/src/main/java/com/example/icebutler_server/alarm/entity/PushNotification.java @@ -34,4 +34,12 @@ public PushNotification(String pushNotificationType, String notificationInfo, Us this.notificationInfo = notificationInfo; this.user = user; } + + public static PushNotification toEntity(String pushNotificationType, String messageBody, User user) { + return PushNotification.builder() + .pushNotificationType(pushNotificationType) + .notificationInfo(messageBody) + .user(user) + .build(); + } } diff --git a/src/main/java/com/example/icebutler_server/alarm/service/NotificationServiceImpl.java b/src/main/java/com/example/icebutler_server/alarm/service/NotificationServiceImpl.java index 3364d985..555550b5 100644 --- a/src/main/java/com/example/icebutler_server/alarm/service/NotificationServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/alarm/service/NotificationServiceImpl.java @@ -1,7 +1,7 @@ package com.example.icebutler_server.alarm.service; import com.example.icebutler_server.alarm.dto.FcmMessage; -import com.example.icebutler_server.alarm.dto.assembler.NotificationAssembler; +import com.example.icebutler_server.alarm.entity.PushNotification; import com.example.icebutler_server.alarm.repository.PushNotificationRepository; import com.example.icebutler_server.global.util.Constant; import com.example.icebutler_server.user.entity.User; @@ -26,7 +26,6 @@ public class NotificationServiceImpl implements NotificationService { private final String API_URL = "https://fcm.googleapis.com/v1/projects/icebutler-46914/messages:send"; private final ObjectMapper objectMapper; private final PushNotificationRepository notificationRepository; - private final NotificationAssembler notificationAssembler; // TODO 냉장고 유저 탈퇴 로직 리팩 후 호출 @Transactional @@ -36,7 +35,7 @@ public void sendWithdrawalAlarm(User user, String fridgeName) throws JsonParseEx if(user.getFcmToken()!=null){ FcmMessage message = FcmMessage.makeMessage(user.getFcmToken(), Constant.PushNotification.FRIDGE, messageBody); Response response = sendMessage(objectMapper.writeValueAsString(message)); - this.notificationRepository.save(this.notificationAssembler.toEntity(Constant.PushNotification.FRIDGE, messageBody, user)); + this.notificationRepository.save(PushNotification.toEntity(Constant.PushNotification.FRIDGE, messageBody, user)); } } // TODO 냉장고 유저 초대 리펙 후 호출 @@ -47,7 +46,7 @@ public void sendJoinFridgeAlarm(User user, String fridgeName) throws IOException if(user.getFcmToken()!=null) { FcmMessage message = FcmMessage.makeMessage(user.getFcmToken(), Constant.PushNotification.FRIDGE, messageBody); Response response = sendMessage(objectMapper.writeValueAsString(message)); - this.notificationRepository.save(this.notificationAssembler.toEntity(Constant.PushNotification.FRIDGE, messageBody, user)); + this.notificationRepository.save(PushNotification.toEntity(Constant.PushNotification.FRIDGE, messageBody, user)); } } @@ -58,7 +57,7 @@ public void sendShelfLifeAlarm(User user, String fridgeName, String foodName) th if(user.getFcmToken()!=null) { FcmMessage message = FcmMessage.makeMessage(user.getFcmToken(), fridgeName, messageBody); Response response = sendMessage(objectMapper.writeValueAsString(message)); - this.notificationRepository.save(this.notificationAssembler.toEntity(fridgeName, messageBody, user)); + this.notificationRepository.save(PushNotification.toEntity(fridgeName, messageBody, user)); } } From f8c5dc6a2e13784161534af14147101089147e32 Mon Sep 17 00:00:00 2001 From: psyeon1120 Date: Wed, 10 Jul 2024 22:50:25 +0900 Subject: [PATCH 6/9] =?UTF-8?q?#327=20refactor:=20idx=20->=20id=EB=A1=9C?= =?UTF-8?q?=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../admin/controller/AdminController.java | 53 ++++----- .../admin/dto/request/RemoveFoodRequest.java | 2 +- .../admin/dto/request/WithDrawRequest.java | 2 +- .../dto/response/SearchFoodsResponse.java | 9 +- .../admin/dto/response/UserResponse.java | 8 +- .../exception/FoodNotFoundException.java | 2 +- .../admin/repository/AdminRepository.java | 2 +- .../admin/service/AdminService.java | 22 ++-- .../admin/service/AdminServiceImpl.java | 48 ++++----- .../cart/controller/CartController.java | 18 ++-- .../request/RemoveFoodFromCartRequest.java | 4 +- .../CartFoodQuerydslRepository.java | 2 +- .../CartFoodQuerydslRepositoryImpl.java | 7 +- .../cart/repository/CartRepository.java | 2 +- .../cart/service/CartService.java | 6 +- .../cart/service/CartServiceImpl.java | 24 ++--- .../food/dto/request/FoodReq.java | 2 +- .../food/dto/response/FoodRes.java | 4 +- .../food/dto/response/FoodResponse.java | 4 +- .../food/repository/FoodRepository.java | 2 +- .../fridge/controller/FridgeController.java | 86 ++++++++------- .../fridge/dto/request/FridgeFoodReq.java | 4 +- .../dto/request/FridgeModifyMembersReq.java | 7 +- .../fridge/dto/request/FridgeModifyReq.java | 5 +- .../dto/request/FridgeRegisterMembersReq.java | 4 +- .../fridge/dto/response/FridgeFoodRes.java | 12 +-- .../fridge/dto/response/FridgeFoodsRes.java | 6 +- .../fridge/dto/response/FridgeRes.java | 6 +- .../fridge/dto/response/FridgeUserRes.java | 6 +- .../fridge/dto/response/FridgeUsersRes.java | 8 +- .../dto/response/GetFridgesMainRes.java | 4 +- .../dto/response/RecipeFridgeFoodListRes.java | 2 +- .../fridge/dto/response/SearchFoodRes.java | 6 +- .../dto/response/SearchFridgeFoodRes.java | 10 +- .../fridge/dto/response/SelectFridgeRes.java | 8 +- .../FridgeFood/FridgeFoodRepository.java | 2 +- .../FridgeFood/FridgeFoodRepositoryImpl.java | 12 +-- .../fridge/repository/FridgeRepository.java | 2 +- .../repository/FridgeUserRepository.java | 2 +- .../fridge/service/FridgeService.java | 26 ++--- .../fridge/service/FridgeServiceImpl.java | 102 +++++++++--------- .../global/feign/dto/AdminReq.java | 8 +- .../global/feign/dto/FoodReq.java | 8 +- .../global/feign/dto/UserReq.java | 6 +- .../global/feign/event/DeleteUserEvent.java | 6 +- .../global/feign/event/FoodEvent.java | 6 +- .../global/feign/event/UpdateFoodEvent.java | 6 +- .../global/feign/event/UpdateUserEvent.java | 6 +- .../global/feign/event/UserEvent.java | 6 +- .../feign/feignClient/RecipeServerClient.java | 4 +- .../global/resolver/AdminLoginStatus.java | 6 +- .../global/resolver/AdminResolver.java | 6 +- .../global/resolver/LoginResolver.java | 6 +- .../global/resolver/LoginStatus.java | 6 +- .../global/util/TokenUtils.java | 36 +++---- .../util/redis/RedisTemplateService.java | 6 +- .../util/redis/RedisTemplateServiceImpl.java | 12 +-- .../user/controller/UserAuthController.java | 12 +-- .../user/dto/request/UserAuthTokenReq.java | 6 +- .../user/dto/response/MyProfileRes.java | 10 +- .../user/dto/response/NickNameRes.java | 6 +- .../user/repository/UserRepository.java | 2 +- .../user/service/UserService.java | 10 +- .../user/service/UserServiceImpl.java | 24 ++--- 64 files changed, 360 insertions(+), 387 deletions(-) diff --git a/src/main/java/com/example/icebutler_server/admin/controller/AdminController.java b/src/main/java/com/example/icebutler_server/admin/controller/AdminController.java index b81c74a0..45409cc6 100644 --- a/src/main/java/com/example/icebutler_server/admin/controller/AdminController.java +++ b/src/main/java/com/example/icebutler_server/admin/controller/AdminController.java @@ -36,22 +36,19 @@ public class AdminController { private final FoodRepository foodRepository; @PostMapping("/join") - public ResponseCustom join(@RequestBody JoinRequest request) - { + public ResponseCustom join(@RequestBody JoinRequest request) { return ResponseCustom.success(adminService.join(request)); } @PostMapping("/login") - public ResponseCustom login(@RequestBody LoginRequest request) - { + public ResponseCustom login(@RequestBody LoginRequest request) { return ResponseCustom.success(adminService.login(request)); } @Admin @PostMapping("/logout") - public ResponseCustom logout(@IsAdminLogin AdminLoginStatus loginStatus) - { - adminService.logout(loginStatus.getAdminIdx()); + public ResponseCustom logout(@IsAdminLogin AdminLoginStatus loginStatus) { + adminService.logout(loginStatus.getAdminId()); return ResponseCustom.success(); } @@ -62,20 +59,18 @@ public ResponseCustom> search( Pageable pageable, @RequestParam(defaultValue = "") String nickname, @RequestParam(defaultValue = "true") boolean active - ) - { - return ResponseCustom.success(adminService.search(pageable, nickname, active,loginStatus.getAdminIdx())); + ) { + return ResponseCustom.success(adminService.search(pageable, nickname, active, loginStatus.getAdminId())); } @Admin - @DeleteMapping("/users/{userIdx}") + @DeleteMapping("/users/{userId}") public ResponseCustom withdraw( @IsAdminLogin AdminLoginStatus loginStatus, - @PathVariable Long userIdx, + @PathVariable Long userId, HttpServletRequest request - ) - { - adminService.withdraw(userIdx, loginStatus.getAdminIdx(), request.getHeader("Authorization")); + ) { + adminService.withdraw(userId, loginStatus.getAdminId(), request.getHeader("Authorization")); return ResponseCustom.success(); } @@ -83,31 +78,27 @@ public ResponseCustom withdraw( @Admin @GetMapping("/foods") public ResponseCustom> searchFoods(@RequestParam String cond, Pageable pageable - ,@IsAdminLogin AdminLoginStatus loginStatus - ) - { - return ResponseCustom.success(adminService.searchFoods(cond, pageable,loginStatus.getAdminIdx())); + , @IsAdminLogin AdminLoginStatus loginStatus + ) { + return ResponseCustom.success(adminService.searchFoods(cond, pageable, loginStatus.getAdminId())); } // 식품수정 @Admin - @PatchMapping("/foods/{foodIdx}") - public ResponseCustom modifyFood(@PathVariable(name = "foodIdx") Long foodIdx, - @RequestBody ModifyFoodRequest request - ,@IsAdminLogin AdminLoginStatus loginStatus - ) - { - adminService.modifyFood(foodIdx, request,loginStatus.getAdminIdx()); + @PatchMapping("/foods/{foodId}") + public ResponseCustom modifyFood(@PathVariable Long foodId, + @RequestBody ModifyFoodRequest request, + @IsAdminLogin AdminLoginStatus loginStatus) { + adminService.modifyFood(foodId, request, loginStatus.getAdminId()); return ResponseCustom.success(); } // 식품삭제 @Admin - @DeleteMapping("/foods/{foodIdx}") - public ResponseCustom removeFoods(@PathVariable(name = "foodIdx") Long foodIdx - ,@IsAdminLogin AdminLoginStatus loginStatus - ) { - adminService.removeFoods(foodIdx,loginStatus.getAdminIdx()); + @DeleteMapping("/foods/{foodId}") + public ResponseCustom removeFoods(@PathVariable Long foodId, + @IsAdminLogin AdminLoginStatus loginStatus) { + adminService.removeFoods(foodId, loginStatus.getAdminId()); return ResponseCustom.success(); } diff --git a/src/main/java/com/example/icebutler_server/admin/dto/request/RemoveFoodRequest.java b/src/main/java/com/example/icebutler_server/admin/dto/request/RemoveFoodRequest.java index a5ed9253..26419cdb 100644 --- a/src/main/java/com/example/icebutler_server/admin/dto/request/RemoveFoodRequest.java +++ b/src/main/java/com/example/icebutler_server/admin/dto/request/RemoveFoodRequest.java @@ -6,5 +6,5 @@ @Data @Getter public class RemoveFoodRequest { - private Long foodIdx; + private Long foodId; } diff --git a/src/main/java/com/example/icebutler_server/admin/dto/request/WithDrawRequest.java b/src/main/java/com/example/icebutler_server/admin/dto/request/WithDrawRequest.java index 2dffb05d..d9e8e6a7 100644 --- a/src/main/java/com/example/icebutler_server/admin/dto/request/WithDrawRequest.java +++ b/src/main/java/com/example/icebutler_server/admin/dto/request/WithDrawRequest.java @@ -6,5 +6,5 @@ @Data @NoArgsConstructor public class WithDrawRequest { - private Long userIdx; + private Long userId; } diff --git a/src/main/java/com/example/icebutler_server/admin/dto/response/SearchFoodsResponse.java b/src/main/java/com/example/icebutler_server/admin/dto/response/SearchFoodsResponse.java index 743d9700..e740896f 100644 --- a/src/main/java/com/example/icebutler_server/admin/dto/response/SearchFoodsResponse.java +++ b/src/main/java/com/example/icebutler_server/admin/dto/response/SearchFoodsResponse.java @@ -1,7 +1,6 @@ package com.example.icebutler_server.admin.dto.response; import com.example.icebutler_server.food.entity.Food; -import com.example.icebutler_server.food.entity.FoodCategory; import com.example.icebutler_server.global.util.AwsS3ImageUrlUtil; import lombok.Builder; import lombok.Data; @@ -10,14 +9,14 @@ @Data @NoArgsConstructor public class SearchFoodsResponse { - private Long foodIdx; + private Long foodId; private String foodCategory; private String foodName; private String foodImgUrl; public static SearchFoodsResponse toDto(Food food) { SearchFoodsResponse searchFoodsResponse = new SearchFoodsResponse(); - searchFoodsResponse.foodIdx = food.getId(); + searchFoodsResponse.foodId = food.getId(); searchFoodsResponse.foodCategory = food.getFoodCategory().getName(); searchFoodsResponse.foodName = food.getFoodName(); searchFoodsResponse.foodImgUrl = AwsS3ImageUrlUtil.toUrl(food.getFoodImgKey()); @@ -25,8 +24,8 @@ public static SearchFoodsResponse toDto(Food food) { } @Builder - public SearchFoodsResponse(Long foodIdx, String foodCategory, String foodName, String foodImgUrl) { - this.foodIdx = foodIdx; + public SearchFoodsResponse(Long foodId, String foodCategory, String foodName, String foodImgUrl) { + this.foodId = foodId; this.foodCategory = foodCategory; this.foodName = foodName; this.foodImgUrl = foodImgUrl; diff --git a/src/main/java/com/example/icebutler_server/admin/dto/response/UserResponse.java b/src/main/java/com/example/icebutler_server/admin/dto/response/UserResponse.java index b9bf30e7..393e3e73 100644 --- a/src/main/java/com/example/icebutler_server/admin/dto/response/UserResponse.java +++ b/src/main/java/com/example/icebutler_server/admin/dto/response/UserResponse.java @@ -7,17 +7,15 @@ @NoArgsConstructor @Data public class UserResponse { - private Long userIdx; + private Long userId; private String nickname; private String email; private String provider; private boolean isDenied; - - public static UserResponse toDto(User user) - { + public static UserResponse toDto(User user) { UserResponse userResponse = new UserResponse(); - userResponse.userIdx = user.getId(); + userResponse.userId = user.getId(); userResponse.nickname = user.getNickname(); userResponse.email = user.getEmail(); userResponse.provider = user.getProvider().getName(); diff --git a/src/main/java/com/example/icebutler_server/admin/exception/FoodNotFoundException.java b/src/main/java/com/example/icebutler_server/admin/exception/FoodNotFoundException.java index 44c8ef67..384fec33 100644 --- a/src/main/java/com/example/icebutler_server/admin/exception/FoodNotFoundException.java +++ b/src/main/java/com/example/icebutler_server/admin/exception/FoodNotFoundException.java @@ -1,5 +1,5 @@ package com.example.icebutler_server.admin.exception; public class FoodNotFoundException extends RuntimeException{ - public FoodNotFoundException() {super("해당 idx를 가진 음식을 찾을 수 없습니다.");} + public FoodNotFoundException() {super("해당 id를 가진 음식을 찾을 수 없습니다.");} } diff --git a/src/main/java/com/example/icebutler_server/admin/repository/AdminRepository.java b/src/main/java/com/example/icebutler_server/admin/repository/AdminRepository.java index 1c39a920..63d6fe78 100644 --- a/src/main/java/com/example/icebutler_server/admin/repository/AdminRepository.java +++ b/src/main/java/com/example/icebutler_server/admin/repository/AdminRepository.java @@ -7,5 +7,5 @@ public interface AdminRepository extends JpaRepository , AdminRepositoryQuerydsl{ Optional findByEmail(String email); - Optional findByIdAndIsEnable(Long adminIdx, boolean isEnable); + Optional findByIdAndIsEnable(Long adminId, boolean isEnable); } diff --git a/src/main/java/com/example/icebutler_server/admin/service/AdminService.java b/src/main/java/com/example/icebutler_server/admin/service/AdminService.java index 5f40c3c0..e80df75d 100644 --- a/src/main/java/com/example/icebutler_server/admin/service/AdminService.java +++ b/src/main/java/com/example/icebutler_server/admin/service/AdminService.java @@ -1,27 +1,25 @@ package com.example.icebutler_server.admin.service; -import com.example.icebutler_server.admin.dto.condition.SearchCond; -import com.example.icebutler_server.admin.dto.request.*; +import com.example.icebutler_server.admin.dto.request.JoinRequest; +import com.example.icebutler_server.admin.dto.request.LoginRequest; +import com.example.icebutler_server.admin.dto.request.ModifyFoodRequest; import com.example.icebutler_server.admin.dto.response.AdminResponse; -import com.example.icebutler_server.admin.dto.response.LogoutResponse; -import com.example.icebutler_server.admin.dto.response.SearchFoodsResponse; -import com.example.icebutler_server.global.resolver.LoginStatus; import com.example.icebutler_server.admin.dto.response.PostAdminRes; +import com.example.icebutler_server.admin.dto.response.SearchFoodsResponse; import com.example.icebutler_server.admin.dto.response.UserResponse; -import com.example.icebutler_server.user.dto.response.MyProfileRes; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; public interface AdminService { AdminResponse join(JoinRequest request); PostAdminRes login(LoginRequest request); - void logout(Long adminIdx); - Page search(Pageable pageable, String nickname, boolean active,Long adminIdx); - void withdraw(Long userIdx,Long adminIdx, String authorization); + void logout(Long adminId); + Page search(Pageable pageable, String nickname, boolean active, Long adminId); + void withdraw(Long userId, Long adminId, String authorization); - Page searchFoods(String cond, Pageable pageable,Long adminIdx); + Page searchFoods(String cond, Pageable pageable, Long adminId); - void modifyFood(Long foodIdx, ModifyFoodRequest request,Long adminIdx); + void modifyFood(Long foodId, ModifyFoodRequest request, Long adminId); - void removeFoods(Long foodIdx,Long adminIdx); + void removeFoods(Long foodId, Long adminId); } diff --git a/src/main/java/com/example/icebutler_server/admin/service/AdminServiceImpl.java b/src/main/java/com/example/icebutler_server/admin/service/AdminServiceImpl.java index 8b195d34..d0f91cb6 100644 --- a/src/main/java/com/example/icebutler_server/admin/service/AdminServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/admin/service/AdminServiceImpl.java @@ -54,9 +54,8 @@ public class AdminServiceImpl implements AdminService { @Transactional @Override - public AdminResponse join(JoinRequest request) - { - if(adminRepository.findByEmail(request.getEmail()).isPresent()) throw new AlreadyExistEmailException(); + public AdminResponse join(JoinRequest request) { + if (adminRepository.findByEmail(request.getEmail()).isPresent()) throw new AlreadyExistEmailException(); Admin admin = adminRepository.save(request.toAdmin(pwEncoder.encode(request.getPassword()))); recipeServerClient.addAdmin(AdminReq.toDto(admin)); return AdminResponse.toDto(admin); @@ -64,19 +63,17 @@ public AdminResponse join(JoinRequest request) @Transactional @Override - public PostAdminRes login(LoginRequest request) - { + public PostAdminRes login(LoginRequest request) { Admin admin = adminRepository.findByEmail(request.getEmail()).orElseThrow(AdminNotFoundException::new); - if(!pwEncoder.matches(request.getPassword(), admin.getPassword())) throw new PasswordNotMatchException(); + if (!pwEncoder.matches(request.getPassword(), admin.getPassword())) throw new PasswordNotMatchException(); admin.login(); return PostAdminRes.toDto(tokenUtils.createToken(admin.getId(), admin.getEmail())); } @Transactional @Override - public void logout(Long adminIdx) - { - Admin admin = adminRepository.findByIdAndIsEnable(adminIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + public void logout(Long adminId) { + Admin admin = adminRepository.findByIdAndIsEnable(adminId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); admin.logout(); redisTemplateService.deleteUserRefreshToken(admin.getId().toString()); } @@ -85,29 +82,28 @@ public void logout(Long adminIdx) public Page search( Pageable pageable, String nickname, - boolean active,Long adminIdx) - { - adminRepository.findByIdAndIsEnable(adminIdx,true).orElseThrow(AdminNotFoundException::new); + boolean active, Long adminId) { + adminRepository.findByIdAndIsEnable(adminId, true).orElseThrow(AdminNotFoundException::new); return adminRepository.findAllByNicknameAndActive(pageable, nickname, active); } + @Transactional @Override - public void withdraw(Long userIdx, Long adminIdx, String authorization) - { - adminRepository.findByIdAndIsEnable(adminIdx,true).orElseThrow(AdminNotFoundException::new); - User user = userRepository.findById(userIdx).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + public void withdraw(Long userId, Long adminId, String authorization) { + adminRepository.findByIdAndIsEnable(adminId, true).orElseThrow(AdminNotFoundException::new); + User user = userRepository.findById(userId).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); HashMap requestHeaders = new HashMap<>(); requestHeaders.put("Authorization", authorization); - recipeServerClient.withdrawUser(userIdx, requestHeaders); + recipeServerClient.withdrawUser(userId, requestHeaders); userRepository.delete(user); } @Override - public Page searchFoods(String cond, Pageable pageable,Long adminIdx) { - adminRepository.findByIdAndIsEnable(adminIdx,true).orElseThrow(AdminNotFoundException::new); + public Page searchFoods(String cond, Pageable pageable, Long adminId) { + adminRepository.findByIdAndIsEnable(adminId, true).orElseThrow(AdminNotFoundException::new); Page searchFoods; - if (StringUtils.hasText(cond)){ + if (StringUtils.hasText(cond)) { Page searchFood = foodRepository.findByFoodNameContainsAndIsEnable(cond, true, pageable); searchFoods = searchFood.map(SearchFoodsResponse::toDto); return searchFoods; @@ -120,9 +116,9 @@ public Page searchFoods(String cond, Pageable pageable,Long @Override @Transactional - public void modifyFood(Long foodIdx, ModifyFoodRequest request,Long adminIdx) { - adminRepository.findByIdAndIsEnable(adminIdx,true).orElseThrow(AdminNotFoundException::new); - Food food = foodRepository.findByIdAndIsEnable(foodIdx, true).orElseThrow(FoodNotFoundException::new); + public void modifyFood(Long foodId, ModifyFoodRequest request, Long adminId) { + adminRepository.findByIdAndIsEnable(adminId, true).orElseThrow(AdminNotFoundException::new); + Food food = foodRepository.findByIdAndIsEnable(foodId, true).orElseThrow(FoodNotFoundException::new); Food checkFood = foodRepository.findByFoodNameAndIsEnable(request.getFoodName(), true); if (!food.getFoodName().equals(request.getFoodName()) && checkFood != null) { adminAssembler.validateFoodName(checkFood, request.getFoodName()); @@ -133,9 +129,9 @@ public void modifyFood(Long foodIdx, ModifyFoodRequest request,Long adminIdx) { @Override @Transactional - public void removeFoods(Long foodIdx,Long adminIdx) { - adminRepository.findByIdAndIsEnable(adminIdx,true).orElseThrow(AdminNotFoundException::new); - Food food = foodRepository.findByIdAndIsEnable(foodIdx, true).orElseThrow(FoodNotFoundException::new); + public void removeFoods(Long foodId, Long adminId) { + adminRepository.findByIdAndIsEnable(adminId, true).orElseThrow(AdminNotFoundException::new); + Food food = foodRepository.findByIdAndIsEnable(foodId, true).orElseThrow(FoodNotFoundException::new); foodRepository.delete(food); recipeServerEventPublisher.deleteFood(food); } diff --git a/src/main/java/com/example/icebutler_server/cart/controller/CartController.java b/src/main/java/com/example/icebutler_server/cart/controller/CartController.java index baa90578..34de3a70 100644 --- a/src/main/java/com/example/icebutler_server/cart/controller/CartController.java +++ b/src/main/java/com/example/icebutler_server/cart/controller/CartController.java @@ -42,10 +42,10 @@ public class CartController { content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth - @GetMapping("/{fridgeIdx}/foods") - public ResponseCustom> getCartFoods(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, + @GetMapping("/{fridgeId}/foods") + public ResponseCustom> getCartFoods(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - return ResponseCustom.success(cartService.getCartFoods(fridgeIdx, loginStatus.getUserIdx())); + return ResponseCustom.success(cartService.getCartFoods(fridgeId, loginStatus.getUserId())); } @Operation(summary = "장바구니 식품 추가", description = "장바구니에 식품을 추가한다.") @@ -60,11 +60,11 @@ public ResponseCustom> getCartFoods(@Parameter(name = "냉장 content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth - @PostMapping("/{fridgeIdx}/foods") - public ResponseCustom addCartFoods(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, + @PostMapping("/{fridgeId}/foods") + public ResponseCustom addCartFoods(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, @RequestBody AddFoodToCartRequest request, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - cartService.addCartFoods(fridgeIdx, request, loginStatus.getUserIdx()); + cartService.addCartFoods(fridgeId, request, loginStatus.getUserId()); return ResponseCustom.success(); } @@ -80,11 +80,11 @@ public ResponseCustom addCartFoods(@Parameter(name = "냉장고 ID") @PathVar content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth - @DeleteMapping("/{fridgeIdx}/foods") - public ResponseCustom deleteCartFoods(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, + @DeleteMapping("/{fridgeId}/foods") + public ResponseCustom deleteCartFoods(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, @RequestBody RemoveFoodFromCartRequest request, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - cartService.deleteCartFoods(fridgeIdx, request, loginStatus.getUserIdx()); + cartService.deleteCartFoods(fridgeId, request, loginStatus.getUserId()); return ResponseCustom.success(); } } diff --git a/src/main/java/com/example/icebutler_server/cart/dto/request/RemoveFoodFromCartRequest.java b/src/main/java/com/example/icebutler_server/cart/dto/request/RemoveFoodFromCartRequest.java index 220e24a6..a43d0e41 100644 --- a/src/main/java/com/example/icebutler_server/cart/dto/request/RemoveFoodFromCartRequest.java +++ b/src/main/java/com/example/icebutler_server/cart/dto/request/RemoveFoodFromCartRequest.java @@ -10,6 +10,6 @@ @Data @Schema(name = "RemoveFoodFromCartRequest", description = "장바구니 식품 삭제 요청 정보") public class RemoveFoodFromCartRequest { - @Schema(name = "foodIdxes", description = "식품 ID 목록") - private List foodIdxes; + @Schema(name = "foodIds", description = "식품 ID 목록") + private List foodIds; } diff --git a/src/main/java/com/example/icebutler_server/cart/repository/CartFoodQuerydslRepository.java b/src/main/java/com/example/icebutler_server/cart/repository/CartFoodQuerydslRepository.java index 39cd9f80..85ef9b16 100644 --- a/src/main/java/com/example/icebutler_server/cart/repository/CartFoodQuerydslRepository.java +++ b/src/main/java/com/example/icebutler_server/cart/repository/CartFoodQuerydslRepository.java @@ -5,6 +5,6 @@ import java.util.List; public interface CartFoodQuerydslRepository { - List findByCartIdAndFoodIdIn(Long cartIdx, List foodIdxes); + List findByCartIdAndFoodIdIn(Long cartId, List foodIds); } diff --git a/src/main/java/com/example/icebutler_server/cart/repository/CartFoodQuerydslRepositoryImpl.java b/src/main/java/com/example/icebutler_server/cart/repository/CartFoodQuerydslRepositoryImpl.java index 2ce679f6..23d1e783 100644 --- a/src/main/java/com/example/icebutler_server/cart/repository/CartFoodQuerydslRepositoryImpl.java +++ b/src/main/java/com/example/icebutler_server/cart/repository/CartFoodQuerydslRepositoryImpl.java @@ -9,7 +9,6 @@ import static com.example.icebutler_server.cart.entity.QCartFood.cartFood; - @RequiredArgsConstructor @Repository public class CartFoodQuerydslRepositoryImpl implements CartFoodQuerydslRepository{ @@ -18,12 +17,12 @@ public class CartFoodQuerydslRepositoryImpl implements CartFoodQuerydslRepositor @Override - public List findByCartIdAndFoodIdIn(Long cartIdx, List foodIdxes) { + public List findByCartIdAndFoodIdIn(Long cartId, List foodIds) { return queryFactory .selectFrom(cartFood) .where( - cartFood.cart.id.eq(cartIdx), - cartFood.food.id.in(foodIdxes) + cartFood.cart.id.eq(cartId), + cartFood.food.id.in(foodIds) ) .fetch(); } diff --git a/src/main/java/com/example/icebutler_server/cart/repository/CartRepository.java b/src/main/java/com/example/icebutler_server/cart/repository/CartRepository.java index 25ca90d3..f87427a5 100644 --- a/src/main/java/com/example/icebutler_server/cart/repository/CartRepository.java +++ b/src/main/java/com/example/icebutler_server/cart/repository/CartRepository.java @@ -7,6 +7,6 @@ import java.util.Optional; public interface CartRepository extends JpaRepository { - Optional findByFridge_IdAndIsEnable(Long fridgeIdx, boolean status); + Optional findByFridge_IdAndIsEnable(Long fridgeId, boolean status); void deleteByFridge(Fridge fridge); } diff --git a/src/main/java/com/example/icebutler_server/cart/service/CartService.java b/src/main/java/com/example/icebutler_server/cart/service/CartService.java index 80186de5..4bb2bef3 100644 --- a/src/main/java/com/example/icebutler_server/cart/service/CartService.java +++ b/src/main/java/com/example/icebutler_server/cart/service/CartService.java @@ -8,7 +8,7 @@ public interface CartService { - List getCartFoods(Long fridgeIdx, Long userIdx); - void addCartFoods(Long cartIdx, AddFoodToCartRequest request, Long userIdx); - void deleteCartFoods(Long cartIdx, RemoveFoodFromCartRequest request, Long userIdx); + List getCartFoods(Long fridgeId, Long userId); + void addCartFoods(Long cartId, AddFoodToCartRequest request, Long userId); + void deleteCartFoods(Long cartId, RemoveFoodFromCartRequest request, Long userId); } diff --git a/src/main/java/com/example/icebutler_server/cart/service/CartServiceImpl.java b/src/main/java/com/example/icebutler_server/cart/service/CartServiceImpl.java index d102099e..ea641622 100644 --- a/src/main/java/com/example/icebutler_server/cart/service/CartServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/cart/service/CartServiceImpl.java @@ -44,8 +44,8 @@ public class CartServiceImpl implements CartService { // 장바구니 식품 조회 @Override - public List getCartFoods(Long fridgeIdx, Long userIdx) { - Cart cart = getCart(userIdx, fridgeIdx); + public List getCartFoods(Long fridgeId, Long userId) { + Cart cart = getCart(userId, fridgeId); List cartResponses = new ArrayList<>(); for (FoodCategory category : FoodCategory.values()) { List cartFoods = cartFoodRepository.findByCartAndFood_FoodCategoryAndIsEnableOrderByCreatedAt(cart, category, true); @@ -62,8 +62,8 @@ public List getCartFoods(Long fridgeIdx, Long userIdx) { // 장바구니 식품 추가 @Transactional @Override - public void addCartFoods(Long fridgeIdx, AddFoodToCartRequest request, Long userIdx) { - Cart cart = getCart(userIdx, fridgeIdx); + public void addCartFoods(Long cartId, AddFoodToCartRequest request, Long userId) { + Cart cart = getCart(userId, cartId); // food 없는 경우 food 생성 List foodRequests = new ArrayList<>(); for(AddFoodRequest foodRequest : request.getFoodRequests()) { @@ -81,7 +81,7 @@ public void addCartFoods(Long fridgeIdx, AddFoodToCartRequest request, Long user .collect(Collectors.toList()); List cartFoods = foodRequests.stream() .filter((f) -> { - for (Long foodInIdx : foodsInNowCart) if(foodInIdx.equals(f.getId())) return false; + for (Long foodInId : foodsInNowCart) if(foodInId.equals(f.getId())) return false; return true; }) .map((food) -> CartFood.toEntity(cart, food)) @@ -93,16 +93,16 @@ public void addCartFoods(Long fridgeIdx, AddFoodToCartRequest request, Long user // 장바구니 식품 삭제 @Transactional @Override - public void deleteCartFoods(Long fridgeIdx, RemoveFoodFromCartRequest request, Long userIdx) { - Cart cart = getCart(userIdx, fridgeIdx); - List removeCartFoods = cartFoodRepository.findByCartIdAndFoodIdIn(cart.getId(), request.getFoodIdxes()); + public void deleteCartFoods(Long cartId, RemoveFoodFromCartRequest request, Long userId) { + Cart cart = getCart(userId, cartId); + List removeCartFoods = cartFoodRepository.findByCartIdAndFoodIdIn(cart.getId(), request.getFoodIds()); cartFoodRepository.deleteAll(removeCartFoods); } - private Cart getCart(Long userIdx, Long fridgeIdx) { - User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + private Cart getCart(Long userId, Long fridgeId) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); - return cartRepository.findByFridge_IdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_CART)); + return cartRepository.findByFridge_IdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_CART)); } } diff --git a/src/main/java/com/example/icebutler_server/food/dto/request/FoodReq.java b/src/main/java/com/example/icebutler_server/food/dto/request/FoodReq.java index efd60ab6..782c3bba 100644 --- a/src/main/java/com/example/icebutler_server/food/dto/request/FoodReq.java +++ b/src/main/java/com/example/icebutler_server/food/dto/request/FoodReq.java @@ -8,7 +8,7 @@ @Getter public class FoodReq { - private Long foodIdx; + private Long foodId; private String foodName; private String foodImgKey; private String foodCategory; diff --git a/src/main/java/com/example/icebutler_server/food/dto/response/FoodRes.java b/src/main/java/com/example/icebutler_server/food/dto/response/FoodRes.java index 825134a7..5a9933bc 100644 --- a/src/main/java/com/example/icebutler_server/food/dto/response/FoodRes.java +++ b/src/main/java/com/example/icebutler_server/food/dto/response/FoodRes.java @@ -15,7 +15,7 @@ @Schema(name = "FoodRes", description = "식품 검색 정보") public class FoodRes { @Schema(name = "식품 ID") - private Long foodIdx; + private Long foodId; @Schema(name = "식품명") private String foodName; @Schema(name = "식품 카테고리") @@ -25,7 +25,7 @@ public class FoodRes { public static FoodRes toDto(Food food) { return FoodRes.builder() - .foodIdx(food.getId()) + .foodId(food.getId()) .foodName(food.getFoodName()) .foodCategory(food.getFoodCategory().getName()) .foodImgUrl(AwsS3ImageUrlUtil.toUrl(food.getFoodImgKey())) diff --git a/src/main/java/com/example/icebutler_server/food/dto/response/FoodResponse.java b/src/main/java/com/example/icebutler_server/food/dto/response/FoodResponse.java index c613f3d1..f1f74b3a 100644 --- a/src/main/java/com/example/icebutler_server/food/dto/response/FoodResponse.java +++ b/src/main/java/com/example/icebutler_server/food/dto/response/FoodResponse.java @@ -11,7 +11,7 @@ @Schema(name = "FoodResponse", description = "장바구니 내 식품 정보") public class FoodResponse { @Schema(name = "식품 ID") - private Long foodIdx; + private Long foodId; @Schema(name = "식품명") private String foodName; @Schema(name = "식품 이미지 URL") @@ -19,7 +19,7 @@ public class FoodResponse { public static FoodResponse toDto(Food food) { FoodResponse foodResponse = new FoodResponse(); - foodResponse.foodIdx = food.getId(); + foodResponse.foodId = food.getId(); foodResponse.foodName = food.getFoodName(); foodResponse.foodImgUrl = AwsS3ImageUrlUtil.toUrl(food.getFoodImgKey()); return foodResponse; diff --git a/src/main/java/com/example/icebutler_server/food/repository/FoodRepository.java b/src/main/java/com/example/icebutler_server/food/repository/FoodRepository.java index 549bee8c..3a3fcba4 100644 --- a/src/main/java/com/example/icebutler_server/food/repository/FoodRepository.java +++ b/src/main/java/com/example/icebutler_server/food/repository/FoodRepository.java @@ -21,7 +21,7 @@ public interface FoodRepository extends JpaRepository { List findByFoodNameContains(String foodName); - Optional findByIdAndIsEnable(Long foodIdx, boolean status); + Optional findByIdAndIsEnable(Long foodId, boolean status); Page findByFoodNameContainsAndIsEnable(String cond, boolean status, Pageable pageable); diff --git a/src/main/java/com/example/icebutler_server/fridge/controller/FridgeController.java b/src/main/java/com/example/icebutler_server/fridge/controller/FridgeController.java index 91f8288b..3cbe2ccb 100644 --- a/src/main/java/com/example/icebutler_server/fridge/controller/FridgeController.java +++ b/src/main/java/com/example/icebutler_server/fridge/controller/FridgeController.java @@ -48,7 +48,7 @@ public ResponseCustom healthCheck() { @PostMapping("/register") public ResponseCustom registerFridge(@RequestBody FridgeRegisterReq fridgeRegisterReq, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - return ResponseCustom.success(fridgeService.registerFridge(fridgeRegisterReq, loginStatus.getUserIdx())); + return ResponseCustom.success(fridgeService.registerFridge(fridgeRegisterReq, loginStatus.getUserId())); } @Operation(summary = "냉장고 수정", description = "냉장고를 수정한다.") @@ -61,11 +61,11 @@ public ResponseCustom registerFridge(@RequestBody FridgeRegisterReq fridge content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth - @PatchMapping("/{fridgeIdx}") - public ResponseCustom modifyFridge(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, + @PatchMapping("/{fridgeId}") + public ResponseCustom modifyFridge(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, @RequestBody FridgeModifyReq fridgeModifyReq, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - fridgeService.modifyFridge(fridgeIdx, fridgeModifyReq, loginStatus.getUserIdx()); + fridgeService.modifyFridge(fridgeId, fridgeModifyReq, loginStatus.getUserId()); return ResponseCustom.success(); } @@ -81,10 +81,10 @@ public ResponseCustom modifyFridge(@Parameter(name = "냉장고 ID") @PathVar content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth - @PatchMapping("/{fridgeIdx}/remove") - public ResponseCustom removeFridge(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, + @PatchMapping("/{fridgeId}/remove") + public ResponseCustom removeFridge(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - return ResponseCustom.success(fridgeService.removeFridge(fridgeIdx, loginStatus.getUserIdx())); + return ResponseCustom.success(fridgeService.removeFridge(fridgeId, loginStatus.getUserId())); } @Operation(summary = "냉장고 사용자 삭제", description = "냉장고 사용자를 삭제한다.") @@ -98,10 +98,10 @@ public ResponseCustom removeFridge(@Parameter(name = "냉장고 ID") @Path content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth - @PatchMapping("/{fridgeIdx}/remove/each") - public ResponseCustom removeFridgeUser(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, + @PatchMapping("/{fridgeId}/remove/each") + public ResponseCustom removeFridgeUser(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - return ResponseCustom.success(fridgeService.removeFridgeUser(fridgeIdx, loginStatus.getUserIdx())); + return ResponseCustom.success(fridgeService.removeFridgeUser(fridgeId, loginStatus.getUserId())); } @Operation(summary = "냉장고 식품 전체 조회(카테고리별)", description = "냉장고 내 식품을 전체조회한다.") @@ -114,11 +114,11 @@ public ResponseCustom removeFridgeUser(@Parameter(name = "냉장고 ID") @ content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth - @GetMapping("/{fridgeIdx}/foods") - public ResponseCustom getFoods(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, + @GetMapping("/{fridgeId}/foods") + public ResponseCustom getFoods(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus, @Parameter(name = "식품 카테고리") @RequestParam(required = false) String category) { - return ResponseCustom.success(fridgeService.getFoods(fridgeIdx, loginStatus.getUserIdx(), category)); + return ResponseCustom.success(fridgeService.getFoods(fridgeId, loginStatus.getUserId(), category)); } @@ -129,11 +129,11 @@ public ResponseCustom getFoods(@Parameter(name = "냉장고 ID") content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth - @GetMapping("/{fridgeIdx}/search") - public ResponseCustom> searchFridgeFood(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, + @GetMapping("/{fridgeId}/search") + public ResponseCustom> searchFridgeFood(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, @Parameter(name = "식품명") @RequestParam String keyword, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - return ResponseCustom.success(fridgeService.searchFridgeFood(fridgeIdx, loginStatus.getUserIdx(), keyword)); + return ResponseCustom.success(fridgeService.searchFridgeFood(fridgeId, loginStatus.getUserId(), keyword)); } @Operation(summary = "냉장고 식품 상세 조회", description = "냉장고 내 식품을 상세 조회한다.") @@ -147,11 +147,11 @@ public ResponseCustom> searchFridgeFood(@Parameter(name = " content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth - @GetMapping("/{fridgeIdx}/foods/{fridgeFoodIdx}") - public ResponseCustom getFridgeFood(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, - @Parameter(name = "냉장고 내 식품 ID") @PathVariable Long fridgeFoodIdx, + @GetMapping("/{fridgeId}/foods/{fridgeFoodId}") + public ResponseCustom getFridgeFood(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, + @Parameter(name = "냉장고 내 식품 ID") @PathVariable Long fridgeFoodId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - return ResponseCustom.success(fridgeService.getFridgeFood(fridgeIdx, fridgeFoodIdx, loginStatus.getUserIdx())); + return ResponseCustom.success(fridgeService.getFridgeFood(fridgeId, fridgeFoodId, loginStatus.getUserId())); } @Operation(summary = "냉장고 식품 추가", description = "냉장고 내 식품을 추가한다.") @@ -166,11 +166,11 @@ public ResponseCustom getFridgeFood(@Parameter(name = "냉장고 content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth - @PostMapping("/{fridgeIdx}/food") + @PostMapping("/{fridgeId}/food") public ResponseCustom addFridgeFood(@RequestBody FridgeFoodsReq fridgeFoodsReq, - @Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, + @Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - fridgeService.addFridgeFood(fridgeFoodsReq, fridgeIdx, loginStatus.getUserIdx()); + fridgeService.addFridgeFood(fridgeFoodsReq, fridgeId, loginStatus.getUserId()); return ResponseCustom.success(); } @@ -187,12 +187,12 @@ public ResponseCustom addFridgeFood(@RequestBody FridgeFoodsReq fridgeFoodsRe content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth - @PatchMapping("/{fridgeIdx}/foods/{fridgeFoodIdx}") + @PatchMapping("/{fridgeId}/foods/{fridgeFoodId}") public ResponseCustom modifyFridgeFood(@RequestBody FridgeFoodReq fridgeFoodReq, - @Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, - @Parameter(name = "냉장고 내 식품 ID") @PathVariable Long fridgeFoodIdx, + @Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, + @Parameter(name = "냉장고 내 식품 ID") @PathVariable Long fridgeFoodId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - fridgeService.modifyFridgeFood(fridgeIdx, fridgeFoodIdx, fridgeFoodReq, loginStatus.getUserIdx()); + fridgeService.modifyFridgeFood(fridgeId, fridgeFoodId, fridgeFoodReq, loginStatus.getUserId()); return ResponseCustom.success(); } @@ -209,12 +209,12 @@ public ResponseCustom modifyFridgeFood(@RequestBody FridgeFoodReq fridgeFoodR content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth - @DeleteMapping("/{fridgeIdx}/foods") + @DeleteMapping("/{fridgeId}/foods") public ResponseCustom deleteFridgeFood(@RequestBody DeleteFridgeFoodsReq deleteFridgeFoodsReq, @Parameter(name = "삭제 타입(폐기/섭취)") @RequestParam String type, - @Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, + @Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - fridgeService.deleteFridgeFood(deleteFridgeFoodsReq, type, fridgeIdx, loginStatus.getUserIdx()); + fridgeService.deleteFridgeFood(deleteFridgeFoodsReq, type, fridgeId, loginStatus.getUserId()); return ResponseCustom.success(); } @@ -225,12 +225,12 @@ public ResponseCustom deleteFridgeFood(@RequestBody DeleteFridgeFoodsReq dele content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth - @GetMapping("{fridgeIdx}/members") + @GetMapping("{fridgeId}/members") public ResponseCustom getMembers( - @Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, + @Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus ) { - return ResponseCustom.success(fridgeService.searchMembers(fridgeIdx, loginStatus.getUserIdx())); + return ResponseCustom.success(fridgeService.searchMembers(fridgeId, loginStatus.getUserId())); } @Operation(summary = "냉장고 선택목록 조회", description = "냉장고 선택목록을 조회한다.") @@ -244,7 +244,7 @@ public ResponseCustom getMembers( public ResponseCustom selectFridges( @Parameter(hidden = true) @IsLogin LoginStatus loginStatus ) { - return ResponseCustom.success(fridgeService.selectFridges(loginStatus.getUserIdx())); + return ResponseCustom.success(fridgeService.selectFridges(loginStatus.getUserId())); } @Operation(summary = "냉장고 목록 조회", description = "냉장고 목록을 조회한다.") @@ -255,23 +255,21 @@ public ResponseCustom selectFridges( }) @Auth @GetMapping("") - public ResponseCustom myFridge( - @Parameter(hidden = true) @IsLogin LoginStatus loginStatus - ) { - return ResponseCustom.success(fridgeService.myFridge(loginStatus.getUserIdx())); + public ResponseCustom myFridge(@Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { + return ResponseCustom.success(fridgeService.myFridge(loginStatus.getUserId())); } /** * [Get] 냉장고 통계 (낭비/소비) */ @Auth - @GetMapping("/{fridgeIdx}/statistics") - public ResponseCustom getFridgeFoodStatistics(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeIdx, + @GetMapping("/{fridgeId}/statistics") + public ResponseCustom getFridgeFoodStatistics(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, @Parameter(name = "통계 타입(낭비/소비)") @RequestParam String deleteCategory, @Parameter(name = "연도") @RequestParam Integer year, @Parameter(name = "월") @RequestParam Integer month, @Parameter(hidden = true) @IsLogin LoginStatus status) { - return ResponseCustom.success(fridgeService.getFridgeFoodStatistics(fridgeIdx, deleteCategory, status.getUserIdx(), year, month)); + return ResponseCustom.success(fridgeService.getFridgeFoodStatistics(fridgeId, deleteCategory, status.getUserId(), year, month)); } @@ -288,8 +286,8 @@ public void notifyFridgeFood() { */ // todo: 토큰 추가하기 @GetMapping("/food-lists") - public ResponseCustom getFridgeUserFoodList(@RequestParam(name = "fridgeIdx", required = false) Long fridgeIdx, - @RequestParam(name = "userIdx") Long userIdx) { - return ResponseCustom.success(this.fridgeService.getFridgeUserFoodList(fridgeIdx, userIdx)); + public ResponseCustom getFridgeUserFoodList(@RequestParam(required = false) Long fridgeId, + @RequestParam Long userId) { + return ResponseCustom.success(this.fridgeService.getFridgeUserFoodList(fridgeId, userId)); } } diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeFoodReq.java b/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeFoodReq.java index d76930b4..cd0f38f3 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeFoodReq.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeFoodReq.java @@ -20,8 +20,8 @@ public class FridgeFoodReq { private String foodCategory; @Schema(name = "shelfLife", description = "식품 소비기한") private String shelfLife; - @Schema(name = "ownerIdx", description = "식품 소유자 ID") - private Long ownerIdx; + @Schema(name = "ownerId", description = "식품 소유자 ID") + private Long ownerId; @Schema(name = "memo", description = "식품 메모") private String memo; @Schema(name = "imgKey", description = "식품 이미지 URL") diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeModifyMembersReq.java b/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeModifyMembersReq.java index 334e2e8f..76e4f045 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeModifyMembersReq.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeModifyMembersReq.java @@ -5,14 +5,11 @@ import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; - - @Data @AllArgsConstructor @NoArgsConstructor @Schema(name = "FridgeModifyMembersReq", description = "냉장고 수정 멤버 요청 정보") public class FridgeModifyMembersReq { - @Schema(name = "userIdx", description = "유저 ID") - private Long userIdx; + @Schema(name = "userId", description = "유저 ID") + private Long userId; } diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeModifyReq.java b/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeModifyReq.java index b33c5e11..1425f38f 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeModifyReq.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeModifyReq.java @@ -7,7 +7,6 @@ import java.util.List; - @Data @AllArgsConstructor @NoArgsConstructor @@ -19,6 +18,6 @@ public class FridgeModifyReq { private String fridgeComment; @Schema(name = "members", description = "냉장고 멤버 ID") private List members; - @Schema(name = "newOwnerIdx", description = "냉장고 주인 ID") - private Long newOwnerIdx; + @Schema(name = "newOwnerId", description = "냉장고 주인 ID") + private Long newOwnerId; } diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeRegisterMembersReq.java b/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeRegisterMembersReq.java index 5a75b192..cb9b506a 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeRegisterMembersReq.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/request/FridgeRegisterMembersReq.java @@ -10,6 +10,6 @@ @NoArgsConstructor @Schema(name = "FridgeRegisterMembersReq", description = "냉장고 등록 멤버 ID") public class FridgeRegisterMembersReq { - @Schema(name = "userIdx", description = "유저 ID") - private Long userIdx; + @Schema(name = "userId", description = "유저 ID") + private Long userId; } diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodRes.java index c53f3907..9910f643 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodRes.java @@ -17,10 +17,10 @@ @NoArgsConstructor @Schema(name = "FridgeFoodRes", description = "냉장고 식품 상세 정보") public class FridgeFoodRes { - @Schema(name = "fridgeFoodIdx", description = "냉장고 ID") - private Long fridgeFoodIdx; - @Schema(name = "foodIdx", description = "식품 ID") - private Long foodIdx; + @Schema(name = "fridgeFoodId", description = "냉장고 ID") + private Long fridgeFoodId; + @Schema(name = "foodId", description = "식품 ID") + private Long foodId; @Schema(name = "foodName", description = "식품명") private String foodName; @Schema(name = "foodDetailName", description = "식품 상세명") @@ -40,8 +40,8 @@ public class FridgeFoodRes { public static FridgeFoodRes toDto(FridgeFood fridgeFood) { return FridgeFoodRes.builder() - .fridgeFoodIdx(fridgeFood.getId()) - .foodIdx(fridgeFood.getFood().getId()) + .fridgeFoodId(fridgeFood.getId()) + .foodId(fridgeFood.getFood().getId()) .foodName(fridgeFood.getFood().getFoodName()) .foodDetailName(fridgeFood.getFoodDetailName()) .foodCategory(fridgeFood.getFood().getFoodCategory().getName()) diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodsRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodsRes.java index 9eccd9af..087afed1 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodsRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodsRes.java @@ -15,8 +15,8 @@ @NoArgsConstructor @Schema(name = "FridgeFoodsRes", description = "냉장고 식품 정보") public class FridgeFoodsRes { - @Schema(name = "fridgeFoodIdx", description = "냉장고 식품 ID") - private Long fridgeFoodIdx; + @Schema(name = "fridgeFoodId", description = "냉장고 식품 ID") + private Long fridgeFoodId; @Schema(name = "foodName", description = "냉장고 식품 이름") private String foodName; @Schema(name = "foodImgUrl", description = "냉장고 식품 이미지 URL") @@ -26,7 +26,7 @@ public class FridgeFoodsRes { public static FridgeFoodsRes toDto(FridgeFood fridgeFood) { return FridgeFoodsRes.builder() - .fridgeFoodIdx(fridgeFood.getId()) + .fridgeFoodId(fridgeFood.getId()) .foodName(fridgeFood.getFood().getFoodName()) .foodImgUrl(AwsS3ImageUrlUtil.toUrl(fridgeFood.getFood().getFoodImgKey())) .shelfLife(FridgeUtils.calShelfLife(fridgeFood.getShelfLife())) diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeRes.java index 8cb4a1e4..8fc12e6a 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeRes.java @@ -16,8 +16,8 @@ @NoArgsConstructor @Schema(name = "FridgeRes", description = "가정용 냉장고 정보") public class FridgeRes { - @Schema(name = "fridgeIdx", description = "냉장고 ID") - private Long fridgeIdx; + @Schema(name = "fridgeId", description = "냉장고 ID") + private Long fridgeId; @Schema(name = "fridgeName", description = "냉장고 이름") private String fridgeName; @Schema(name = "comment", description = "냉장고 설명") @@ -36,7 +36,7 @@ public static FridgeRes toDto(Fridge fridge, List> fridgeUserLi } FridgeRes fridgeRes = new FridgeRes(); - fridgeRes.fridgeIdx = fridge.getId(); + fridgeRes.fridgeId = fridge.getId(); fridgeRes.fridgeName = fridge.getFridgeName(); fridgeRes.comment = fridge.getFridgeComment(); fridgeRes.users = fridgeUsers.stream().map(m -> FridgeUserRes.toDto(m.getUser(), m.getRole())).collect(Collectors.toList()); diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeUserRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeUserRes.java index 951b25df..fc60eacc 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeUserRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeUserRes.java @@ -15,8 +15,8 @@ @Builder @Schema(name = "FridgeUserRes", description = "냉장고 유저 정보") public class FridgeUserRes { - @Schema(name = "userIdx", description = "유저 ID") - private Long userIdx; + @Schema(name = "userId", description = "유저 ID") + private Long userId; @Schema(name = "nickname", description = "유저 닉네임") private String nickname; @Schema(name = "role", description = "냉장고 내 유저 역할") @@ -26,7 +26,7 @@ public class FridgeUserRes { public static FridgeUserRes toDto(User user, FridgeRole role) { FridgeUserRes fridgeUserRes = new FridgeUserRes(); - fridgeUserRes.userIdx = user.getId(); + fridgeUserRes.userId = user.getId(); fridgeUserRes.nickname = user.getNickname(); fridgeUserRes.role = role; fridgeUserRes.profileImgUrl = AwsS3ImageUrlUtil.toUrl(user.getProfileImgKey()); diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeUsersRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeUsersRes.java index e9ddd11e..3765b38d 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeUsersRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeUsersRes.java @@ -3,8 +3,6 @@ import com.example.icebutler_server.global.util.AwsS3ImageUrlUtil; import com.example.icebutler_server.user.entity.User; import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @@ -12,8 +10,8 @@ @NoArgsConstructor @Schema(name = "FridgeUsersRes", description = "냉장고 멤버 정보") public class FridgeUsersRes { - @Schema(name = "userIdx", description = "유저 ID") - private Long userIdx; + @Schema(name = "userId", description = "유저 ID") + private Long userId; @Schema(name = "nickName", description = "유저 닉네임") private String nickName; @Schema(name = "profileImageUrl", description = "유저 프로필 이미지 URL") @@ -22,7 +20,7 @@ public class FridgeUsersRes { public static FridgeUsersRes toDto(User user){ FridgeUsersRes fridgeUsersRes=new FridgeUsersRes(); fridgeUsersRes.nickName=user.getNickname(); - fridgeUsersRes.userIdx=user.getId(); + fridgeUsersRes.userId =user.getId(); fridgeUsersRes.profileImageUrl=AwsS3ImageUrlUtil.toUrl(user.getProfileImgKey()); return fridgeUsersRes; } diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/GetFridgesMainRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/GetFridgesMainRes.java index 6798531c..c5f20d3f 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/GetFridgesMainRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/GetFridgesMainRes.java @@ -22,10 +22,10 @@ public class GetFridgesMainRes { @Schema(name = "fridgeList", description = "가정용 냉장고 정보") List fridgeList; - public static GetFridgesMainRes toDto(List> fridgeUserListList, Long userIdx) { + public static GetFridgesMainRes toDto(List> fridgeUserListList, Long userId) { GetFridgesMainRes getFridgesMainRes = new GetFridgesMainRes(); - List fridgeUsers = fridgeUserListList.stream().map(m -> m.stream().filter(f -> f.getUser().getId().equals(userIdx)).findAny().orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER))).collect(Collectors.toList()); + List fridgeUsers = fridgeUserListList.stream().map(m -> m.stream().filter(f -> f.getUser().getId().equals(userId)).findAny().orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER))).collect(Collectors.toList()); getFridgesMainRes.fridgeList = fridgeUsers.stream().map(m -> FridgeRes.toDto(m.getFridge(), fridgeUserListList)).collect(Collectors.toList()); return getFridgesMainRes; diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/RecipeFridgeFoodListRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/RecipeFridgeFoodListRes.java index 7a4ab239..67b8829a 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/RecipeFridgeFoodListRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/RecipeFridgeFoodListRes.java @@ -12,5 +12,5 @@ @AllArgsConstructor @NoArgsConstructor public class RecipeFridgeFoodListRes { - private UUID foodIdx; + private UUID foodId; } \ No newline at end of file diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/SearchFoodRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/SearchFoodRes.java index 17fa51bd..d0609302 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/SearchFoodRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/SearchFoodRes.java @@ -10,12 +10,12 @@ @AllArgsConstructor @NoArgsConstructor public class SearchFoodRes { - private Long fridgeFoodIdx; + private Long fridgeFoodId; private String foodDetailName; - public static SearchFoodRes toDto(Long fridgeFoodIdx, String foodDetailName) { + public static SearchFoodRes toDto(Long fridgeFoodId, String foodDetailName) { SearchFoodRes searchFoodRes = new SearchFoodRes(); - searchFoodRes.fridgeFoodIdx = fridgeFoodIdx; + searchFoodRes.fridgeFoodId = fridgeFoodId; searchFoodRes.foodDetailName = foodDetailName; return searchFoodRes; } diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/SearchFridgeFoodRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/SearchFridgeFoodRes.java index f1721b7e..36d97247 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/SearchFridgeFoodRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/SearchFridgeFoodRes.java @@ -14,15 +14,15 @@ @AllArgsConstructor @NoArgsConstructor public class SearchFridgeFoodRes { - private Long fridgeIdx; - private Long userIdx; + private Long fridgeId; + private Long userId; private List searchFoods; - public static SearchFridgeFoodRes toDto(List searchFoods, Long fridgeIdx, Long userIdx) { + public static SearchFridgeFoodRes toDto(List searchFoods, Long fridgeId, Long userId) { SearchFridgeFoodRes searchFridgeFoodRes = new SearchFridgeFoodRes(); searchFridgeFoodRes.searchFoods = searchFoods.stream().map(m -> SearchFoodRes.toDto(m.getId(), m.getFoodDetailName())).collect(Collectors.toList()); - searchFridgeFoodRes.fridgeIdx = fridgeIdx; - searchFridgeFoodRes.userIdx = userIdx; + searchFridgeFoodRes.fridgeId = fridgeId; + searchFridgeFoodRes.userId = userId; return searchFridgeFoodRes; } } diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/SelectFridgeRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/SelectFridgeRes.java index 7b800cc9..857c3c9d 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/SelectFridgeRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/SelectFridgeRes.java @@ -8,12 +8,12 @@ public class SelectFridgeRes { @Schema(name = "fridgeName", description = "냉장고 이름") private String fridgeName; - @Schema(name = "fridgeIdx", description = "냉장고 ID") - private Long fridgeIdx; + @Schema(name = "fridgeId", description = "냉장고 ID") + private Long fridgeId; - public static SelectFridgeRes toDto(String fridgeName, Long fridgeIdx) { + public static SelectFridgeRes toDto(String fridgeName, Long fridgeId) { SelectFridgeRes selectFridgeRes = new SelectFridgeRes(); - selectFridgeRes.fridgeIdx = fridgeIdx; + selectFridgeRes.fridgeId = fridgeId; selectFridgeRes.fridgeName = fridgeName; return selectFridgeRes; } diff --git a/src/main/java/com/example/icebutler_server/fridge/repository/FridgeFood/FridgeFoodRepository.java b/src/main/java/com/example/icebutler_server/fridge/repository/FridgeFood/FridgeFoodRepository.java index 68354dd7..11bc52ec 100644 --- a/src/main/java/com/example/icebutler_server/fridge/repository/FridgeFood/FridgeFoodRepository.java +++ b/src/main/java/com/example/icebutler_server/fridge/repository/FridgeFood/FridgeFoodRepository.java @@ -15,7 +15,7 @@ @Repository public interface FridgeFoodRepository extends JpaRepository, FridgeFoodCustom { - Optional findByIdAndFridgeAndIsEnable(Long fridgeFoodIdx, Fridge fridge, Boolean status); + Optional findByIdAndFridgeAndIsEnable(Long fridgeFoodId, Fridge fridge, Boolean status); List findByFridgeAndFood_FoodCategoryAndIsEnableOrderByShelfLife(Fridge fridge, FoodCategory foodCategory, Boolean status); List findByFridgeAndIsEnableOrderByShelfLife(Fridge fridge, Boolean status); List findByFoodDetailNameContainingAndFridgeAndIsEnable(String keyword, Fridge fridge, Boolean isEnable); diff --git a/src/main/java/com/example/icebutler_server/fridge/repository/FridgeFood/FridgeFoodRepositoryImpl.java b/src/main/java/com/example/icebutler_server/fridge/repository/FridgeFood/FridgeFoodRepositoryImpl.java index 160ce145..412a38bf 100644 --- a/src/main/java/com/example/icebutler_server/fridge/repository/FridgeFood/FridgeFoodRepositoryImpl.java +++ b/src/main/java/com/example/icebutler_server/fridge/repository/FridgeFood/FridgeFoodRepositoryImpl.java @@ -53,15 +53,15 @@ public FridgeDiscardRes findByFridgeForDisCardFood(Fridge fridge) { } /** - * select food.food_idx, food.food_name + * select food.food_id, food.food_name * from food, * fridge_food as ff, fridge as f, fridge_user as fu, * multi_fridge_food as mff, multi_fridge as mf, multi_fridge_user as mfu - * where (food.food_idx = ff.food_idx and ff.fridge_idx = f.fridge_idx and f.fridge_idx = fu.fridge_idx - * and fu.user_idx = 369 and ff.is_enable = true and f.is_enable = true and fu.is_enable = true) - * or ((food.food_idx = mff.food_idx and mff.multi_fridge_idx = mf.multi_fridge_idx and mf.multi_fridge_idx = mfu.multi_fridge_idx) - * and (mfu.user_idx = 369 and mff.is_enable = true and mf.is_enable = true and mfu.is_enable = true)) - * group by food.food_idx; + * where (food.food_id = ff.food_id and ff.fridge_id = f.fridge_id and f.fridge_id = fu.fridge_id + * and fu.user_id = 369 and ff.is_enable = true and f.is_enable = true and fu.is_enable = true) + * or ((food.food_id = mff.food_id and mff.multi_fridge_id = mf.multi_fridge_id and mf.multi_fridge_id = mfu.multi_fridge_id) + * and (mfu.user_id = 369 and mff.is_enable = true and mf.is_enable = true and mfu.is_enable = true)) + * group by food.food_id; */ @Override diff --git a/src/main/java/com/example/icebutler_server/fridge/repository/FridgeRepository.java b/src/main/java/com/example/icebutler_server/fridge/repository/FridgeRepository.java index f37c8003..40b5b80b 100644 --- a/src/main/java/com/example/icebutler_server/fridge/repository/FridgeRepository.java +++ b/src/main/java/com/example/icebutler_server/fridge/repository/FridgeRepository.java @@ -8,5 +8,5 @@ @Repository public interface FridgeRepository extends JpaRepository { - Optional findByIdAndIsEnable(Long fridgeIdx, Boolean isEnable); + Optional findByIdAndIsEnable(Long fridgeId, Boolean isEnable); } diff --git a/src/main/java/com/example/icebutler_server/fridge/repository/FridgeUserRepository.java b/src/main/java/com/example/icebutler_server/fridge/repository/FridgeUserRepository.java index 65f202a1..7083e99a 100644 --- a/src/main/java/com/example/icebutler_server/fridge/repository/FridgeUserRepository.java +++ b/src/main/java/com/example/icebutler_server/fridge/repository/FridgeUserRepository.java @@ -17,7 +17,7 @@ public interface FridgeUserRepository extends JpaRepository { Optional findByFridgeAndUserAndRoleAndIsEnable(Fridge fridge, User user, FridgeRole fridgeRole, Boolean status); - Optional findByFridgeAndUser_IdAndRoleAndIsEnableAndUser_IsEnable(Fridge fridge, Long userIdx, FridgeRole fridgeRole, Boolean status, Boolean userStatus); + Optional findByFridgeAndUser_IdAndRoleAndIsEnableAndUser_IsEnable(Fridge fridge, Long userId, FridgeRole fridgeRole, Boolean status, Boolean userStatus); List findByFridgeAndIsEnable(Fridge fridge, Boolean isEnable); diff --git a/src/main/java/com/example/icebutler_server/fridge/service/FridgeService.java b/src/main/java/com/example/icebutler_server/fridge/service/FridgeService.java index dd1aeca8..4c8a5507 100644 --- a/src/main/java/com/example/icebutler_server/fridge/service/FridgeService.java +++ b/src/main/java/com/example/icebutler_server/fridge/service/FridgeService.java @@ -7,18 +7,18 @@ import java.util.List; public interface FridgeService { - FridgeMainRes getFoods(Long fridgeIdx, Long userIdx, String category); - Long registerFridge(FridgeRegisterReq registerFridgeReq, Long ownerIdx); - void modifyFridge(Long fridgeIdx, FridgeModifyReq updateFridgeReq, Long userIdx); - Long removeFridge(Long fridgeIdx, Long userIdx); - Long removeFridgeUser(Long fridgeIdx, Long userIdx) throws IOException; - List searchFridgeFood(Long fridgeIdx, Long ownerIdx, String foodName); - FridgeFoodRes getFridgeFood(Long fridgeIdx, Long fridgeFoodIdx, Long userIdx); - void addFridgeFood(FridgeFoodsReq fridgeFoodsReq, Long fridgeIdx, Long userIdx); - void modifyFridgeFood(Long fridgeIdx, Long fridgeFoodIdx, FridgeFoodReq fridgeFoodReq, Long userIdx); - void deleteFridgeFood(DeleteFridgeFoodsReq deleteFridgeFoodsReq, String deleteType, Long fridgeIdx, Long userIdx); - FridgeUserMainRes searchMembers(Long fridgeIdx, Long userIdx); - FridgeFoodsStatistics getFridgeFoodStatistics(Long fridgeIdx, String deleteCategory, Long userIdx, Integer year, Integer month); - RecipeFridgeFoodListsRes getFridgeUserFoodList(Long fridgeIdx, Long userIdx); + FridgeMainRes getFoods(Long fridgeId, Long userId, String category); + Long registerFridge(FridgeRegisterReq registerFridgeReq, Long ownerId); + void modifyFridge(Long fridgeId, FridgeModifyReq updateFridgeReq, Long userId); + Long removeFridge(Long fridgeId, Long userId); + Long removeFridgeUser(Long fridgeId, Long userId) throws IOException; + List searchFridgeFood(Long fridgeId, Long ownerId, String foodName); + FridgeFoodRes getFridgeFood(Long fridgeId, Long fridgeFoodId, Long userId); + void addFridgeFood(FridgeFoodsReq fridgeFoodsReq, Long fridgeId, Long userId); + void modifyFridgeFood(Long fridgeId, Long fridgeFoodId, FridgeFoodReq fridgeFoodReq, Long userId); + void deleteFridgeFood(DeleteFridgeFoodsReq deleteFridgeFoodsReq, String deleteType, Long fridgeId, Long userId); + FridgeUserMainRes searchMembers(Long fridgeId, Long userId); + FridgeFoodsStatistics getFridgeFoodStatistics(Long fridgeId, String deleteCategory, Long userId, Integer year, Integer month); + RecipeFridgeFoodListsRes getFridgeUserFoodList(Long fridgeId, Long userId); void notifyFridgeFood(); } diff --git a/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java b/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java index 6695f0bf..49549b0b 100644 --- a/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java @@ -54,9 +54,9 @@ public class FridgeServiceImpl implements FridgeService { private final NotificationServiceImpl alarmService; @Override - public FridgeMainRes getFoods(Long fridgeIdx, Long userIdx, String category) { - User user = this.userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + public FridgeMainRes getFoods(Long fridgeId, Long userId, String category) { + User user = this.userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); if (category == null) { // 값이 없으면 전체 조회 @@ -69,14 +69,14 @@ public FridgeMainRes getFoods(Long fridgeIdx, Long userIdx, String category) { @Override @Transactional - public Long registerFridge(FridgeRegisterReq registerFridgeReq, Long ownerIdx) { + public Long registerFridge(FridgeRegisterReq registerFridgeReq, Long ownerId) { if (!StringUtils.hasText(registerFridgeReq.getFridgeName())) throw new BaseException(INVALID_PARAM); Fridge fridge = Fridge.toEntity(registerFridgeReq); fridgeRepository.save(fridge); List fridgeUsers = new ArrayList<>(); - List users = registerFridgeReq.getMembers().stream().map(m -> userRepository.findByIdAndIsEnable(m.getUserIdx(), true).orElseThrow(() -> new BaseException(NOT_FOUND_USER))).collect(Collectors.toList()); - User owner = userRepository.findByIdAndIsEnable(ownerIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + List users = registerFridgeReq.getMembers().stream().map(m -> userRepository.findByIdAndIsEnable(m.getUserId(), true).orElseThrow(() -> new BaseException(NOT_FOUND_USER))).collect(Collectors.toList()); + User owner = userRepository.findByIdAndIsEnable(ownerId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); // fridge - fridgeUser 연관관계 추가 for (User user : users) { @@ -101,14 +101,14 @@ public Long registerFridge(FridgeRegisterReq registerFridgeReq, Long ownerIdx) { @Override @Transactional - public void modifyFridge(Long fridgeIdx, FridgeModifyReq updateFridgeReq, Long userIdx) { - User user = this.userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + public void modifyFridge(Long fridgeId, FridgeModifyReq updateFridgeReq, Long userId) { + User user = this.userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); FridgeUser owner = this.fridgeUserRepository.findByFridgeAndUserAndRoleAndIsEnable(fridge, user, FridgeRole.OWNER, true).orElseThrow(() -> new BaseException(NO_PERMISSION)); // 오너 업데이트 - if (!owner.getUser().getId().equals(updateFridgeReq.getNewOwnerIdx())) { - FridgeUser newOwner = this.fridgeUserRepository.findByFridgeAndUser_IdAndRoleAndIsEnableAndUser_IsEnable(fridge, updateFridgeReq.getNewOwnerIdx(), FridgeRole.MEMBER, true, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); + if (!owner.getUser().getId().equals(updateFridgeReq.getNewOwnerId())) { + FridgeUser newOwner = this.fridgeUserRepository.findByFridgeAndUser_IdAndRoleAndIsEnableAndUser_IsEnable(fridge, updateFridgeReq.getNewOwnerId(), FridgeRole.MEMBER, true, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); toUpdateFridgeOwner(owner, newOwner); } @@ -119,7 +119,7 @@ public void modifyFridge(Long fridgeIdx, FridgeModifyReq updateFridgeReq, Long u if (updateFridgeReq.getMembers() != null) { List members = this.fridgeUserRepository.findByFridgeAndIsEnable(fridge, true); List newMembers = updateFridgeReq.getMembers().stream() - .map(m -> this.userRepository.findByIdAndIsEnable(m.getUserIdx(), true).orElseThrow(() -> new BaseException(NOT_FOUND_USER))).collect(Collectors.toList()); + .map(m -> this.userRepository.findByIdAndIsEnable(m.getUserId(), true).orElseThrow(() -> new BaseException(NOT_FOUND_USER))).collect(Collectors.toList()); UpdateMembersRes updateMembers = toUpdateFridgeMembers(newMembers, members); if (!updateMembers.getCheckNewMember().isEmpty()) { @@ -185,9 +185,9 @@ private void toUpdateFridgeOwner(FridgeUser owner, FridgeUser newOwner) { // 냉장고 자체 삭제 @Transactional - public Long removeFridge(Long fridgeIdx, Long userId) { + public Long removeFridge(Long fridgeId, Long userId) { User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); FridgeUser owner = (FridgeUser) fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); List fridgeUsers = fridgeUserRepository.findByFridgeAndIsEnable(fridge, true); List fridgeFoods = fridgeFoodRepository.findByFridgeAndIsEnableOrderByShelfLife(fridge, true); @@ -206,9 +206,9 @@ public Long removeFridge(Long fridgeIdx, Long userId) { // 냉장고 개별 @Override @Transactional - public Long removeFridgeUser(Long fridgeIdx, Long userIdx) { - User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + public Long removeFridgeUser(Long fridgeId, Long userId) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); FridgeUser fridgeUser = (FridgeUser) fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); if (fridgeUser.getRole() == FridgeRole.OWNER) throw new BaseException(NO_PERMISSION); @@ -218,34 +218,34 @@ public Long removeFridgeUser(Long fridgeIdx, Long userIdx) { } @Override - public List searchFridgeFood(Long fridgeIdx, Long userIdx, String keyword) { - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + public List searchFridgeFood(Long fridgeId, Long ownerId, String keyword) { + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); List searchFoods = fridgeFoodRepository.findByFoodDetailNameContainingAndFridgeAndIsEnable(keyword, fridge, true); return searchFoods.stream().map(FridgeFoodsRes::toDto).collect(Collectors.toList()); } @Override - public FridgeFoodRes getFridgeFood(Long fridgeIdx, Long fridgeFoodIdx, Long userIdx) { - User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + public FridgeFoodRes getFridgeFood(Long fridgeId, Long fridgeFoodId, Long userId) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); - FridgeFood fridgeFood = fridgeFoodRepository.findByIdAndFridgeAndIsEnable(fridgeFoodIdx, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_FOOD)); + FridgeFood fridgeFood = fridgeFoodRepository.findByIdAndFridgeAndIsEnable(fridgeFoodId, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_FOOD)); return FridgeFoodRes.toDto(fridgeFood); } @Override @Transactional - public void addFridgeFood(FridgeFoodsReq fridgeFoodsReq, Long fridgeIdx, Long userIdx) { - User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + public void addFridgeFood(FridgeFoodsReq fridgeFoodsReq, Long fridgeId, Long userId) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); List fridgeFoods = new ArrayList<>(); for (FridgeFoodReq fridgeFoodReq : fridgeFoodsReq.getFridgeFoods()) { User owner = null; - if (fridgeFoodReq.getOwnerIdx() != null) { - owner = userRepository.findByIdAndIsEnable(fridgeFoodReq.getOwnerIdx(), true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + if (fridgeFoodReq.getOwnerId() != null) { + owner = userRepository.findByIdAndIsEnable(fridgeFoodReq.getOwnerId(), true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); fridgeUserRepository.findByUserAndFridgeAndIsEnable(owner, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); } Food food = foodRepository.findByFoodName(fridgeFoodReq.getFoodName()) @@ -262,14 +262,14 @@ public void addFridgeFood(FridgeFoodsReq fridgeFoodsReq, Long fridgeIdx, Long us @Override @Transactional - public void modifyFridgeFood(Long fridgeIdx, Long fridgeFoodIdx, FridgeFoodReq fridgeFoodReq, Long userIdx) { - User user = this.userRepository.findByIdAndIsEnable(userIdx, true) + public void modifyFridgeFood(Long fridgeId, Long fridgeFoodId, FridgeFoodReq fridgeFoodReq, Long userId) { + User user = this.userRepository.findByIdAndIsEnable(userId, true) .orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true) + Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeId, true) .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, user, true) .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); - FridgeFood modifyFridgeFood = this.fridgeFoodRepository.findByIdAndFridgeAndIsEnable(fridgeFoodIdx, fridge, true) + FridgeFood modifyFridgeFood = this.fridgeFoodRepository.findByIdAndFridgeAndIsEnable(fridgeFoodId, fridge, true) .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_FOOD)); if (!modifyFridgeFood.getFood().getFoodName().equals(fridgeFoodReq.getFoodName())) { @@ -289,10 +289,10 @@ public void modifyFridgeFood(Long fridgeIdx, Long fridgeFoodIdx, FridgeFoodReq f fridgeFoodReq.getImgKey() ); - if (fridgeFoodReq.getOwnerIdx() == null) + if (fridgeFoodReq.getOwnerId() == null) modifyFridgeFood.updateFridgeFoodOwner(null); else { - User newOwner = this.userRepository.findByIdAndIsEnable(fridgeFoodReq.getOwnerIdx(), true) + User newOwner = this.userRepository.findByIdAndIsEnable(fridgeFoodReq.getOwnerId(), true) .orElseThrow(() -> new BaseException(NOT_FOUND_USER)); this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, newOwner, true) .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); @@ -303,17 +303,17 @@ public void modifyFridgeFood(Long fridgeIdx, Long fridgeFoodIdx, FridgeFoodReq f @Override @Transactional - public void deleteFridgeFood(DeleteFridgeFoodsReq deleteFridgeFoodsReq, String type, Long fridgeIdx, Long userIdx) { + public void deleteFridgeFood(DeleteFridgeFoodsReq deleteFridgeFoodsReq, String type, Long fridgeId, Long userId) { FoodDeleteStatus deleteStatus = FoodDeleteStatus.getFoodDeleteStatusByName(type); - User user = this.userRepository.findByIdAndIsEnable(userIdx, true) + User user = this.userRepository.findByIdAndIsEnable(userId, true) .orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true) + Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeId, true) .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, user, true) .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); List deleteFridgeFoods = deleteFridgeFoodsReq.getDeleteFoods().stream() - .map(foodIdx -> this.fridgeFoodRepository.findByIdAndFridgeAndIsEnable(foodIdx, fridge, true) + .map(foodId -> this.fridgeFoodRepository.findByIdAndFridgeAndIsEnable(foodId, fridge, true) .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_FOOD))) .collect(Collectors.toList()); @@ -322,16 +322,16 @@ public void deleteFridgeFood(DeleteFridgeFoodsReq deleteFridgeFoodsReq, String t @Override //냉장고 내 유저 조회 - public FridgeUserMainRes searchMembers(Long fridgeIdx, Long userIdx) { - Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeIdx, true) + public FridgeUserMainRes searchMembers(Long fridgeId, Long userId) { + Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeId, true) .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); return FridgeUserMainRes.doDto(fridgeUserRepository.findByFridgeAndIsEnable(fridge, true)); } @Override - public FridgeFoodsStatistics getFridgeFoodStatistics(Long fridgeIdx, String deleteCategory, Long userIdx, Integer year, Integer month) { - User user = this.userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + public FridgeFoodsStatistics getFridgeFoodStatistics(Long fridgeId, String deleteCategory, Long userId, Integer year, Integer month) { + User user = this.userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, user, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); Map deleteStatusList = new HashMap<>(); @@ -359,29 +359,29 @@ private FridgeFoodsStatistics toFoodStatisticsByDeleteStatus(Map new BaseException(NOT_FOUND_USER)); + public SelectFridgesMainRes selectFridges(Long userId) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); return SelectFridgesMainRes.toDto(fridgeUserRepository.findByUserAndIsEnable(user, true)); } - public GetFridgesMainRes myFridge(Long userIdx) { - User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + public GetFridgesMainRes myFridge(Long userId) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); // 가정용 냉장고 조회 List fridgeUsers = fridgeUserRepository.findByUserAndIsEnable(user, true); List fridges = fridgeUsers.stream().map(m -> fridgeRepository.findByIdAndIsEnable(m.getFridge().getId(), true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE))).collect(Collectors.toList()); List> fridgeUserListList = fridges.stream().map(m -> fridgeUserRepository.findByFridgeAndIsEnableOrderByRoleDesc(m, true)).collect(Collectors.toList()); - return GetFridgesMainRes.toDto(fridgeUserListList, userIdx); + return GetFridgesMainRes.toDto(fridgeUserListList, userId); } // 사용자가 속한 가정용/공용 냉장고 food list - public RecipeFridgeFoodListsRes getFridgeUserFoodList(Long fridgeIdx, Long userIdx) { - User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + public RecipeFridgeFoodListsRes getFridgeUserFoodList(Long fridgeId, Long userId) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); + Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, user, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); return RecipeFridgeFoodListsRes.toDto(this.fridgeFoodRepository.findByUserForFridgeRecipeFoodList(fridge)); diff --git a/src/main/java/com/example/icebutler_server/global/feign/dto/AdminReq.java b/src/main/java/com/example/icebutler_server/global/feign/dto/AdminReq.java index 115a5c84..d1cd3cf4 100644 --- a/src/main/java/com/example/icebutler_server/global/feign/dto/AdminReq.java +++ b/src/main/java/com/example/icebutler_server/global/feign/dto/AdminReq.java @@ -8,18 +8,18 @@ @NoArgsConstructor @Data public class AdminReq { - private Long adminIdx; + private Long adminId; private String email; @Builder - public AdminReq(Long adminIdx, String email) { - this.adminIdx = adminIdx; + public AdminReq(Long adminId, String email) { + this.adminId = adminId; this.email = email; } public static AdminReq toDto(Admin admin){ AdminReq adminReq = new AdminReq(); - adminReq.adminIdx = admin.getId(); + adminReq.adminId = admin.getId(); adminReq.email = admin.getEmail(); return adminReq; } diff --git a/src/main/java/com/example/icebutler_server/global/feign/dto/FoodReq.java b/src/main/java/com/example/icebutler_server/global/feign/dto/FoodReq.java index 8b9dcc5b..2774fbf4 100644 --- a/src/main/java/com/example/icebutler_server/global/feign/dto/FoodReq.java +++ b/src/main/java/com/example/icebutler_server/global/feign/dto/FoodReq.java @@ -9,15 +9,15 @@ @Data public class FoodReq { - private Long foodIdx; + private Long foodId; private String foodName; private String foodImgKey; private FoodCategory foodCategory; private UUID uuid; @Builder - public FoodReq(Long foodIdx, String foodName, String foodImgKey, FoodCategory foodCategory, UUID uuid) { - this.foodIdx = foodIdx; + public FoodReq(Long foodId, String foodName, String foodImgKey, FoodCategory foodCategory, UUID uuid) { + this.foodId = foodId; this.foodName = foodName; this.foodImgKey = foodImgKey; this.foodCategory = foodCategory; @@ -26,7 +26,7 @@ public FoodReq(Long foodIdx, String foodName, String foodImgKey, FoodCategory fo public static FoodReq toDto(Food food) { return FoodReq.builder() - .foodIdx(food.getId()) + .foodId(food.getId()) .foodName(food.getFoodName()) .foodImgKey(food.getFoodImgKey()) .foodCategory(food.getFoodCategory()) diff --git a/src/main/java/com/example/icebutler_server/global/feign/dto/UserReq.java b/src/main/java/com/example/icebutler_server/global/feign/dto/UserReq.java index fb10d165..cb473652 100644 --- a/src/main/java/com/example/icebutler_server/global/feign/dto/UserReq.java +++ b/src/main/java/com/example/icebutler_server/global/feign/dto/UserReq.java @@ -5,14 +5,14 @@ @Data public class UserReq { - private Long userIdx; + private Long userId; private String nickname; private String profileImgKey; private String email; @Builder - public UserReq(Long userIdx, String nickname, String profileImgKey, String email) { - this.userIdx = userIdx; + public UserReq(Long userId, String nickname, String profileImgKey, String email) { + this.userId = userId; this.nickname = nickname; this.profileImgKey = profileImgKey; this.email = email; diff --git a/src/main/java/com/example/icebutler_server/global/feign/event/DeleteUserEvent.java b/src/main/java/com/example/icebutler_server/global/feign/event/DeleteUserEvent.java index e4235d59..927adb03 100644 --- a/src/main/java/com/example/icebutler_server/global/feign/event/DeleteUserEvent.java +++ b/src/main/java/com/example/icebutler_server/global/feign/event/DeleteUserEvent.java @@ -6,14 +6,14 @@ @Getter public class DeleteUserEvent { - private Long userIdx; + private Long userId; private String nickname; private String profileImgKey; private String email; public static DeleteUserEvent toEvent(User user){ DeleteUserEvent userJoinEvent = new DeleteUserEvent(); - userJoinEvent.userIdx = user.getId(); + userJoinEvent.userId = user.getId(); userJoinEvent.email = user.getEmail(); userJoinEvent.nickname = user.getNickname(); userJoinEvent.profileImgKey = user.getProfileImgKey(); @@ -22,7 +22,7 @@ public static DeleteUserEvent toEvent(User user){ public UserReq toDto() { return UserReq.builder() - .userIdx(this.userIdx) + .userId(this.userId) .nickname(this.nickname) .email(this.email) .profileImgKey(this.profileImgKey).build(); diff --git a/src/main/java/com/example/icebutler_server/global/feign/event/FoodEvent.java b/src/main/java/com/example/icebutler_server/global/feign/event/FoodEvent.java index 568b2cd2..e19ad5d5 100644 --- a/src/main/java/com/example/icebutler_server/global/feign/event/FoodEvent.java +++ b/src/main/java/com/example/icebutler_server/global/feign/event/FoodEvent.java @@ -9,7 +9,7 @@ @Getter public class FoodEvent { - private Long foodIdx; + private Long foodId; private String foodName; private String foodImgKey; private FoodCategory foodCategory; @@ -17,7 +17,7 @@ public class FoodEvent { public static FoodEvent toEvent(Food food){ FoodEvent foodJoinEvent = new FoodEvent(); - foodJoinEvent.foodIdx = food.getId(); + foodJoinEvent.foodId = food.getId(); foodJoinEvent.foodName = food.getFoodName(); foodJoinEvent.foodImgKey = food.getFoodImgKey(); foodJoinEvent.foodCategory = food.getFoodCategory(); @@ -27,7 +27,7 @@ public static FoodEvent toEvent(Food food){ public FoodReq toDto() { return FoodReq.builder() - .foodIdx(foodIdx) + .foodId(foodId) .foodName(foodName) .foodImgKey(foodImgKey) .foodCategory(foodCategory) diff --git a/src/main/java/com/example/icebutler_server/global/feign/event/UpdateFoodEvent.java b/src/main/java/com/example/icebutler_server/global/feign/event/UpdateFoodEvent.java index 6393e262..e438aebe 100644 --- a/src/main/java/com/example/icebutler_server/global/feign/event/UpdateFoodEvent.java +++ b/src/main/java/com/example/icebutler_server/global/feign/event/UpdateFoodEvent.java @@ -9,7 +9,7 @@ @Getter public class UpdateFoodEvent { - private Long foodIdx; + private Long foodId; private String foodName; private String foodImgKey; private FoodCategory foodCategory; @@ -17,7 +17,7 @@ public class UpdateFoodEvent { public static UpdateFoodEvent toEvent(Food food){ UpdateFoodEvent foodJoinEvent = new UpdateFoodEvent(); - foodJoinEvent.foodIdx = food.getId(); + foodJoinEvent.foodId = food.getId(); foodJoinEvent.foodName = food.getFoodName(); foodJoinEvent.foodImgKey = food.getFoodImgKey(); foodJoinEvent.foodCategory = food.getFoodCategory(); @@ -27,7 +27,7 @@ public static UpdateFoodEvent toEvent(Food food){ public FoodReq toDto() { return FoodReq.builder() - .foodIdx(foodIdx) + .foodId(foodId) .foodName(foodName) .foodImgKey(foodImgKey) .foodCategory(foodCategory) diff --git a/src/main/java/com/example/icebutler_server/global/feign/event/UpdateUserEvent.java b/src/main/java/com/example/icebutler_server/global/feign/event/UpdateUserEvent.java index 4222c6f2..18462921 100644 --- a/src/main/java/com/example/icebutler_server/global/feign/event/UpdateUserEvent.java +++ b/src/main/java/com/example/icebutler_server/global/feign/event/UpdateUserEvent.java @@ -6,14 +6,14 @@ @Getter public class UpdateUserEvent { - private Long userIdx; + private Long userId; private String nickname; private String profileImgKey; private String email; public static UpdateUserEvent toEvent(User user){ UpdateUserEvent userJoinEvent = new UpdateUserEvent(); - userJoinEvent.userIdx = user.getId(); + userJoinEvent.userId = user.getId(); userJoinEvent.email = user.getEmail(); userJoinEvent.nickname = user.getNickname(); userJoinEvent.profileImgKey = user.getProfileImgKey(); @@ -22,7 +22,7 @@ public static UpdateUserEvent toEvent(User user){ public UserReq toDto() { return UserReq.builder() - .userIdx(this.userIdx) + .userId(this.userId) .nickname(this.nickname) .email(this.email) .profileImgKey(this.profileImgKey).build(); diff --git a/src/main/java/com/example/icebutler_server/global/feign/event/UserEvent.java b/src/main/java/com/example/icebutler_server/global/feign/event/UserEvent.java index f9856610..7f54ab85 100644 --- a/src/main/java/com/example/icebutler_server/global/feign/event/UserEvent.java +++ b/src/main/java/com/example/icebutler_server/global/feign/event/UserEvent.java @@ -6,14 +6,14 @@ @Getter public class UserEvent { - private Long userIdx; + private Long userId; private String nickname; private String profileImgKey; private String email; public static UserEvent toEvent(User user){ UserEvent userJoinEvent = new UserEvent(); - userJoinEvent.userIdx = user.getId(); + userJoinEvent.userId = user.getId(); userJoinEvent.email = user.getEmail(); userJoinEvent.nickname = user.getNickname(); userJoinEvent.profileImgKey = user.getProfileImgKey(); @@ -22,7 +22,7 @@ public static UserEvent toEvent(User user){ public UserReq toDto() { return UserReq.builder() - .userIdx(this.userIdx) + .userId(this.userId) .nickname(this.nickname) .email(this.email) .profileImgKey(this.profileImgKey).build(); diff --git a/src/main/java/com/example/icebutler_server/global/feign/feignClient/RecipeServerClient.java b/src/main/java/com/example/icebutler_server/global/feign/feignClient/RecipeServerClient.java index efe506df..cacd0e72 100644 --- a/src/main/java/com/example/icebutler_server/global/feign/feignClient/RecipeServerClient.java +++ b/src/main/java/com/example/icebutler_server/global/feign/feignClient/RecipeServerClient.java @@ -25,8 +25,8 @@ public interface RecipeServerClient { @PostMapping("/admin") ResponseCustom addAdmin(@RequestBody AdminReq adminReq); - @DeleteMapping("/admin/users/{userIdx}") - ResponseCustom withdrawUser(@PathVariable("userIdx") Long userIdx, @RequestHeader Map requestHeader); + @DeleteMapping("/admin/users/{userId}") + ResponseCustom withdrawUser(@PathVariable Long userId, @RequestHeader Map requestHeader); @DeleteMapping("/foods") void deleteFood(@RequestBody FoodReq foodReq); diff --git a/src/main/java/com/example/icebutler_server/global/resolver/AdminLoginStatus.java b/src/main/java/com/example/icebutler_server/global/resolver/AdminLoginStatus.java index 0ede7970..17ee4a67 100644 --- a/src/main/java/com/example/icebutler_server/global/resolver/AdminLoginStatus.java +++ b/src/main/java/com/example/icebutler_server/global/resolver/AdminLoginStatus.java @@ -6,11 +6,11 @@ @Data public class AdminLoginStatus { private Boolean isLogin; - private Long adminIdx; + private Long adminId; @Builder - public AdminLoginStatus(Boolean isLogin, Long adminIdx) { + public AdminLoginStatus(Boolean isLogin, Long adminId) { this.isLogin = isLogin; - this.adminIdx = adminIdx; + this.adminId = adminId; } public static AdminLoginStatus getNotAdminLoginStatus() { return new AdminLoginStatus(false, null); diff --git a/src/main/java/com/example/icebutler_server/global/resolver/AdminResolver.java b/src/main/java/com/example/icebutler_server/global/resolver/AdminResolver.java index 3abe4dfb..6430abbb 100644 --- a/src/main/java/com/example/icebutler_server/global/resolver/AdminResolver.java +++ b/src/main/java/com/example/icebutler_server/global/resolver/AdminResolver.java @@ -49,12 +49,12 @@ public Object resolveArgument(@NotNull MethodParameter parameter, if(accessToken == null || !tokenUtils.isValidToken(tokenUtils.parseJustTokenFromFullToken(accessToken))) return AdminLoginStatus.getNotAdminLoginStatus(); - Long adminIdx = Long.valueOf(tokenUtils.getUserIdFromFullToken(accessToken)); + Long adminId = Long.valueOf(tokenUtils.getUserIdFromFullToken(accessToken)); - if (!admin.optional() && adminIdx == null) { + if (!admin.optional() && adminId == null) { return AdminLoginStatus.getNotAdminLoginStatus(); } - return AdminLoginStatus.builder().isLogin(true).adminIdx(adminIdx).build(); + return AdminLoginStatus.builder().isLogin(true).adminId(adminId).build(); } } diff --git a/src/main/java/com/example/icebutler_server/global/resolver/LoginResolver.java b/src/main/java/com/example/icebutler_server/global/resolver/LoginResolver.java index b8efa915..5e0a702c 100644 --- a/src/main/java/com/example/icebutler_server/global/resolver/LoginResolver.java +++ b/src/main/java/com/example/icebutler_server/global/resolver/LoginResolver.java @@ -49,12 +49,12 @@ public Object resolveArgument(@NotNull MethodParameter parameter, if(accessToken == null || !tokenUtils.isValidToken(tokenUtils.parseJustTokenFromFullToken(accessToken))) return LoginStatus.getNotLoginStatus(); - Long userIdx = Long.valueOf(tokenUtils.getUserIdFromFullToken(accessToken)); + Long userId = Long.valueOf(tokenUtils.getUserIdFromFullToken(accessToken)); - if (!auth.optional() && userIdx == null) { + if (!auth.optional() && userId == null) { return LoginStatus.getNotLoginStatus(); } - return LoginStatus.builder().isLogin(true).userIdx(userIdx).build(); + return LoginStatus.builder().isLogin(true).userId(userId).build(); } } diff --git a/src/main/java/com/example/icebutler_server/global/resolver/LoginStatus.java b/src/main/java/com/example/icebutler_server/global/resolver/LoginStatus.java index fab78ecf..5b08086c 100644 --- a/src/main/java/com/example/icebutler_server/global/resolver/LoginStatus.java +++ b/src/main/java/com/example/icebutler_server/global/resolver/LoginStatus.java @@ -6,11 +6,11 @@ @Data public class LoginStatus { private Boolean isLogin; - private Long userIdx; + private Long userId; @Builder - public LoginStatus(Boolean isLogin, Long userIdx) { + public LoginStatus(Boolean isLogin, Long userId) { this.isLogin = isLogin; - this.userIdx = userIdx; + this.userId = userId; } public static LoginStatus getNotLoginStatus() { return new LoginStatus(false, null); diff --git a/src/main/java/com/example/icebutler_server/global/util/TokenUtils.java b/src/main/java/com/example/icebutler_server/global/util/TokenUtils.java index da066c15..e7807e8c 100644 --- a/src/main/java/com/example/icebutler_server/global/util/TokenUtils.java +++ b/src/main/java/com/example/icebutler_server/global/util/TokenUtils.java @@ -21,7 +21,7 @@ @RequiredArgsConstructor @Component public class TokenUtils { - public static final String USER_IDX = "userIdx"; + public static final String USER_ID = "userId"; public static final String NICKNAME = "nickname"; public static final String EMAIL = "email"; @@ -86,17 +86,17 @@ public String createToken(User user) { return access_token + COMMA + refresh_token; } - public String createToken(Long idx, String email) { - String access_token = this.createAccessTokenEmail(idx, email); - String refresh_token = this.createRefreshTokenEmail(idx, email); + public String createToken(Long id, String email) { + String access_token = this.createAccessTokenEmail(id, email); + String refresh_token = this.createRefreshTokenEmail(id, email); return access_token + COMMA + refresh_token; } - public String createAccessToken(Long userIdx, String nickname) { + public String createAccessToken(Long userId, String nickname) { Claims claims = Jwts.claims() .setSubject(accessName) .setIssuedAt(new Date()); - claims.put(USER_IDX, userIdx); + claims.put(USER_ID, userId); claims.put(NICKNAME, nickname); Date ext = new Date(); ext.setTime(ext.getTime() + Long.parseLong(Objects.requireNonNull(accessExTime))); @@ -109,11 +109,11 @@ public String createAccessToken(Long userIdx, String nickname) { return tokenType + ONE_BLOCK + accessToken; } - public String createRefreshToken(Long userIdx, String nickname) { + public String createRefreshToken(Long userId, String nickname) { Claims claims = Jwts.claims() .setSubject(refreshName) .setIssuedAt(new Date()); - claims.put(USER_IDX, userIdx); + claims.put(USER_ID, userId); claims.put(NICKNAME, nickname); Date ext = new Date(); ext.setTime(ext.getTime() + Long.parseLong(Objects.requireNonNull(refreshExTime))); @@ -123,15 +123,15 @@ public String createRefreshToken(Long userIdx, String nickname) { .setExpiration(ext) .signWith(SignatureAlgorithm.HS256, secretKey) .compact(); - redisTemplateService.setUserRefreshToken(userIdx.toString(), tokenType + ONE_BLOCK + refreshToken); + redisTemplateService.setUserRefreshToken(userId.toString(), tokenType + ONE_BLOCK + refreshToken); return tokenType + ONE_BLOCK + refreshToken; } - public String createAccessTokenEmail(Long userIdx, String email) { + public String createAccessTokenEmail(Long userId, String email) { Claims claims = Jwts.claims() .setSubject(accessName) .setIssuedAt(new Date()); - claims.put(USER_IDX, userIdx); + claims.put(USER_ID, userId); claims.put(EMAIL, email); Date ext = new Date(); ext.setTime(ext.getTime() + Long.parseLong(Objects.requireNonNull(accessExTime))); @@ -144,11 +144,11 @@ public String createAccessTokenEmail(Long userIdx, String email) { return tokenType + ONE_BLOCK + accessToken; } - public String createRefreshTokenEmail(Long userIdx, String email) { + public String createRefreshTokenEmail(Long userId, String email) { Claims claims = Jwts.claims() .setSubject(refreshName) .setIssuedAt(new Date()); - claims.put(USER_IDX, userIdx); + claims.put(USER_ID, userId); claims.put(EMAIL, email); Date ext = new Date(); ext.setTime(ext.getTime() + Long.parseLong(Objects.requireNonNull(refreshExTime))); @@ -158,7 +158,7 @@ public String createRefreshTokenEmail(Long userIdx, String email) { .setExpiration(ext) .signWith(SignatureAlgorithm.HS256, secretKey) .compact(); - redisTemplateService.setUserRefreshToken(userIdx.toString(), tokenType + ONE_BLOCK + refreshToken); + redisTemplateService.setUserRefreshToken(userId.toString(), tokenType + ONE_BLOCK + refreshToken); return tokenType + ONE_BLOCK + refreshToken; } @@ -221,7 +221,7 @@ public boolean isTokenExpired(String justToken) { } public String getUserIdFromFullToken(String fullToken) { - return String.valueOf(getJwtBodyFromJustToken(parseJustTokenFromFullToken(fullToken)).get(USER_IDX)); + return String.valueOf(getJwtBodyFromJustToken(parseJustTokenFromFullToken(fullToken)).get(USER_ID)); } public String getNicknameFromFullToken(String fullToken) { @@ -239,14 +239,14 @@ public String parseJustTokenFromFullToken(String fullToken) { } @Transactional - public String accessExpiration(Long userIdx) { - String userRefreshToken = redisTemplateService.getUserRefreshToken(userIdx.toString()); + public String accessExpiration(Long userId) { + String userRefreshToken = redisTemplateService.getUserRefreshToken(userId.toString()); if (userRefreshToken == null) throw new BaseException(EXPIRED_TOKEN); String refreshNickname = getNicknameFromFullToken(userRefreshToken); if (refreshNickname.isEmpty()) throw new BaseException(EXPIRED_TOKEN); //토큰이 만료되었을 경우. - return createAccessToken(userIdx, refreshNickname); + return createAccessToken(userId, refreshNickname); } } diff --git a/src/main/java/com/example/icebutler_server/global/util/redis/RedisTemplateService.java b/src/main/java/com/example/icebutler_server/global/util/redis/RedisTemplateService.java index 097f29de..8f83f8f4 100644 --- a/src/main/java/com/example/icebutler_server/global/util/redis/RedisTemplateService.java +++ b/src/main/java/com/example/icebutler_server/global/util/redis/RedisTemplateService.java @@ -3,7 +3,7 @@ import com.sun.istack.NotNull; public interface RedisTemplateService { - public void deleteUserRefreshToken(@NotNull String userIdx); - public String getUserRefreshToken(@NotNull String userIdx); - public void setUserRefreshToken(@NotNull String userIdx, String refreshToken) ; + public void deleteUserRefreshToken(@NotNull String userId); + public String getUserRefreshToken(@NotNull String userId); + public void setUserRefreshToken(@NotNull String userId, String refreshToken) ; } \ No newline at end of file diff --git a/src/main/java/com/example/icebutler_server/global/util/redis/RedisTemplateServiceImpl.java b/src/main/java/com/example/icebutler_server/global/util/redis/RedisTemplateServiceImpl.java index e436b07f..8529c685 100644 --- a/src/main/java/com/example/icebutler_server/global/util/redis/RedisTemplateServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/global/util/redis/RedisTemplateServiceImpl.java @@ -13,17 +13,17 @@ public class RedisTemplateServiceImpl implements RedisTemplateService { private final RedisTemplate redisTemplate; - public void deleteUserRefreshToken(String userIdx){ - if(redisTemplate.opsForValue().get(userIdx)!=null) redisTemplate.delete(userIdx); + public void deleteUserRefreshToken(String userId){ + if(redisTemplate.opsForValue().get(userId)!=null) redisTemplate.delete(userId); } // @Nullable @Transactional(readOnly = true) - public String getUserRefreshToken(@NotNull String userIdx) { - return redisTemplate.opsForValue().get(userIdx); + public String getUserRefreshToken(@NotNull String userId) { + return redisTemplate.opsForValue().get(userId); } - public void setUserRefreshToken(@NotNull String userIdx, String refreshToken) { - redisTemplate.opsForValue().set(userIdx, refreshToken); + public void setUserRefreshToken(@NotNull String userId, String refreshToken) { + redisTemplate.opsForValue().set(userId, refreshToken); } } diff --git a/src/main/java/com/example/icebutler_server/user/controller/UserAuthController.java b/src/main/java/com/example/icebutler_server/user/controller/UserAuthController.java index 22229783..1403b961 100644 --- a/src/main/java/com/example/icebutler_server/user/controller/UserAuthController.java +++ b/src/main/java/com/example/icebutler_server/user/controller/UserAuthController.java @@ -40,7 +40,7 @@ public class UserAuthController { @Auth @GetMapping("/renew") public ResponseCustom accessToken(@Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - return ResponseCustom.success(tokenUtils.accessExpiration(loginStatus.getUserIdx())); + return ResponseCustom.success(tokenUtils.accessExpiration(loginStatus.getUserId())); } @Operation(summary = "유저 프로필 수정", description = "유저 프로필을 수정한다.") @@ -53,7 +53,7 @@ public ResponseCustom accessToken(@Parameter(hidden = true) @IsLogin Log @PatchMapping("/profile") public ResponseCustom modifyProfile(@RequestBody PatchProfileReq patchProfileReq, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - userService.modifyProfile(loginStatus.getUserIdx(), patchProfileReq); + userService.modifyProfile(loginStatus.getUserId(), patchProfileReq); return ResponseCustom.success(); } @@ -68,7 +68,7 @@ public ResponseCustom modifyProfile(@RequestBody PatchProfileReq patchProfile @DeleteMapping("/delete") public ResponseCustom deleteUser( @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - userService.deleteUser(loginStatus.getUserIdx()); + userService.deleteUser(loginStatus.getUserId()); return ResponseCustom.success(); } @@ -81,7 +81,7 @@ public ResponseCustom deleteUser( @PostMapping("/logout") public ResponseCustom logout( @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - userService.logout(loginStatus.getUserIdx()); + userService.logout(loginStatus.getUserId()); return ResponseCustom.success(); } @@ -94,7 +94,7 @@ public ResponseCustom logout( @GetMapping("") public ResponseCustom profile( @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - return ResponseCustom.success(userService.checkProfile(loginStatus.getUserIdx())); + return ResponseCustom.success(userService.checkProfile(loginStatus.getUserId())); } @Operation(summary = "유저 알림 목록", description = "유저 알림 목록을 조회한다.") @@ -107,7 +107,7 @@ public ResponseCustom profile( public ResponseCustom> getUserNotification( @Parameter(hidden = true) @IsLogin LoginStatus loginStatus, @PageableDefault(size = 10) Pageable pageable) { - return ResponseCustom.success(userService.getUserNotification(loginStatus.getUserIdx(), pageable)); + return ResponseCustom.success(userService.getUserNotification(loginStatus.getUserId(), pageable)); } } diff --git a/src/main/java/com/example/icebutler_server/user/dto/request/UserAuthTokenReq.java b/src/main/java/com/example/icebutler_server/user/dto/request/UserAuthTokenReq.java index 5d5ec084..f46492ef 100644 --- a/src/main/java/com/example/icebutler_server/user/dto/request/UserAuthTokenReq.java +++ b/src/main/java/com/example/icebutler_server/user/dto/request/UserAuthTokenReq.java @@ -9,13 +9,13 @@ @Getter public class UserAuthTokenReq { - private Long userIdx; + private Long userId; private String nickname; @Builder - public UserAuthTokenReq(Long userIdx, String nickname) { - this.userIdx = userIdx; + public UserAuthTokenReq(Long userId, String nickname) { + this.userId = userId; this.nickname = nickname; } diff --git a/src/main/java/com/example/icebutler_server/user/dto/response/MyProfileRes.java b/src/main/java/com/example/icebutler_server/user/dto/response/MyProfileRes.java index 2d61760a..ead9134f 100644 --- a/src/main/java/com/example/icebutler_server/user/dto/response/MyProfileRes.java +++ b/src/main/java/com/example/icebutler_server/user/dto/response/MyProfileRes.java @@ -11,8 +11,8 @@ @RequiredArgsConstructor @Schema(name = "MyProfileRes", description = "유저 프로필 조회 정보") public class MyProfileRes { - @Schema(name = "userIdx", description = "유저 ID") - private Long userIdx; + @Schema(name = "userId", description = "유저 ID") + private Long userId; @Schema(name = "nickname", description = "유저 닉네임") private String nickname; @Schema(name = "profileImgUrl", description = "유저 프로필 이미지 URL") @@ -21,8 +21,8 @@ public class MyProfileRes { private String email; @Builder - public MyProfileRes(Long userIdx, String nickname, String profileImgUrl, String email) { - this.userIdx = userIdx; + public MyProfileRes(Long userId, String nickname, String profileImgUrl, String email) { + this.userId = userId; this.nickname = nickname; this.profileImgUrl = profileImgUrl; this.email = email; @@ -30,7 +30,7 @@ public MyProfileRes(Long userIdx, String nickname, String profileImgUrl, String public static MyProfileRes toDto(User user) { MyProfileResBuilder builder = MyProfileRes.builder() - .userIdx(user.getId()) + .userId(user.getId()) .nickname(user.getNickname()) .email(user.getEmail()); diff --git a/src/main/java/com/example/icebutler_server/user/dto/response/NickNameRes.java b/src/main/java/com/example/icebutler_server/user/dto/response/NickNameRes.java index 12345c49..3e612d3d 100644 --- a/src/main/java/com/example/icebutler_server/user/dto/response/NickNameRes.java +++ b/src/main/java/com/example/icebutler_server/user/dto/response/NickNameRes.java @@ -16,8 +16,8 @@ public class NickNameRes { @Schema(name = "nickname", description = "닉네임") private String nickname; - @Schema(name = "userIdx", description = "유저 ID") - private Long userIdx; + @Schema(name = "userId", description = "유저 ID") + private Long userId; @Schema(name = "profileImgUrl", description = "유저 프로필 이미지 URL") private String profileImgUrl; @@ -25,7 +25,7 @@ public class NickNameRes { public static NickNameRes toDto(User user){ return NickNameRes.builder() .nickname(user.getNickname()) - .userIdx(user.getId()) + .userId(user.getId()) .profileImgUrl(AwsS3ImageUrlUtil.toUrl(user.getProfileImgKey())) .build(); } diff --git a/src/main/java/com/example/icebutler_server/user/repository/UserRepository.java b/src/main/java/com/example/icebutler_server/user/repository/UserRepository.java index 1b73431a..826e928d 100644 --- a/src/main/java/com/example/icebutler_server/user/repository/UserRepository.java +++ b/src/main/java/com/example/icebutler_server/user/repository/UserRepository.java @@ -10,7 +10,7 @@ @Repository public interface UserRepository extends JpaRepository { - Optional findByIdAndIsEnable(Long userIdx, Boolean isEnable); + Optional findByIdAndIsEnable(Long userId, Boolean isEnable); User findByEmailAndProvider(String email, Provider provider); Boolean existsByNickname(String nickName); List findByNicknameContains(String nickname); diff --git a/src/main/java/com/example/icebutler_server/user/service/UserService.java b/src/main/java/com/example/icebutler_server/user/service/UserService.java index 51759f10..0ff5cf8f 100644 --- a/src/main/java/com/example/icebutler_server/user/service/UserService.java +++ b/src/main/java/com/example/icebutler_server/user/service/UserService.java @@ -16,17 +16,17 @@ public interface UserService { PostUserRes login(LoginUserReq loginUserReq); - void modifyProfile(@IsLogin Long userIdx, PatchProfileReq patchProfileReq); + void modifyProfile(@IsLogin Long userId, PatchProfileReq patchProfileReq); PostNickNameRes checkNickname(PostNicknameReq postNicknameReq); - void deleteUser(Long userIdx); + void deleteUser(Long userId); - void logout(Long userIdx); + void logout(Long userId); - MyProfileRes checkProfile(Long userIdx); + MyProfileRes checkProfile(Long userId); List searchNickname(String nickname); - Page getUserNotification(Long userIdx, Pageable pageable); + Page getUserNotification(Long userId, Pageable pageable); } diff --git a/src/main/java/com/example/icebutler_server/user/service/UserServiceImpl.java b/src/main/java/com/example/icebutler_server/user/service/UserServiceImpl.java index 76fbf50e..3bc8cef7 100644 --- a/src/main/java/com/example/icebutler_server/user/service/UserServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/user/service/UserServiceImpl.java @@ -95,8 +95,8 @@ public User saveUser(PostUserReq postUserReq) { // 프로필 설정 @Transactional - public void modifyProfile(@IsLogin Long userIdx, PatchProfileReq patchProfileReq) { - User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + public void modifyProfile(@IsLogin Long userId, PatchProfileReq patchProfileReq) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); if (StringUtils.hasText(patchProfileReq.getNickname())) user.modifyProfileNickName(patchProfileReq.getNickname()); if (StringUtils.hasText(patchProfileReq.getProfileImgKey())) user.modifyProfileImgKey(patchProfileReq.getProfileImgKey()); @@ -127,8 +127,8 @@ private Boolean isValidNickname(String nickname) { //유저 탈퇴 @Override @Transactional - public void deleteUser(Long userIdx) { - User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + public void deleteUser(Long userId) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); List fridgeOwners = fridgeUserRepository.findByUserAndRoleAndIsEnable(user, FridgeRole.OWNER, true); for (FridgeUser fridgeOwner : fridgeOwners) { Fridge fridge = fridgeOwner.getFridge(); @@ -139,7 +139,7 @@ public void deleteUser(Long userIdx) { fridgeRepository.delete(fridge); } user.deleteUser(); - redisTemplateService.deleteUserRefreshToken(userIdx.toString()); + redisTemplateService.deleteUserRefreshToken(userId.toString()); // user.setIsEnable(false); recipeServerEventPublisher.deleteUser(user); } @@ -147,16 +147,16 @@ public void deleteUser(Long userIdx) { //유저 로그아웃 @Override @Transactional - public void logout(Long userIdx) { - User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - redisTemplateService.deleteUserRefreshToken(userIdx.toString()); + public void logout(Long userId) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + redisTemplateService.deleteUserRefreshToken(userId.toString()); user.logout(); } //마이페이지 조회 @Override - public MyProfileRes checkProfile(Long userIdx) { - User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + public MyProfileRes checkProfile(Long userId) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); return MyProfileRes.toDto(user); @@ -170,8 +170,8 @@ public List searchNickname(String nickname) { } @Override - public Page getUserNotification(Long userIdx, Pageable pageable) { - User user = userRepository.findByIdAndIsEnable(userIdx, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + public Page getUserNotification(Long userId, Pageable pageable) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); return MyNotificationRes.toUserNotificationList(this.pushNotificationRepository.findByUserOrderByCreatedAtDesc(user, pageable)); } From 6ad77c6843f5a33a4a67ba67de5b7b5f8fb166f8 Mon Sep 17 00:00:00 2001 From: psyeon1120 Date: Fri, 12 Jul 2024 01:05:21 +0900 Subject: [PATCH 7/9] =?UTF-8?q?#327=20docs:=20exception=20=EA=B4=80?= =?UTF-8?q?=EB=A0=A8=20swagger=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cart/controller/CartController.java | 30 ++- .../cart/service/CartServiceImpl.java | 10 +- .../food/controller/FoodController.java | 13 +- .../fridge/controller/FridgeController.java | 150 ++++++----- .../fridge/service/FridgeServiceImpl.java | 22 +- .../user/controller/UserAuthController.java | 152 ++++++----- .../user/controller/UserController.java | 89 ++++--- .../user/service/UserServiceImpl.java | 247 +++++++++--------- 8 files changed, 375 insertions(+), 338 deletions(-) diff --git a/src/main/java/com/example/icebutler_server/cart/controller/CartController.java b/src/main/java/com/example/icebutler_server/cart/controller/CartController.java index 34de3a70..f313626f 100644 --- a/src/main/java/com/example/icebutler_server/cart/controller/CartController.java +++ b/src/main/java/com/example/icebutler_server/cart/controller/CartController.java @@ -34,11 +34,11 @@ public class CartController { @Operation(summary = "장바구니 식품 조회", description = "장바구니 식품 목록을 조회한다.") @SwaggerApiSuccess(implementation = CartResponse.class) @ApiResponses(value = { - @ApiResponse(responseCode = "403", description = "냉장고의 멤버가 아닙니다.", + @ApiResponse(responseCode = "403", description = "(G0001)권한이 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "(U0005)해당 유저를 찾을 수 없습니다.\t\n" + - "요청한 id를 가진 냉장고를 찾을 수 없습니다.\t\n" + - "(C0000)장바구니를 찾을 수 없습니다.", + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.\t\n" + + "(R0000)존재하지 않는 냉장고입니다.\t\n" + + "(C0000)존재하지 않는 장바구니입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @@ -51,12 +51,13 @@ public ResponseCustom> getCartFoods(@Parameter(name = "냉장 @Operation(summary = "장바구니 식품 추가", description = "장바구니에 식품을 추가한다.") @SwaggerApiSuccess(implementation = ResponseCustom.class) @ApiResponses(value = { - @ApiResponse(responseCode = "403", description = "냉장고의 멤버가 아닙니다.", + @ApiResponse(responseCode = "400", description = "(F0000)존재하지 않는 카테고리입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "(U0005)해당 유저를 찾을 수 없습니다.\t\n" + - "요청한 id를 가진 냉장고를 찾을 수 없습니다.\t\n" + - "(C0000)장바구니를 찾을 수 없습니다.\t\n" + - "(F0000)존재하지 않는 카테고리입니다.", + @ApiResponse(responseCode = "403", description = "(G0001)권한이 없습니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.\t\n" + + "(R0000)존재하지 않는 냉장고입니다.\t\n" + + "(C0000)존재하지 않는 장바구니입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @@ -71,12 +72,13 @@ public ResponseCustom addCartFoods(@Parameter(name = "냉장고 ID") @PathVar @Operation(summary = "장바구니 식품 삭제", description = "장바구니의 식품을 삭제한다.") @SwaggerApiSuccess(implementation = ResponseCustom.class) @ApiResponses(value = { - @ApiResponse(responseCode = "403", description = "냉장고의 멤버가 아닙니다.", + @ApiResponse(responseCode = "400", description = "(F0000)존재하지 않는 카테고리입니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + @ApiResponse(responseCode = "403", description = "(G0001)권한이 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "(U0005)해당 유저를 찾을 수 없습니다.\t\n" + - "요청한 id를 가진 냉장고를 찾을 수 없습니다.\t\n" + - "(C0000)장바구니를 찾을 수 없습니다.\t\n" + - "(F0000)존재하지 않는 카테고리입니다.", + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.\t\n" + + "(R0000)존재하지 않는 냉장고입니다.\t\n" + + "(C0000)존재하지 않는 장바구니입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth diff --git a/src/main/java/com/example/icebutler_server/cart/service/CartServiceImpl.java b/src/main/java/com/example/icebutler_server/cart/service/CartServiceImpl.java index ea641622..92619b2a 100644 --- a/src/main/java/com/example/icebutler_server/cart/service/CartServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/cart/service/CartServiceImpl.java @@ -50,7 +50,7 @@ public List getCartFoods(Long fridgeId, Long userId) { for (FoodCategory category : FoodCategory.values()) { List cartFoods = cartFoodRepository.findByCartAndFood_FoodCategoryAndIsEnableOrderByCreatedAt(cart, category, true); // 카테고리별 음식이 있는 경우만 응답 - if(cartFoods.isEmpty()) continue; + if (cartFoods.isEmpty()) continue; CartResponse cartResponse = CartResponse.toDto(cartFoods, category); cartResponses.add(cartResponse); } @@ -66,9 +66,9 @@ public void addCartFoods(Long cartId, AddFoodToCartRequest request, Long userId) Cart cart = getCart(userId, cartId); // food 없는 경우 food 생성 List foodRequests = new ArrayList<>(); - for(AddFoodRequest foodRequest : request.getFoodRequests()) { + for (AddFoodRequest foodRequest : request.getFoodRequests()) { Food food = this.foodRepository.findByFoodNameAndFoodCategory(foodRequest.getFoodName(), FoodCategory.getFoodCategoryByName(foodRequest.getFoodCategory())); - if(food == null) { + if (food == null) { food = this.foodRepository.save(Food.toEntity(foodRequest)); amazonSQSSender.sendMessage(FoodData.toDto(food)); } @@ -81,7 +81,7 @@ public void addCartFoods(Long cartId, AddFoodToCartRequest request, Long userId) .collect(Collectors.toList()); List cartFoods = foodRequests.stream() .filter((f) -> { - for (Long foodInId : foodsInNowCart) if(foodInId.equals(f.getId())) return false; + for (Long foodInId : foodsInNowCart) if (foodInId.equals(f.getId())) return false; return true; }) .map((food) -> CartFood.toEntity(cart, food)) @@ -102,7 +102,7 @@ public void deleteCartFoods(Long cartId, RemoveFoodFromCartRequest request, Long private Cart getCart(Long userId, Long fridgeId) { User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); - fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); + fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NO_PERMISSION)); return cartRepository.findByFridge_IdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_CART)); } } diff --git a/src/main/java/com/example/icebutler_server/food/controller/FoodController.java b/src/main/java/com/example/icebutler_server/food/controller/FoodController.java index 1fbfac09..47b80235 100644 --- a/src/main/java/com/example/icebutler_server/food/controller/FoodController.java +++ b/src/main/java/com/example/icebutler_server/food/controller/FoodController.java @@ -40,20 +40,21 @@ public class FoodController { @Operation(summary = "식품 검색", description = "식품을 검색한다.") @SwaggerApiSuccess(implementation = FoodRes.class) - @ApiResponse(responseCode = "404", description = "(F0000)존재하지 않는 카테고리입니다.", + @ApiResponse(responseCode = "400", description = "(F0000)존재하지 않는 카테고리입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))) @GetMapping("") public ResponseCustom> searchFood(@Parameter(name = "category", description = "식품 카테고리") @RequestParam(required = false) String category, - @Parameter(name = "word", description = "검색어")@RequestParam(required = false) String word) { - if(category != null && word != null) return ResponseCustom.success(foodService.getAllFoodByCategoryAndWord(category, word)); - else if(category != null) return ResponseCustom.success(foodService.getAllFoodByCategory(category)); - else if(word != null) return ResponseCustom.success(foodService.getAllFoodByWord(word)); + @Parameter(name = "word", description = "검색어") @RequestParam(required = false) String word) { + if (category != null && word != null) + return ResponseCustom.success(foodService.getAllFoodByCategoryAndWord(category, word)); + else if (category != null) return ResponseCustom.success(foodService.getAllFoodByCategory(category)); + else if (word != null) return ResponseCustom.success(foodService.getAllFoodByWord(word)); else return ResponseCustom.success(foodService.getAllFood()); } @Operation(summary = "식품 바코드 조회", description = "바코드 번호로 식품을 조회한다.") @SwaggerApiSuccess(implementation = BarcodeFoodRes.class) - @ApiResponse(responseCode = "404", description = "(F00001)해당 바코드의 상품을 찾을 수 없습니다.", + @ApiResponse(responseCode = "404", description = "(F0001)해당 바코드의 상품을 찾을 수 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))) @GetMapping("/barcode") public ResponseCustom searchByBarcode(@RequestParam String code_num) throws IOException, org.json.simple.parser.ParseException { diff --git a/src/main/java/com/example/icebutler_server/fridge/controller/FridgeController.java b/src/main/java/com/example/icebutler_server/fridge/controller/FridgeController.java index 3cbe2ccb..754ee9e6 100644 --- a/src/main/java/com/example/icebutler_server/fridge/controller/FridgeController.java +++ b/src/main/java/com/example/icebutler_server/fridge/controller/FridgeController.java @@ -38,10 +38,9 @@ public ResponseCustom healthCheck() { @Operation(summary = "냉장고 추가", description = "냉장고를 추가한다.") @SwaggerApiSuccess(implementation = ResponseCustom.class) @ApiResponses(value = { - @ApiResponse(responseCode = "400", description = "냉장고 이름를 입력하지 않았습니다.\t\n" + - "존재하지 않는 냉장고 유형입니다.", + @ApiResponse(responseCode = "400", description = "(G0000)잘못된 파라미터입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "요청한 id를 가진 유저를 찾을 수 없습니다.", + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @@ -51,18 +50,21 @@ public ResponseCustom registerFridge(@RequestBody FridgeRegisterReq fridge return ResponseCustom.success(fridgeService.registerFridge(fridgeRegisterReq, loginStatus.getUserId())); } - @Operation(summary = "냉장고 수정", description = "냉장고를 수정한다.") + @Operation(summary = "냉장고 정보 수정", description = "냉장고 정보를 수정한다.") @SwaggerApiSuccess(implementation = ResponseCustom.class) @ApiResponses(value = { - @ApiResponse(responseCode = "400", description = "냉장고 이름를 입력하지 않았습니다.\t\n" + - "존재하지 않는 냉장고 유형입니다.", + @ApiResponse(responseCode = "400", description = "(G0000)잘못된 파라미터입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "요청한 id를 가진 유저를 찾을 수 없습니다.", + @ApiResponse(responseCode = "403", description = "(G0001)권한이 없습니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.\t\n" + + "(R0000)존재하지 않는 냉장고입니다.\t\n" + + "(R0003)해당 냉장고에 존재하지 않는 사용자입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @PatchMapping("/{fridgeId}") - public ResponseCustom modifyFridge(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, + public ResponseCustom modifyFridge(@Parameter(description = "냉장고 ID") @PathVariable Long fridgeId, @RequestBody FridgeModifyReq fridgeModifyReq, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { fridgeService.modifyFridge(fridgeId, fridgeModifyReq, loginStatus.getUserId()); @@ -72,17 +74,19 @@ public ResponseCustom modifyFridge(@Parameter(name = "냉장고 ID") @PathVar @Operation(summary = "냉장고 삭제", description = "냉장고를 삭제한다.") @SwaggerApiSuccess(implementation = ResponseCustom.class) @ApiResponses(value = { - @ApiResponse(responseCode = "403", description = "냉장고의 멤버가 아닙니다.\t\n" + - "올바르지 않은 접근 권한입니다.\t\n" + - "올바르지 않은 냉장고 삭제 조건입니다.", + @ApiResponse(responseCode = "400", description = "(G0000)잘못된 파라미터입니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + @ApiResponse(responseCode = "403", description = "(G0001)권한이 없습니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.\t\n" + + "(R0000)존재하지 않는 냉장고입니다.\t\n", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "요청한 id를 가진 유저를 찾을 수 없습니다.\t\n" + - "요청한 id를 가진 냉장고를 찾을 수 없습니다.", + @ApiResponse(responseCode = "409", description = "(R0001)해당 냉장고에 사용자가 존재합니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @PatchMapping("/{fridgeId}/remove") - public ResponseCustom removeFridge(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, + public ResponseCustom removeFridge(@Parameter(description = "냉장고 ID") @PathVariable Long fridgeId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { return ResponseCustom.success(fridgeService.removeFridge(fridgeId, loginStatus.getUserId())); } @@ -90,34 +94,34 @@ public ResponseCustom removeFridge(@Parameter(name = "냉장고 ID") @Path @Operation(summary = "냉장고 사용자 삭제", description = "냉장고 사용자를 삭제한다.") @SwaggerApiSuccess(implementation = ResponseCustom.class) @ApiResponses(value = { - @ApiResponse(responseCode = "403", description = "냉장고의 멤버가 아닙니다.\t\n" + - "올바르지 않은 접근 권한입니다.", + @ApiResponse(responseCode = "403", description = "(G0001)권한이 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "요청한 id를 가진 유저를 찾을 수 없습니다.\t\n" + - "요청한 id를 가진 냉장고를 찾을 수 없습니다.", + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.\t\n" + + "(R0000)존재하지 않는 냉장고입니다.\t\n" + + "(R0003)해당 냉장고에 존재하지 않는 사용자입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @PatchMapping("/{fridgeId}/remove/each") - public ResponseCustom removeFridgeUser(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, + public ResponseCustom removeFridgeUser(@Parameter(description = "냉장고 ID") @PathVariable Long fridgeId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { return ResponseCustom.success(fridgeService.removeFridgeUser(fridgeId, loginStatus.getUserId())); } - @Operation(summary = "냉장고 식품 전체 조회(카테고리별)", description = "냉장고 내 식품을 전체조회한다.") + @Operation(summary = "냉장고 식품 전체 조회(카테고리별)", description = "냉장고 내 식품을 카테고리 별로 전체조회한다.") @SwaggerApiSuccess(implementation = FridgeMainRes.class) @ApiResponses(value = { - @ApiResponse(responseCode = "400", description = "존재하지 않는 카테고리입니다.", + @ApiResponse(responseCode = "400", description = "(F0000)존재하지 않는 카테고리입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "요청한 id를 가진 유저를 찾을 수 없습니다.\t\n" + - "요청한 id를 가진 냉장고를 찾을 수 없습니다.", + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.\t\n" + + "(R0000)존재하지 않는 냉장고입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @GetMapping("/{fridgeId}/foods") - public ResponseCustom getFoods(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, - @Parameter(hidden = true) @IsLogin LoginStatus loginStatus, - @Parameter(name = "식품 카테고리") @RequestParam(required = false) String category) { + public ResponseCustom getFoods(@Parameter(description = "냉장고 ID") @PathVariable Long fridgeId, + @Parameter(description = "식품 카테고리") @RequestParam(required = false) String category, + @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { return ResponseCustom.success(fridgeService.getFoods(fridgeId, loginStatus.getUserId(), category)); } @@ -125,13 +129,13 @@ public ResponseCustom getFoods(@Parameter(name = "냉장고 ID") @Operation(summary = "냉장고 식품 검색 조회", description = "냉장고 내 식품을 검색한다.") @SwaggerApiSuccess(implementation = FridgeFoodsRes.class) @ApiResponses(value = { - @ApiResponse(responseCode = "404", description = "요청한 id를 가진 냉장고를 찾을 수 없습니다.", + @ApiResponse(responseCode = "404", description = "(R0000)존재하지 않는 냉장고입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @GetMapping("/{fridgeId}/search") - public ResponseCustom> searchFridgeFood(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, - @Parameter(name = "식품명") @RequestParam String keyword, + public ResponseCustom> searchFridgeFood(@Parameter(description = "냉장고 ID") @PathVariable Long fridgeId, + @Parameter(description = "식품명") @RequestParam String keyword, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { return ResponseCustom.success(fridgeService.searchFridgeFood(fridgeId, loginStatus.getUserId(), keyword)); } @@ -139,17 +143,17 @@ public ResponseCustom> searchFridgeFood(@Parameter(name = " @Operation(summary = "냉장고 식품 상세 조회", description = "냉장고 내 식품을 상세 조회한다.") @SwaggerApiSuccess(implementation = FridgeFoodsRes.class) @ApiResponses(value = { - @ApiResponse(responseCode = "403", description = "냉장고의 멤버가 아닙니다.", + @ApiResponse(responseCode = "403", description = "(G0001)권한이 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "요청한 id를 가진 유저를 찾을 수 없습니다.\t\n" + - "요청한 id를 가진 냉장고를 찾을 수 없습니다.\t\n" + - "요청한 id를 가진 냉장고 내 식품을 찾을 수 없습니다.", + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.\t\n" + + "(R0000)존재하지 않는 냉장고입니다.\t\n" + + "(R0002)해당 냉장고에 존재하지 않는 식품입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @GetMapping("/{fridgeId}/foods/{fridgeFoodId}") - public ResponseCustom getFridgeFood(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, - @Parameter(name = "냉장고 내 식품 ID") @PathVariable Long fridgeFoodId, + public ResponseCustom getFridgeFood(@Parameter(description = "냉장고 ID") @PathVariable Long fridgeId, + @Parameter(description = "냉장고 내 식품 ID") @PathVariable Long fridgeFoodId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { return ResponseCustom.success(fridgeService.getFridgeFood(fridgeId, fridgeFoodId, loginStatus.getUserId())); } @@ -157,18 +161,19 @@ public ResponseCustom getFridgeFood(@Parameter(name = "냉장고 @Operation(summary = "냉장고 식품 추가", description = "냉장고 내 식품을 추가한다.") @SwaggerApiSuccess(implementation = ResponseCustom.class) @ApiResponses(value = { - @ApiResponse(responseCode = "400", description = "존재하지 않는 카테고리입니다.", + @ApiResponse(responseCode = "400", description = "(F0000)존재하지 않는 카테고리입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "403", description = "냉장고의 멤버가 아닙니다.", + @ApiResponse(responseCode = "403", description = "(G0001)권한이 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "요청한 id를 가진 유저를 찾을 수 없습니다.\t\n" + - "요청한 id를 가진 냉장고를 찾을 수 없습니다.", + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.\t\n" + + "(R0000)존재하지 않는 냉장고입니다.\t\n" + + "(R0003)해당 냉장고에 존재하지 않는 사용자입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @PostMapping("/{fridgeId}/food") public ResponseCustom addFridgeFood(@RequestBody FridgeFoodsReq fridgeFoodsReq, - @Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, + @Parameter(description = "냉장고 ID") @PathVariable Long fridgeId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { fridgeService.addFridgeFood(fridgeFoodsReq, fridgeId, loginStatus.getUserId()); return ResponseCustom.success(); @@ -177,20 +182,21 @@ public ResponseCustom addFridgeFood(@RequestBody FridgeFoodsReq fridgeFoodsRe @Operation(summary = "냉장고 식품 수정", description = "냉장고 내 식품을 수정한다.") @SwaggerApiSuccess(implementation = ResponseCustom.class) @ApiResponses(value = { - @ApiResponse(responseCode = "400", description = "존재하지 않는 카테고리입니다.", + @ApiResponse(responseCode = "400", description = "(F0000)존재하지 않는 카테고리입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "403", description = "냉장고의 멤버가 아닙니다.", + @ApiResponse(responseCode = "403", description = "(G0001)권한이 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "요청한 id를 가진 유저를 찾을 수 없습니다.\t\n" + - "요청한 id를 가진 냉장고를 찾을 수 없습니다.\t\n" + - "요청한 id를 가진 냉장고 내 식품을 찾을 수 없습니다.", + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.\t\n" + + "(R0000)존재하지 않는 냉장고입니다.\t\n" + + "(R0002)해당 냉장고에 존재하지 않는 식품입니다.\t\n" + + "(R0003)해당 냉장고에 존재하지 않는 사용자입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @PatchMapping("/{fridgeId}/foods/{fridgeFoodId}") public ResponseCustom modifyFridgeFood(@RequestBody FridgeFoodReq fridgeFoodReq, - @Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, - @Parameter(name = "냉장고 내 식품 ID") @PathVariable Long fridgeFoodId, + @Parameter(description = "냉장고 ID") @PathVariable Long fridgeId, + @Parameter(description = "냉장고 내 식품 ID") @PathVariable Long fridgeFoodId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { fridgeService.modifyFridgeFood(fridgeId, fridgeFoodId, fridgeFoodReq, loginStatus.getUserId()); return ResponseCustom.success(); @@ -199,20 +205,20 @@ public ResponseCustom modifyFridgeFood(@RequestBody FridgeFoodReq fridgeFoodR @Operation(summary = "냉장고 식품 삭제", description = "냉장고 내 식품을 삭제한다.") @SwaggerApiSuccess(implementation = ResponseCustom.class) @ApiResponses(value = { - @ApiResponse(responseCode = "400", description = "존재하지 않는 식품삭제 타입입니다.", + @ApiResponse(responseCode = "400", description = "(F0003)존재하지 않는 식품삭제 타입입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "403", description = "냉장고의 멤버가 아닙니다.", + @ApiResponse(responseCode = "403", description = "(G0001)권한이 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "요청한 id를 가진 유저를 찾을 수 없습니다.\t\n" + - "요청한 id를 가진 냉장고를 찾을 수 없습니다.\t\n" + - "요청한 id를 가진 냉장고 내 식품을 찾을 수 없습니다.", + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.\t\n" + + "(R0000)존재하지 않는 냉장고입니다.\t\n" + + "(R0002)해당 냉장고에 존재하지 않는 식품입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @DeleteMapping("/{fridgeId}/foods") public ResponseCustom deleteFridgeFood(@RequestBody DeleteFridgeFoodsReq deleteFridgeFoodsReq, - @Parameter(name = "삭제 타입(폐기/섭취)") @RequestParam String type, - @Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, + @Parameter(description = "삭제 타입(폐기/섭취)") @RequestParam String type, + @Parameter(description = "냉장고 ID") @PathVariable Long fridgeId, @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { fridgeService.deleteFridgeFood(deleteFridgeFoodsReq, type, fridgeId, loginStatus.getUserId()); return ResponseCustom.success(); @@ -221,22 +227,21 @@ public ResponseCustom deleteFridgeFood(@RequestBody DeleteFridgeFoodsReq dele @Operation(summary = "냉장고 멤버 조회", description = "냉장고의 멤버를 조회한다.") @SwaggerApiSuccess(implementation = FridgeUserMainRes.class) @ApiResponses(value = { - @ApiResponse(responseCode = "404", description = "요청한 id를 가진 냉장고를 찾을 수 없습니다.", + @ApiResponse(responseCode = "404", description = "(R0000)존재하지 않는 냉장고입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @GetMapping("{fridgeId}/members") public ResponseCustom getMembers( - @Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, - @Parameter(hidden = true) @IsLogin LoginStatus loginStatus - ) { + @Parameter(description = "냉장고 ID") @PathVariable Long fridgeId, + @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { return ResponseCustom.success(fridgeService.searchMembers(fridgeId, loginStatus.getUserId())); } @Operation(summary = "냉장고 선택목록 조회", description = "냉장고 선택목록을 조회한다.") @SwaggerApiSuccess(implementation = SelectFridgesMainRes.class) @ApiResponses(value = { - @ApiResponse(responseCode = "404", description = "요청한 id를 가진 유저를 찾을 수 없습니다.", + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @@ -250,7 +255,8 @@ public ResponseCustom selectFridges( @Operation(summary = "냉장고 목록 조회", description = "냉장고 목록을 조회한다.") @SwaggerApiSuccess(implementation = GetFridgesMainRes.class) @ApiResponses(value = { - @ApiResponse(responseCode = "404", description = "요청한 id를 가진 유저를 찾을 수 없습니다.", + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.\t\n" + + "(R0000)존재하지 않는 냉장고입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), }) @Auth @@ -262,13 +268,25 @@ public ResponseCustom myFridge(@Parameter(hidden = true) @IsL /** * [Get] 냉장고 통계 (낭비/소비) */ + @Operation(summary = "냉장고 식품 삭제 통계 조회", description = "냉장고 식품의 삭제 타입별 통계를 조회한다.") + @SwaggerApiSuccess(implementation = GetFridgesMainRes.class) + @ApiResponses(value = { + @ApiResponse(responseCode = "400", description = "(F0003)존재하지 않는 식품삭제 타입입니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + @ApiResponse(responseCode = "403", description = "(G0001)권한이 없습니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.\t\n" + + "(R0000)존재하지 않는 냉장고입니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + }) @Auth @GetMapping("/{fridgeId}/statistics") - public ResponseCustom getFridgeFoodStatistics(@Parameter(name = "냉장고 ID") @PathVariable Long fridgeId, - @Parameter(name = "통계 타입(낭비/소비)") @RequestParam String deleteCategory, - @Parameter(name = "연도") @RequestParam Integer year, - @Parameter(name = "월") @RequestParam Integer month, - @Parameter(hidden = true) @IsLogin LoginStatus status) { + public ResponseCustom getFridgeFoodStatistics( + @Parameter(description = "냉장고 ID") @PathVariable Long fridgeId, + @Parameter(description = "통계 타입(낭비/소비)") @RequestParam String deleteCategory, + @Parameter(description = "연도") @RequestParam Integer year, + @Parameter(description = "월") @RequestParam Integer month, + @Parameter(hidden = true) @IsLogin LoginStatus status) { return ResponseCustom.success(fridgeService.getFridgeFoodStatistics(fridgeId, deleteCategory, status.getUserId(), year, month)); } @@ -284,7 +302,7 @@ public void notifyFridgeFood() { /** * [Get] 사용자가 속한 냉장고 food list */ - // todo: 토큰 추가하기 + // todo: 토큰 추가하기, 어디에 쓰이는지? @GetMapping("/food-lists") public ResponseCustom getFridgeUserFoodList(@RequestParam(required = false) Long fridgeId, @RequestParam Long userId) { diff --git a/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java b/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java index 49549b0b..d8ef14db 100644 --- a/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/fridge/service/FridgeServiceImpl.java @@ -160,7 +160,7 @@ private UpdateMembersRes toUpdateFridgeMembers(List newMembers, List newMembers, List new BaseException(NOT_FOUND_USER)); Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); - FridgeUser owner = (FridgeUser) fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); + FridgeUser owner = (FridgeUser) fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NO_PERMISSION)); List fridgeUsers = fridgeUserRepository.findByFridgeAndIsEnable(fridge, true); List fridgeFoods = fridgeFoodRepository.findByFridgeAndIsEnableOrderByShelfLife(fridge, true); if (owner.getRole() != FridgeRole.OWNER) throw new BaseException(NO_PERMISSION); - if(fridgeUsers.size() > 1) throw new BaseException(STILL_MEMBER_EXIST); + if (fridgeUsers.size() > 1) throw new BaseException(STILL_MEMBER_EXIST); fridgeUsers.forEach(FridgeUser::remove); // fridgeFoods.forEach(FridgeFood::remove); @@ -228,7 +228,7 @@ public List searchFridgeFood(Long fridgeId, Long ownerId, String public FridgeFoodRes getFridgeFood(Long fridgeId, Long fridgeFoodId, Long userId) { User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); - fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); + fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NO_PERMISSION)); FridgeFood fridgeFood = fridgeFoodRepository.findByIdAndFridgeAndIsEnable(fridgeFoodId, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_FOOD)); return FridgeFoodRes.toDto(fridgeFood); @@ -239,7 +239,7 @@ public FridgeFoodRes getFridgeFood(Long fridgeId, Long fridgeFoodId, Long userId public void addFridgeFood(FridgeFoodsReq fridgeFoodsReq, Long fridgeId, Long userId) { User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); Fridge fridge = fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); - fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); + fridgeUserRepository.findByUserAndFridgeAndIsEnable(user, fridge, true).orElseThrow(() -> new BaseException(NO_PERMISSION)); List fridgeFoods = new ArrayList<>(); for (FridgeFoodReq fridgeFoodReq : fridgeFoodsReq.getFridgeFoods()) { @@ -268,7 +268,7 @@ public void modifyFridgeFood(Long fridgeId, Long fridgeFoodId, FridgeFoodReq fri Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeId, true) .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, user, true) - .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); + .orElseThrow(() -> new BaseException(NO_PERMISSION)); FridgeFood modifyFridgeFood = this.fridgeFoodRepository.findByIdAndFridgeAndIsEnable(fridgeFoodId, fridge, true) .orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_FOOD)); @@ -332,7 +332,7 @@ public FridgeUserMainRes searchMembers(Long fridgeId, Long userId) { public FridgeFoodsStatistics getFridgeFoodStatistics(Long fridgeId, String deleteCategory, Long userId, Integer year, Integer month) { User user = this.userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); Fridge fridge = this.fridgeRepository.findByIdAndIsEnable(fridgeId, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE)); - this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, user, true).orElseThrow(() -> new BaseException(NOT_FOUND_FRIDGE_USER)); + this.fridgeUserRepository.findByFridgeAndUserAndIsEnable(fridge, user, true).orElseThrow(() -> new BaseException(NO_PERMISSION)); Map deleteStatusList = new HashMap<>(); @@ -346,13 +346,13 @@ public FridgeFoodsStatistics getFridgeFoodStatistics(Long fridgeId, String delet private FridgeFoodsStatistics toFoodStatisticsByDeleteStatus(Map deleteStatusList) { int sum = 0; - for(Long value : deleteStatusList.values()){ + for (Long value : deleteStatusList.values()) { sum += value.intValue(); } List foodStatisticsList = new ArrayList<>(); - for(Map.Entry deleteStatus: deleteStatusList.entrySet()){ - foodStatisticsList.add(new FridgeFoodStatistics(deleteStatus.getKey().getName(), AwsS3ImageUrlUtil.toUrl(deleteStatus.getKey().getImage()) , FridgeUtils.calPercentage(deleteStatus.getValue().intValue(), sum), deleteStatus.getValue().intValue())); + for (Map.Entry deleteStatus : deleteStatusList.entrySet()) { + foodStatisticsList.add(new FridgeFoodStatistics(deleteStatus.getKey().getName(), AwsS3ImageUrlUtil.toUrl(deleteStatus.getKey().getImage()), FridgeUtils.calPercentage(deleteStatus.getValue().intValue(), sum), deleteStatus.getValue().intValue())); } // sorting foodStatisticsList.sort((fs1, fs2) -> (fs2.getCount() - fs1.getCount())); diff --git a/src/main/java/com/example/icebutler_server/user/controller/UserAuthController.java b/src/main/java/com/example/icebutler_server/user/controller/UserAuthController.java index 1403b961..1f3cd83e 100644 --- a/src/main/java/com/example/icebutler_server/user/controller/UserAuthController.java +++ b/src/main/java/com/example/icebutler_server/user/controller/UserAuthController.java @@ -24,7 +24,6 @@ import org.springframework.data.web.PageableDefault; import org.springframework.web.bind.annotation.*; - @RequiredArgsConstructor @RequestMapping(value = "/users") @RestController @@ -32,82 +31,91 @@ @SecurityRequirement(name = "Bearer") public class UserAuthController { - private final TokenUtils tokenUtils; - private final UserService userService; + private final TokenUtils tokenUtils; + private final UserService userService; - @Operation(summary = "토큰 재발급", description = "만료된 토큰을 재발급한다.") - @SwaggerApiSuccess(implementation = String.class) - @Auth - @GetMapping("/renew") - public ResponseCustom accessToken(@Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - return ResponseCustom.success(tokenUtils.accessExpiration(loginStatus.getUserId())); - } + @Operation(summary = "토큰 재발급", description = "만료된 토큰을 재발급한다.") + @SwaggerApiSuccess(implementation = String.class) + @ApiResponses(value = { + @ApiResponse(responseCode = "404", description = "(A0000)만료된 토큰입니다. 다시 발급해주세요.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))) + }) + @Auth + @GetMapping("/renew") + public ResponseCustom accessToken(@Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { + return ResponseCustom.success(tokenUtils.accessExpiration(loginStatus.getUserId())); + } - @Operation(summary = "유저 프로필 수정", description = "유저 프로필을 수정한다.") - @SwaggerApiSuccess(implementation = ResponseCustom.class) - @ApiResponses(value = { - @ApiResponse(responseCode = "404", description = "(U0005)해당 유저를 찾을 수 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))) - }) - @Auth - @ResponseBody - @PatchMapping("/profile") - public ResponseCustom modifyProfile(@RequestBody PatchProfileReq patchProfileReq, - @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - userService.modifyProfile(loginStatus.getUserId(), patchProfileReq); - return ResponseCustom.success(); - } + @Operation(summary = "유저 프로필 수정", description = "유저 프로필을 수정한다.") + @SwaggerApiSuccess(implementation = ResponseCustom.class) + @ApiResponses(value = { + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))) + }) + @Auth + @ResponseBody + @PatchMapping("/profile") + public ResponseCustom modifyProfile(@RequestBody PatchProfileReq patchProfileReq, + @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { + userService.modifyProfile(loginStatus.getUserId(), patchProfileReq); + return ResponseCustom.success(); + } - @Operation(summary = "유저 탈퇴", description = "유저를 탈퇴한다.") - @SwaggerApiSuccess(implementation = ResponseCustom.class) - @ApiResponses(value = { - @ApiResponse(responseCode = "400", description = "해당 냉장고에 멤버가 있어서 삭제할 수 없습니다.", - content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "(U0005)해당 유저를 찾을 수 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))) - }) - @Auth - @DeleteMapping("/delete") - public ResponseCustom deleteUser( - @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - userService.deleteUser(loginStatus.getUserId()); - return ResponseCustom.success(); - } + @Operation(summary = "유저 탈퇴", description = "유저를 탈퇴한다.") + @SwaggerApiSuccess(implementation = ResponseCustom.class) + @ApiResponses(value = { + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + @ApiResponse(responseCode = "409", description = "(R0001)해당 냉장고에 사용자가 존재합니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + }) + @Auth + @DeleteMapping("/delete") + public ResponseCustom deleteUser( + @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { + userService.deleteUser(loginStatus.getUserId()); + return ResponseCustom.success(); + } - @Operation(summary = "유저 로그아웃", description = "유저를 로그아웃한다.") - @SwaggerApiSuccess(implementation = ResponseCustom.class) - @ApiResponses(value = { - @ApiResponse(responseCode = "404", description = "(U0005)해당 유저를 찾을 수 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - }) - @Auth - @PostMapping("/logout") - public ResponseCustom logout( - @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - userService.logout(loginStatus.getUserId()); - return ResponseCustom.success(); - } + @Operation(summary = "유저 로그아웃", description = "유저를 로그아웃한다.") + @SwaggerApiSuccess(implementation = ResponseCustom.class) + @ApiResponses(value = { + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + }) + @Auth + @PostMapping("/logout") + public ResponseCustom logout( + @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { + userService.logout(loginStatus.getUserId()); + return ResponseCustom.success(); + } - @Operation(summary = "유저 프로필 조회", description = "유저 프로필을 조회한다.") - @SwaggerApiSuccess(implementation = MyProfileRes.class) - @ApiResponses(value = { - @ApiResponse(responseCode = "404", description = "(U0005)해당 유저를 찾을 수 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))) - }) - @Auth - @GetMapping("") - public ResponseCustom profile( - @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { - return ResponseCustom.success(userService.checkProfile(loginStatus.getUserId())); - } + @Operation(summary = "유저 프로필 조회", description = "유저 프로필을 조회한다.") + @SwaggerApiSuccess(implementation = MyProfileRes.class) + @ApiResponses(value = { + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))) + }) + @Auth + @GetMapping("") + public ResponseCustom profile( + @Parameter(hidden = true) @IsLogin LoginStatus loginStatus) { + return ResponseCustom.success(userService.checkProfile(loginStatus.getUserId())); + } - @Operation(summary = "유저 알림 목록", description = "유저 알림 목록을 조회한다.") - @SwaggerApiSuccess(implementation = MyNotificationRes.class) - @ApiResponses(value = { - @ApiResponse(responseCode = "404", description = "(U0005)해당 유저를 찾을 수 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - }) - @Auth - @GetMapping("/notification") - public ResponseCustom> getUserNotification( - @Parameter(hidden = true) @IsLogin LoginStatus loginStatus, - @PageableDefault(size = 10) Pageable pageable) { - return ResponseCustom.success(userService.getUserNotification(loginStatus.getUserId(), pageable)); - } + @Operation(summary = "유저 알림 목록", description = "유저 알림 목록을 조회한다.") + @SwaggerApiSuccess(implementation = MyNotificationRes.class) + @ApiResponses(value = { + @ApiResponse(responseCode = "404", description = "(U0000)존재하지 않는 사용자입니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + }) + @Auth + @GetMapping("/notification") + public ResponseCustom> getUserNotification( + @Parameter(hidden = true) @IsLogin LoginStatus loginStatus, + @PageableDefault(size = 10) Pageable pageable) { + return ResponseCustom.success(userService.getUserNotification(loginStatus.getUserId(), pageable)); + } } diff --git a/src/main/java/com/example/icebutler_server/user/controller/UserController.java b/src/main/java/com/example/icebutler_server/user/controller/UserController.java index 311ae4dc..142e39e4 100644 --- a/src/main/java/com/example/icebutler_server/user/controller/UserController.java +++ b/src/main/java/com/example/icebutler_server/user/controller/UserController.java @@ -27,51 +27,56 @@ @Tag(name = "User", description = "유저 API (인증 불필요)") public class UserController { - private final UserService userService; + private final UserService userService; - @Operation(summary = "유저 회원가입", description = "유저가 회원가입한다.") - @SwaggerApiSuccess(implementation = PostUserRes.class) - @ApiResponses(value = { - @ApiResponse(responseCode = "400", description = "(U0000)부적절한 소셜로그인 provider 입력입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "401", description = "(U0001)관리자에 의해 서비스 이용이 제한되었습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "(U0002)사용자 이메일 값을 찾아올 수 없습니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))) - }) - @ResponseBody - @PostMapping("/join") - public ResponseCustom join(@RequestBody PostUserReq postUserReq) { - return ResponseCustom.success(userService.join(postUserReq)); - } + @Operation(summary = "유저 회원가입", description = "유저가 회원가입한다.") + @SwaggerApiSuccess(implementation = PostUserRes.class) + @ApiResponses(value = { + @ApiResponse(responseCode = "400", description = "(U0003)부적절한 소셜로그인 provider 입력입니다.\t\n" + + "(G0000)잘못된 파라미터입니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + @ApiResponse(responseCode = "403", description = "(U0002)관리자에 의해 서비스 이용이 제한되었습니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + }) + @ResponseBody + @PostMapping("/join") + public ResponseCustom join(@RequestBody PostUserReq postUserReq) { + return ResponseCustom.success(userService.join(postUserReq)); + } - @Operation(summary = "유저 로그인", description = "유저가 로그인한다.") - @SwaggerApiSuccess(implementation = PostUserRes.class) - @ApiResponses(value = { - @ApiResponse(responseCode = "400", description = "(U0000)부적절한 소셜로그인 provider 입력입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))), - @ApiResponse(responseCode = "404", description = "(U0002)사용자 이메일 값을 찾아올 수 없습니다." + - "(U0003)이미 탈퇴한 회원입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))) - }) - @ResponseBody - @PostMapping("/login") - public ResponseCustom login(@RequestBody LoginUserReq loginUserReq) { - return ResponseCustom.success(userService.login(loginUserReq)); - } + @Operation(summary = "유저 로그인", description = "유저가 로그인한다.") + @SwaggerApiSuccess(implementation = PostUserRes.class) + @ApiResponses(value = { + @ApiResponse(responseCode = "400", description = "(U0003)부적절한 소셜로그인 provider 입력입니다.\t\n" + + "(G0000)잘못된 파라미터입니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + @ApiResponse(responseCode = "404", description = "(U0001)이미 탈퇴한 회원입니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))), + }) + @ResponseBody + @PostMapping("/login") + public ResponseCustom login(@RequestBody LoginUserReq loginUserReq) { + return ResponseCustom.success(userService.login(loginUserReq)); + } - @Operation(summary = "유저 닉네임 중복 조회", description = "닉네임 중복 여부를 조회한다.") - @SwaggerApiSuccess(implementation = PostNickNameRes.class) - @ApiResponses(value = { - @ApiResponse(responseCode = "400", description = "(U0004)올바르지 않은 닉네임 형식입니다.", content = @Content(schema = @Schema(implementation = ResponseCustom.class))) - }) - @ResponseBody - @PostMapping("/nickname") - public ResponseCustom checkNickname(@RequestBody PostNicknameReq postNicknameReq) { - return ResponseCustom.success(userService.checkNickname(postNicknameReq)); - } + @Operation(summary = "유저 닉네임 중복 조회", description = "닉네임 중복 여부를 조회한다.") + @SwaggerApiSuccess(implementation = PostNickNameRes.class) + @ApiResponses(value = { + @ApiResponse(responseCode = "400", description = "(U0004)올바르지 않은 닉네임 형식입니다.", + content = @Content(schema = @Schema(implementation = ResponseCustom.class))) + }) + @ResponseBody + @PostMapping("/nickname") + public ResponseCustom checkNickname(@RequestBody PostNicknameReq postNicknameReq) { + return ResponseCustom.success(userService.checkNickname(postNicknameReq)); + } - @Operation(summary = "유저 닉네임 검색 조회", description = "닉네임으로 유저를 검색한다.") - @SwaggerApiSuccess(implementation = NickNameRes.class) - @GetMapping("/search") - public ResponseCustom> searchNickname( - @Parameter(name = "nickname", description = "닉네임") @RequestParam String nickname) { - return ResponseCustom.success(userService.searchNickname(nickname)); - } + @Operation(summary = "유저 닉네임 검색 조회", description = "닉네임으로 유저를 검색한다.") + @SwaggerApiSuccess(implementation = NickNameRes.class) + @GetMapping("/search") + public ResponseCustom> searchNickname( + @Parameter(name = "nickname", description = "닉네임") @RequestParam String nickname) { + return ResponseCustom.success(userService.searchNickname(nickname)); + } } diff --git a/src/main/java/com/example/icebutler_server/user/service/UserServiceImpl.java b/src/main/java/com/example/icebutler_server/user/service/UserServiceImpl.java index 3bc8cef7..c7195ab1 100644 --- a/src/main/java/com/example/icebutler_server/user/service/UserServiceImpl.java +++ b/src/main/java/com/example/icebutler_server/user/service/UserServiceImpl.java @@ -38,141 +38,144 @@ @RequiredArgsConstructor public class UserServiceImpl implements UserService { - private final UserRepository userRepository; - private final FridgeUserRepository fridgeUserRepository; - private final FridgeRepository fridgeRepository; - private final TokenUtils tokenUtils; - private final RedisUtils redisUtils; - - private final RecipeServerEventPublisherImpl recipeServerEventPublisher; - private final RedisTemplateService redisTemplateService; - private final PushNotificationRepository pushNotificationRepository; - // 소셜로그인 - @Transactional - public PostUserRes join(PostUserReq postUserReq) { - User user = checkUserInfo(postUserReq.getEmail(), postUserReq.getProvider()); - if (user == null) user = saveUser(postUserReq); - // 정지된 회원은 재가입 불가 - if (user.getIsDenied().equals(true)) throw new BaseException(BLOCKED_USER); - // 자진 탈퇴 회원은 재가입 처리 - if (user.getIsEnable().equals(false)) user=saveUser(postUserReq); // 새로운 행 추가 - - user.login(postUserReq.getFcmToken()); - this.recipeServerEventPublisher.addUser(user); - return PostUserRes.toDto(tokenUtils.createToken(user)); - } - - @Transactional - public PostUserRes login(LoginUserReq loginUserReq) { - User user = checkUserInfo(loginUserReq.getEmail(), loginUserReq.getProvider()); - - if (user != null) { - if (user.getIsEnable().equals(false)) throw new BaseException(ALREADY_WITHDRAWN_USER); - user.login(loginUserReq.getFcmToken()); - return PostUserRes.toDto(tokenUtils.createToken(user)); + private final UserRepository userRepository; + private final FridgeUserRepository fridgeUserRepository; + private final FridgeRepository fridgeRepository; + private final TokenUtils tokenUtils; + private final RedisUtils redisUtils; + + private final RecipeServerEventPublisherImpl recipeServerEventPublisher; + private final RedisTemplateService redisTemplateService; + private final PushNotificationRepository pushNotificationRepository; + + // 소셜로그인 + @Transactional + public PostUserRes join(PostUserReq postUserReq) { + User user = checkUserInfo(postUserReq.getEmail(), postUserReq.getProvider()); + if (user == null) user = saveUser(postUserReq); + // 정지된 회원은 재가입 불가 + if (user.getIsDenied().equals(true)) throw new BaseException(BLOCKED_USER); + // 자진 탈퇴 회원은 재가입 처리 + if (user.getIsEnable().equals(false)) user = saveUser(postUserReq); // 새로운 행 추가 + + user.login(postUserReq.getFcmToken()); + this.recipeServerEventPublisher.addUser(user); + return PostUserRes.toDto(tokenUtils.createToken(user)); } - return null; - } + @Transactional + public PostUserRes login(LoginUserReq loginUserReq) { + User user = checkUserInfo(loginUserReq.getEmail(), loginUserReq.getProvider()); + + if (user != null) { + if (user.getIsEnable().equals(false)) throw new BaseException(ALREADY_WITHDRAWN_USER); + user.login(loginUserReq.getFcmToken()); + return PostUserRes.toDto(tokenUtils.createToken(user)); + } + return null; + } - public User checkUserInfo(String email, String provider) { - if (Provider.getProviderByName(provider) == null) throw new BaseException(INVALID_PROVIDER); - if (!StringUtils.hasText(email)) throw new BaseException(INVALID_PARAM); - return userRepository.findByEmailAndProvider(email, Provider.getProviderByName(provider)); - } + public User checkUserInfo(String email, String provider) { + if (Provider.getProviderByName(provider) == null) throw new BaseException(INVALID_PROVIDER); + if (!StringUtils.hasText(email)) throw new BaseException(INVALID_PARAM); - @Transactional - public User saveUser(PostUserReq postUserReq) { - return userRepository.save(User.builder() - .provider(Provider.getProviderByName(postUserReq.getProvider())) - .email(postUserReq.getEmail()) - .nickname(postUserReq.getNickname()) - .profileImgKey(postUserReq.getProfileImgKey()) - .fcmToken(postUserReq.getFcmToken()) - .build()); - } + return userRepository.findByEmailAndProvider(email, Provider.getProviderByName(provider)); + } + + @Transactional + public User saveUser(PostUserReq postUserReq) { + return userRepository.save(User.builder() + .provider(Provider.getProviderByName(postUserReq.getProvider())) + .email(postUserReq.getEmail()) + .nickname(postUserReq.getNickname()) + .profileImgKey(postUserReq.getProfileImgKey()) + .fcmToken(postUserReq.getFcmToken()) + .build()); + } - // 프로필 설정 - @Transactional - public void modifyProfile(@IsLogin Long userId, PatchProfileReq patchProfileReq) { - User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + // 프로필 설정 + @Transactional + public void modifyProfile(@IsLogin Long userId, PatchProfileReq patchProfileReq) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - if (StringUtils.hasText(patchProfileReq.getNickname())) user.modifyProfileNickName(patchProfileReq.getNickname()); - if (StringUtils.hasText(patchProfileReq.getProfileImgKey())) user.modifyProfileImgKey(patchProfileReq.getProfileImgKey()); + if (StringUtils.hasText(patchProfileReq.getNickname())) + user.modifyProfileNickName(patchProfileReq.getNickname()); + if (StringUtils.hasText(patchProfileReq.getProfileImgKey())) + user.modifyProfileImgKey(patchProfileReq.getProfileImgKey()); // user.modifyProfileNickName(patchProfileReq.getNickname(), patchProfileReq.getProfileImgKey()); - recipeServerEventPublisher.changeUserProfile(user); - } - - // 닉네임 중복 확인 - public PostNickNameRes checkNickname(PostNicknameReq postNicknameReq) { - if (!isValidNickname(postNicknameReq.getNickname())) throw new BaseException(INVALID_NICKNAME); - Boolean existence = userRepository.existsByNickname(postNicknameReq.getNickname()); - - return PostNickNameRes.toDto(postNicknameReq.getNickname(), existence); - } - - private Boolean isValidNickname(String nickname) { - boolean err = false; - String regex = "^(?=.*[a-z0-9가-힣])[a-z0-9가-힣]{2,8}$"; - Pattern p = Pattern.compile(regex); - Matcher m = p.matcher(nickname); - if(m.matches()) { - err = true; + recipeServerEventPublisher.changeUserProfile(user); } - return err; - } - - //유저 탈퇴 - @Override - @Transactional - public void deleteUser(Long userId) { - User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - List fridgeOwners = fridgeUserRepository.findByUserAndRoleAndIsEnable(user, FridgeRole.OWNER, true); - for (FridgeUser fridgeOwner : fridgeOwners) { - Fridge fridge = fridgeOwner.getFridge(); - List fridgeMembers = fridgeUserRepository.findByFridgeAndRoleAndIsEnable(fridge, FridgeRole.MEMBER, true); - if (fridgeMembers.size() > 0) { - throw new BaseException(STILL_MEMBER_EXIST); - } - fridgeRepository.delete(fridge); + + // 닉네임 중복 확인 + public PostNickNameRes checkNickname(PostNicknameReq postNicknameReq) { + if (!isValidNickname(postNicknameReq.getNickname())) throw new BaseException(INVALID_NICKNAME); + Boolean existence = userRepository.existsByNickname(postNicknameReq.getNickname()); + + return PostNickNameRes.toDto(postNicknameReq.getNickname(), existence); } - user.deleteUser(); - redisTemplateService.deleteUserRefreshToken(userId.toString()); + + private Boolean isValidNickname(String nickname) { + boolean err = false; + String regex = "^(?=.*[a-z0-9가-힣])[a-z0-9가-힣]{2,8}$"; + Pattern p = Pattern.compile(regex); + Matcher m = p.matcher(nickname); + if (m.matches()) { + err = true; + } + return err; + } + + //유저 탈퇴 + @Override + @Transactional + public void deleteUser(Long userId) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + List fridgeOwners = fridgeUserRepository.findByUserAndRoleAndIsEnable(user, FridgeRole.OWNER, true); + for (FridgeUser fridgeOwner : fridgeOwners) { + Fridge fridge = fridgeOwner.getFridge(); + List fridgeMembers = fridgeUserRepository.findByFridgeAndRoleAndIsEnable(fridge, FridgeRole.MEMBER, true); + if (fridgeMembers.size() > 0) { + throw new BaseException(STILL_MEMBER_EXIST); + } + fridgeRepository.delete(fridge); + } + user.deleteUser(); + redisTemplateService.deleteUserRefreshToken(userId.toString()); // user.setIsEnable(false); - recipeServerEventPublisher.deleteUser(user); - } - - //유저 로그아웃 - @Override - @Transactional - public void logout(Long userId) { - User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - redisTemplateService.deleteUserRefreshToken(userId.toString()); - user.logout(); - } - - //마이페이지 조회 - @Override - public MyProfileRes checkProfile(Long userId) { - User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - - return MyProfileRes.toDto(user); - - } - - @Override - public List searchNickname(String nickname) { - return userRepository.findByNicknameContains(nickname) - .stream().map(NickNameRes::toDto).collect(Collectors.toList()); + recipeServerEventPublisher.deleteUser(user); + } + + //유저 로그아웃 + @Override + @Transactional + public void logout(Long userId) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + redisTemplateService.deleteUserRefreshToken(userId.toString()); + user.logout(); + } + + //마이페이지 조회 + @Override + public MyProfileRes checkProfile(Long userId) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + + return MyProfileRes.toDto(user); + + } + + @Override + public List searchNickname(String nickname) { + return userRepository.findByNicknameContains(nickname) + .stream().map(NickNameRes::toDto).collect(Collectors.toList()); // return NickNameRes.toDto(user.getNickname()); - } + } - @Override - public Page getUserNotification(Long userId, Pageable pageable) { - User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); - return MyNotificationRes.toUserNotificationList(this.pushNotificationRepository.findByUserOrderByCreatedAtDesc(user, pageable)); - } + @Override + public Page getUserNotification(Long userId, Pageable pageable) { + User user = userRepository.findByIdAndIsEnable(userId, true).orElseThrow(() -> new BaseException(NOT_FOUND_USER)); + return MyNotificationRes.toUserNotificationList(this.pushNotificationRepository.findByUserOrderByCreatedAtDesc(user, pageable)); + } } From 457ea939dbb9274f477deae42adb386f86e517c1 Mon Sep 17 00:00:00 2001 From: psyeon1120 Date: Fri, 12 Jul 2024 01:17:25 +0900 Subject: [PATCH 8/9] =?UTF-8?q?#327=20docs:=20fridge=20=EA=B4=80=EB=A0=A8?= =?UTF-8?q?=20response=20swagger=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dto/response/FridgeFoodStatistics.java | 9 ++++--- .../dto/response/FridgeFoodsStatistics.java | 5 +++- .../fridge/dto/response/UpdateMembersRes.java | 24 +++++++++++-------- 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodStatistics.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodStatistics.java index 45af8c17..002247e4 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodStatistics.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodStatistics.java @@ -1,5 +1,6 @@ package com.example.icebutler_server.fridge.dto.response; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -9,12 +10,14 @@ @Builder @AllArgsConstructor @NoArgsConstructor +@Schema(name = "FridgeFoodStatistics", description = "냉장고 식품 삭제 통계 정보") public class FridgeFoodStatistics { + @Schema(name = "foodCategory", description = "식품 카테고리") private String foodCategory; + @Schema(name = "foodCategoryImgUrl", description = "식품 카테고리 이미지 URL") private String foodCategoryImgUrl; + @Schema(name = "percentage", description = "삭제 비율") private Double percentage; + @Schema(name = "count", description = "삭제 개수") private Integer count; - - - } diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodsStatistics.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodsStatistics.java index e191afaf..89fcafcb 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodsStatistics.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/FridgeFoodsStatistics.java @@ -1,5 +1,6 @@ package com.example.icebutler_server.fridge.dto.response; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,11 +12,13 @@ @Builder @AllArgsConstructor @NoArgsConstructor +@Schema(name = "FridgeFoodsStatistics", description = "식품 카테고리별 삭제 통계 목록") public class FridgeFoodsStatistics { + @Schema(name = "foodStatisticsList", description = "식품 삭제 통계 목록") private List foodStatisticsList; - public static FridgeFoodsStatistics toDto(List list){ + public static FridgeFoodsStatistics toDto(List list) { return new FridgeFoodsStatistics(list); } diff --git a/src/main/java/com/example/icebutler_server/fridge/dto/response/UpdateMembersRes.java b/src/main/java/com/example/icebutler_server/fridge/dto/response/UpdateMembersRes.java index f1b14445..97092401 100644 --- a/src/main/java/com/example/icebutler_server/fridge/dto/response/UpdateMembersRes.java +++ b/src/main/java/com/example/icebutler_server/fridge/dto/response/UpdateMembersRes.java @@ -1,6 +1,7 @@ package com.example.icebutler_server.fridge.dto.response; import com.example.icebutler_server.fridge.entity.FridgeUser; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @@ -9,17 +10,20 @@ @Data @NoArgsConstructor +@Schema(name = "UpdateMembersRes", description = "냉장고 사용자 변경 정보") public class UpdateMembersRes { - private List withDrawMember; - private List checkNewMember; + @Schema(name = "withDrawMember", description = "냉장고 탈퇴 사용자 목록") + private List withDrawMember; + @Schema(name = "checkNewMember", description = "냉장고 가입 사용자 목록") + private List checkNewMember; - @Builder - public UpdateMembersRes(List withDrawMember, List checkNewMember) { - this.withDrawMember = withDrawMember; - this.checkNewMember = checkNewMember; - } + @Builder + public UpdateMembersRes(List withDrawMember, List checkNewMember) { + this.withDrawMember = withDrawMember; + this.checkNewMember = checkNewMember; + } - public static UpdateMembersRes toDto(List withDrawMember, List checkNewMember) { - return UpdateMembersRes.builder().withDrawMember(withDrawMember).checkNewMember(checkNewMember).build(); - } + public static UpdateMembersRes toDto(List withDrawMember, List checkNewMember) { + return UpdateMembersRes.builder().withDrawMember(withDrawMember).checkNewMember(checkNewMember).build(); + } } From a5a7bfe3c83c79d91e54b7fc03167dc39987d421 Mon Sep 17 00:00:00 2001 From: psyeon1120 Date: Fri, 12 Jul 2024 01:25:32 +0900 Subject: [PATCH 9/9] =?UTF-8?q?#327=20feat:=20ExceptionAdvice=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../global/exception/ExceptionAdvice.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/main/java/com/example/icebutler_server/global/exception/ExceptionAdvice.java b/src/main/java/com/example/icebutler_server/global/exception/ExceptionAdvice.java index d2d61b55..01958364 100644 --- a/src/main/java/com/example/icebutler_server/global/exception/ExceptionAdvice.java +++ b/src/main/java/com/example/icebutler_server/global/exception/ExceptionAdvice.java @@ -3,11 +3,17 @@ import com.example.icebutler_server.global.dto.response.ResponseCustom; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.validation.FieldError; +import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; +import java.sql.SQLException; +import java.time.format.DateTimeParseException; import java.util.Objects; public class ExceptionAdvice { @@ -25,4 +31,26 @@ protected ResponseCustom handleMethodArgumentNotValidException(MethodArgumentNot ReturnCode returnCode = ReturnCode.findByCode(fieldError.getDefaultMessage()); return ResponseCustom.error(returnCode); } + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler( + value = { + HttpMessageNotReadableException.class, + HttpRequestMethodNotSupportedException.class, + MissingServletRequestParameterException.class, + MethodArgumentTypeMismatchException.class, + DateTimeParseException.class + } + ) + protected ResponseCustom handleBaseException(Exception e) { + return ResponseCustom.error(ReturnCode.INVALID_PARAM); + } + + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + @ExceptionHandler( + value = {SQLException.class} + ) + protected ResponseCustom handleBaseException(SQLException e) { + return ResponseCustom.error(ReturnCode.INTERNAL_SERVER_ERROR); + } }