Refactor: Split useBudgetState hook
The useBudgetState hook was split into smaller, more manageable files to improve code organization and maintainability.
This commit is contained in:
72
src/contexts/budget/hooks/useExtendedBudgetUpdate.ts
Normal file
72
src/contexts/budget/hooks/useExtendedBudgetUpdate.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
|
||||
import { useCallback } from 'react';
|
||||
import { BudgetPeriod, BudgetData } from '../types';
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
|
||||
// 확장된 예산 목표 업데이트 훅
|
||||
export const useExtendedBudgetUpdate = (
|
||||
budgetData: BudgetData,
|
||||
categoryBudgets: Record<string, number>,
|
||||
handleBudgetGoalUpdate: (type: BudgetPeriod, amount: number) => void,
|
||||
updateCategoryBudgets: (newCategoryBudgets: Record<string, number>) => void
|
||||
) => {
|
||||
// 확장된 예산 목표 업데이트 함수
|
||||
const extendedBudgetGoalUpdate = useCallback((
|
||||
type: BudgetPeriod,
|
||||
amount: number,
|
||||
newCategoryBudgets?: Record<string, number>
|
||||
) => {
|
||||
try {
|
||||
console.log(`확장된 예산 목표 업데이트 호출: ${type}, 금액: ${amount}`);
|
||||
|
||||
// 카테고리 예산이 직접 업데이트된 경우
|
||||
if (newCategoryBudgets) {
|
||||
console.log('카테고리 예산 직접 업데이트:', newCategoryBudgets);
|
||||
updateCategoryBudgets(newCategoryBudgets);
|
||||
return;
|
||||
}
|
||||
|
||||
// 월간 예산을 업데이트하고 일일, 주간도 자동 계산
|
||||
if (type === 'monthly') {
|
||||
console.log('월간 예산 업데이트:', amount);
|
||||
if (amount <= 0) return; // 예산이 0 이하면 업데이트하지 않음
|
||||
|
||||
const ratio = amount / (budgetData.monthly.targetAmount || 1); // 0으로 나누기 방지
|
||||
const updatedCategoryBudgets: Record<string, number> = {};
|
||||
|
||||
// 비율에 따라 카테고리 예산 업데이트
|
||||
Object.keys(categoryBudgets).forEach(category => {
|
||||
updatedCategoryBudgets[category] = Math.round(categoryBudgets[category] * ratio);
|
||||
});
|
||||
|
||||
// 모든 카테고리가 0인 경우 (초기 상태)
|
||||
const allZero = Object.values(categoryBudgets).every(value => value === 0);
|
||||
if (allZero) {
|
||||
// 카테고리 간 균등 분배
|
||||
const categories = Object.keys(categoryBudgets);
|
||||
const perCategoryAmount = Math.round(amount / categories.length);
|
||||
|
||||
categories.forEach(category => {
|
||||
updatedCategoryBudgets[category] = perCategoryAmount;
|
||||
});
|
||||
}
|
||||
|
||||
console.log('업데이트된 카테고리 예산:', updatedCategoryBudgets);
|
||||
updateCategoryBudgets(updatedCategoryBudgets);
|
||||
} else {
|
||||
// 일일이나 주간 예산이 직접 업데이트되는 경우
|
||||
console.log(`${type} 예산 직접 업데이트:`, amount);
|
||||
handleBudgetGoalUpdate(type, amount);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('예산 목표 업데이트 중 오류:', error);
|
||||
toast({
|
||||
title: "예산 업데이트 실패",
|
||||
description: "예산 목표를 업데이트하는 중 오류가 발생했습니다.",
|
||||
variant: "destructive"
|
||||
});
|
||||
}
|
||||
}, [budgetData, categoryBudgets, handleBudgetGoalUpdate, updateCategoryBudgets]);
|
||||
|
||||
return { extendedBudgetGoalUpdate };
|
||||
};
|
||||
Reference in New Issue
Block a user