diff --git a/src/main/java/com/bbteam/budgetbuddies/domain/category/service/CategoryServiceImpl.java b/src/main/java/com/bbteam/budgetbuddies/domain/category/service/CategoryServiceImpl.java index eaa2681f..029a7197 100644 --- a/src/main/java/com/bbteam/budgetbuddies/domain/category/service/CategoryServiceImpl.java +++ b/src/main/java/com/bbteam/budgetbuddies/domain/category/service/CategoryServiceImpl.java @@ -89,9 +89,15 @@ public void deleteCategory(Long categoryId, Long userId) { throw new IllegalArgumentException("Default categories cannot be deleted."); } - // 삭제되지 않은 Expense 조회 - List expenses = expenseRepository.findByCategoryIdAndUserId(categoryId, userId); - long totalAmount = expenses.stream() + // 현재 날짜를 기준으로 해당 월의 시작과 끝 날짜 계산 + LocalDate startOfMonth = LocalDate.now().withDayOfMonth(1); + LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()); + + // 현재 월에 해당하는 삭제되지 않은 Expense 조회 (deleted = false) + List currentMonthExpenses = expenseRepository.findByCategoryIdAndUserIdAndExpenseDateBetweenAndDeletedFalse( + categoryId, userId, startOfMonth.atStartOfDay(), endOfMonth.atTime(23, 59, 59)); + + long totalAmount = currentMonthExpenses.stream() .mapToLong(Expense::getAmount) .sum(); @@ -101,8 +107,11 @@ public void deleteCategory(Long categoryId, Long userId) { goal.setConsumeAmount(goal.getConsumeAmount() + totalAmount); consumptionGoalRepository.save(goal); - // 해당 카테고리에 부합하는 Expense들을 etc 카테고리로 이동 - expenses.forEach(expense -> { + // 삭제되지 않은 모든 기간의 Expense 조회 (deleted = false) + List allExpenses = expenseRepository.findByCategoryIdAndUserIdAndDeletedFalse(categoryId, userId); + + // 해당 카테고리에 부합하는 모든 기간의 Expense들을 etc 카테고리로 이동 + allExpenses.forEach(expense -> { expense.setCategory(goal.getCategory()); expenseRepository.save(expense); }); @@ -115,4 +124,5 @@ public void deleteCategory(Long categoryId, Long userId) { categoryRepository.save(category); }); } + } \ No newline at end of file diff --git a/src/main/java/com/bbteam/budgetbuddies/domain/consumptiongoal/service/ConsumptionGoalService.java b/src/main/java/com/bbteam/budgetbuddies/domain/consumptiongoal/service/ConsumptionGoalService.java index 27553813..1c35f2ce 100644 --- a/src/main/java/com/bbteam/budgetbuddies/domain/consumptiongoal/service/ConsumptionGoalService.java +++ b/src/main/java/com/bbteam/budgetbuddies/domain/consumptiongoal/service/ConsumptionGoalService.java @@ -20,17 +20,17 @@ public interface ConsumptionGoalService { List getTopConsumptionGoalCategories(Long userId, int peerAgeStart, int peerAgeEnd, - String peerGender); + String peerGender); List getAllConsumptionGoalCategories(Long userId, int peerAgeS, int peerAgeE, - String peerG); + String peerG); ConsumptionGoalResponseListDto findUserConsumptionGoalList(Long userId, LocalDate date); PeerInfoResponseDto getPeerInfo(Long userId, int peerAgeStart, int peerAgeEnd, String peerGender); ConsumptionGoalResponseListDto updateConsumptionGoals(Long userId, - ConsumptionGoalListRequestDto consumptionGoalListRequestDto); + ConsumptionGoalListRequestDto consumptionGoalListRequestDto); ConsumptionAnalysisResponseDto getTopCategoryAndConsumptionAmount(Long userId); @@ -41,8 +41,10 @@ ConsumptionGoalResponseListDto updateConsumptionGoals(Long userId, void decreaseConsumeAmount(Long userId, Long categoryId, Long amount, LocalDate expenseDate); List getTopConsumptionCategories(Long userId, int peerAgeStart, int peerAgeEnd, - String peerGender); + String peerGender); List getAllConsumptionCategories(Long userId, int peerAgeS, int peerAgeE, - String peerG); + String peerG); + + void updateOrCreateDeletedConsumptionGoal(Long userId, Long categoryId, LocalDate goalMonth, Long amount); } diff --git a/src/main/java/com/bbteam/budgetbuddies/domain/consumptiongoal/service/ConsumptionGoalServiceImpl.java b/src/main/java/com/bbteam/budgetbuddies/domain/consumptiongoal/service/ConsumptionGoalServiceImpl.java index 51183197..a371880d 100644 --- a/src/main/java/com/bbteam/budgetbuddies/domain/consumptiongoal/service/ConsumptionGoalServiceImpl.java +++ b/src/main/java/com/bbteam/budgetbuddies/domain/consumptiongoal/service/ConsumptionGoalServiceImpl.java @@ -539,4 +539,34 @@ public void decreaseConsumeAmount(Long userId, Long categoryId, Long amount, Loc consumptionGoal.decreaseConsumeAmount(amount); consumptionGoalRepository.save(consumptionGoal); } + + // 현재 월이 아닌 이전 소비 내역에 대해서 소비 목표를 생성해야되는 경우 updateOrCreateDeletedConsumptionGoal 사용 + @Override + @Transactional + public void updateOrCreateDeletedConsumptionGoal(Long userId, Long categoryId, LocalDate goalMonth, Long amount) { + User user = userRepository.findById(userId) + .orElseThrow(() -> new IllegalArgumentException("Invalid user ID")); + Category category = categoryRepository.findById(categoryId) + .orElseThrow(() -> new IllegalArgumentException("Invalid category ID")); + + // 해당 월의 ConsumptionGoal이 존재하는지 확인 + Optional existingGoal = consumptionGoalRepository.findConsumptionGoalByUserAndCategoryAndGoalMonth(user, category, goalMonth); + + if (existingGoal.isPresent()) { // 존재하는 경우, consumeAmount 업데이트 + ConsumptionGoal consumptionGoal = existingGoal.get(); + consumptionGoal.updateConsumeAmount(amount); + consumptionGoalRepository.save(consumptionGoal); + } else { // 존재하지 않는 경우, 새로운 ConsumptionGoal을 생성 (이 때 목표 금액은 0) + ConsumptionGoal newGoal = ConsumptionGoal.builder() + .user(user) + .category(category) + .goalMonth(goalMonth) + .consumeAmount(amount) + .goalAmount(0L) + .build(); + + newGoal.updateConsumeAmount(amount); // 신규 생성된 목표에 소비 금액 추가 + consumptionGoalRepository.save(newGoal); + } + } } \ No newline at end of file diff --git a/src/main/java/com/bbteam/budgetbuddies/domain/expense/repository/ExpenseRepository.java b/src/main/java/com/bbteam/budgetbuddies/domain/expense/repository/ExpenseRepository.java index b90c66ab..86dfd81a 100644 --- a/src/main/java/com/bbteam/budgetbuddies/domain/expense/repository/ExpenseRepository.java +++ b/src/main/java/com/bbteam/budgetbuddies/domain/expense/repository/ExpenseRepository.java @@ -4,6 +4,7 @@ import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; @@ -15,5 +16,11 @@ public interface ExpenseRepository extends JpaRepository { List findAllByUserIdForPeriod(@Param("user") User user, @Param("startDate") LocalDateTime startDate, @Param("endDate") LocalDateTime endDate); - @Query("SELECT e FROM Expense e WHERE e.category.id = :categoryId AND e.user.id = :userId AND e.deleted = FALSE") - List findByCategoryIdAndUserId(@Param("categoryId") Long categoryId, @Param("userId") Long userId);} + List findByCategoryIdAndUserIdAndExpenseDateBetweenAndDeletedFalse(Long categoryId, Long userId, LocalDateTime startDate, LocalDateTime endDate); + + List findByCategoryIdAndUserIdAndDeletedFalse(Long categoryId, Long userId); + + @Modifying + @Query("UPDATE Expense e SET e.deleted = TRUE WHERE e.id = :expenseId") + void softDeleteById(@Param("expenseId") Long expenseId); +} diff --git a/src/main/java/com/bbteam/budgetbuddies/domain/expense/service/ExpenseServiceImpl.java b/src/main/java/com/bbteam/budgetbuddies/domain/expense/service/ExpenseServiceImpl.java index 6f88ab4b..b8779a95 100644 --- a/src/main/java/com/bbteam/budgetbuddies/domain/expense/service/ExpenseServiceImpl.java +++ b/src/main/java/com/bbteam/budgetbuddies/domain/expense/service/ExpenseServiceImpl.java @@ -66,9 +66,18 @@ else if (!category.getIsDefault() && category.getUser().getId().equals(userId)) Expense expense = expenseConverter.toExpenseEntity(expenseRequestDto, user, category); expenseRepository.save(expense); - // 소비 목표 업데이트 - consumptionGoalService.updateConsumeAmount(userId, expenseRequestDto.getCategoryId(), - expenseRequestDto.getAmount()); + // expenseDate가 현재 월인지 확인 + LocalDate expenseDateMonth = expenseRequestDto.getExpenseDate().toLocalDate().withDayOfMonth(1); + LocalDate currentMonth = LocalDate.now().withDayOfMonth(1); + + if (expenseDateMonth.equals(currentMonth)) { + // 현재 월의 소비 내역일 경우 ConsumptionGoal을 업데이트 + consumptionGoalService.updateConsumeAmount(userId, expenseRequestDto.getCategoryId(), expenseRequestDto.getAmount()); + } +// else { +// // 과거 월의 소비 내역일 경우 해당 월의 ConsumptionGoal을 업데이트 또는 삭제 상태로 생성 +// consumptionGoalService.updateOrCreateDeletedConsumptionGoal(userId, expenseRequestDto.getCategoryId(), expenseDateMonth, expenseRequestDto.getAmount()); +// } return expenseConverter.toExpenseResponseDto(expense); /* @@ -78,19 +87,25 @@ else if (!category.getIsDefault() && category.getUser().getId().equals(userId)) } @Override + @Transactional public void deleteExpense(Long expenseId) { Expense expense = expenseRepository.findById(expenseId) - .orElseThrow(() -> new IllegalArgumentException("Not found Expense")); + .orElseThrow(() -> new IllegalArgumentException("Not found Expense")); Long userId = expense.getUser().getId(); Long categoryId = expense.getCategory().getId(); Long amount = expense.getAmount(); LocalDate expenseDate = expense.getExpenseDate().toLocalDate(); + LocalDate currentMonth = LocalDate.now().withDayOfMonth(1); - expenseRepository.delete(expense); - - // 소비 금액 차감 로직 - consumptionGoalService.decreaseConsumeAmount(userId, categoryId, amount, expenseDate); + if (expenseDate.withDayOfMonth(1).equals(currentMonth)) { + // 현재 달에 해당하는 소비 내역인 경우, 소비 금액 차감 로직 실행 + expenseRepository.delete(expense); + consumptionGoalService.decreaseConsumeAmount(userId, categoryId, amount, expenseDate); + } else { + // 과거 달의 소비 내역인 경우, soft delete 처리 + expenseRepository.softDeleteById(expenseId); + } } @Override