Skip to content

Commit

Permalink
Merge pull request #166 from BudgetBuddiesTeam/dev
Browse files Browse the repository at this point in the history
[v11] 가계부 소비, 카테고리 삭제 관련 버그 수정
  • Loading branch information
m3k0813 authored Aug 22, 2024
2 parents cd1fad6 + 2e799ab commit 0c1504c
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,15 @@ public void deleteCategory(Long categoryId, Long userId) {
throw new IllegalArgumentException("Default categories cannot be deleted.");
}

// 삭제되지 않은 Expense 조회
List<Expense> 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<Expense> currentMonthExpenses = expenseRepository.findByCategoryIdAndUserIdAndExpenseDateBetweenAndDeletedFalse(
categoryId, userId, startOfMonth.atStartOfDay(), endOfMonth.atTime(23, 59, 59));

long totalAmount = currentMonthExpenses.stream()
.mapToLong(Expense::getAmount)
.sum();

Expand All @@ -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<Expense> allExpenses = expenseRepository.findByCategoryIdAndUserIdAndDeletedFalse(categoryId, userId);

// 해당 카테고리에 부합하는 모든 기간의 Expense들을 etc 카테고리로 이동
allExpenses.forEach(expense -> {
expense.setCategory(goal.getCategory());
expenseRepository.save(expense);
});
Expand All @@ -115,4 +124,5 @@ public void deleteCategory(Long categoryId, Long userId) {
categoryRepository.save(category);
});
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,17 @@
public interface ConsumptionGoalService {

List<TopGoalCategoryResponseDto> getTopConsumptionGoalCategories(Long userId, int peerAgeStart, int peerAgeEnd,
String peerGender);
String peerGender);

List<AllConsumptionCategoryResponseDto> 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);

Expand All @@ -41,8 +41,10 @@ ConsumptionGoalResponseListDto updateConsumptionGoals(Long userId,
void decreaseConsumeAmount(Long userId, Long categoryId, Long amount, LocalDate expenseDate);

List<TopCategoryConsumptionDto> getTopConsumptionCategories(Long userId, int peerAgeStart, int peerAgeEnd,
String peerGender);
String peerGender);

List<AllConsumptionCategoryResponseDto> getAllConsumptionCategories(Long userId, int peerAgeS, int peerAgeE,
String peerG);
String peerG);

void updateOrCreateDeletedConsumptionGoal(Long userId, Long categoryId, LocalDate goalMonth, Long amount);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<ConsumptionGoal> 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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -15,5 +16,11 @@ public interface ExpenseRepository extends JpaRepository<Expense, Long> {
List<Expense> 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<Expense> findByCategoryIdAndUserId(@Param("categoryId") Long categoryId, @Param("userId") Long userId);}
List<Expense> findByCategoryIdAndUserIdAndExpenseDateBetweenAndDeletedFalse(Long categoryId, Long userId, LocalDateTime startDate, LocalDateTime endDate);

List<Expense> findByCategoryIdAndUserIdAndDeletedFalse(Long categoryId, Long userId);

@Modifying
@Query("UPDATE Expense e SET e.deleted = TRUE WHERE e.id = :expenseId")
void softDeleteById(@Param("expenseId") Long expenseId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
/*
Expand All @@ -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
Expand Down

0 comments on commit 0c1504c

Please sign in to comment.