Files
zellyy-finance/src/utils/sync/budget/downloadBudget.ts
gpt-engineer-app[bot] dab1a9cb84 Fix budget synchronization issue
Ensure budget data is also synchronized when syncing with cloud after local data deletion.
2025-03-16 10:30:38 +00:00

142 lines
4.4 KiB
TypeScript

import { supabase } from '@/lib/supabase';
import { isSyncEnabled } from '../syncSettings';
/**
* 서버에서 예산 데이터 다운로드
*/
export const downloadBudgets = async (userId: string): Promise<void> => {
if (!isSyncEnabled()) return;
try {
console.log('서버에서 예산 데이터 다운로드 시작');
// 예산 데이터 및 카테고리 예산 데이터 가져오기
const [budgetData, categoryData] = await Promise.all([
fetchBudgetData(userId),
fetchCategoryBudgetData(userId)
]);
// 예산 데이터 처리
if (budgetData) {
await processBudgetData(budgetData);
} else {
console.log('서버에서 예산 데이터를 찾을 수 없음');
}
// 카테고리 예산 데이터 처리
if (categoryData && categoryData.length > 0) {
await processCategoryBudgetData(categoryData);
} else {
console.log('서버에서 카테고리 예산 데이터를 찾을 수 없음');
}
console.log('예산 데이터 다운로드 완료');
} catch (error) {
console.error('예산 데이터 다운로드 실패:', error);
throw error;
}
};
/**
* 예산 데이터 조회
*/
async function fetchBudgetData(userId: string) {
// 현재 월/년도 가져오기
const now = new Date();
const currentMonth = now.getMonth() + 1; // 0-11 -> 1-12
const currentYear = now.getFullYear();
const { data, error } = await supabase
.from('budgets')
.select('*')
.eq('user_id', userId)
.eq('month', currentMonth)
.eq('year', currentYear);
if (error) {
console.error('예산 데이터 조회 실패:', error);
throw error;
}
return data && data.length > 0 ? data[0] : null;
}
/**
* 카테고리 예산 데이터 조회
*/
async function fetchCategoryBudgetData(userId: string) {
const { data, error } = await supabase
.from('category_budgets')
.select('*')
.eq('user_id', userId);
if (error) {
console.error('카테고리 예산 조회 실패:', error);
throw error;
}
return data;
}
/**
* 예산 데이터 처리 및 로컬 저장
*/
async function processBudgetData(budgetData: any) {
console.log('서버에서 예산 데이터 수신:', budgetData);
// 기존 로컬 데이터 가져오기
const localBudgetDataStr = localStorage.getItem('budgetData');
let localBudgetData = localBudgetDataStr ? JSON.parse(localBudgetDataStr) : {
daily: { targetAmount: 0, spentAmount: 0, remainingAmount: 0 },
weekly: { targetAmount: 0, spentAmount: 0, remainingAmount: 0 },
monthly: { targetAmount: 0, spentAmount: 0, remainingAmount: 0 }
};
// 서버 데이터로 업데이트 (지출 금액은 유지)
const updatedBudgetData = {
daily: {
targetAmount: Math.round(budgetData.total_budget / 30),
spentAmount: localBudgetData.daily.spentAmount,
remainingAmount: Math.round(budgetData.total_budget / 30) - localBudgetData.daily.spentAmount
},
weekly: {
targetAmount: Math.round(budgetData.total_budget / 4.3),
spentAmount: localBudgetData.weekly.spentAmount,
remainingAmount: Math.round(budgetData.total_budget / 4.3) - localBudgetData.weekly.spentAmount
},
monthly: {
targetAmount: budgetData.total_budget,
spentAmount: localBudgetData.monthly.spentAmount,
remainingAmount: budgetData.total_budget - localBudgetData.monthly.spentAmount
}
};
// 로컬 스토리지에 저장
localStorage.setItem('budgetData', JSON.stringify(updatedBudgetData));
console.log('예산 데이터 로컬 저장 완료', updatedBudgetData);
// 이벤트 발생시켜 UI 업데이트
window.dispatchEvent(new Event('budgetDataUpdated'));
}
/**
* 카테고리 예산 데이터 처리 및 로컬 저장
*/
async function processCategoryBudgetData(categoryData: any[]) {
console.log(`${categoryData.length}개의 카테고리 예산 수신`);
// 카테고리 예산 로컬 형식으로 변환
const localCategoryBudgets = categoryData.reduce((acc, curr) => {
acc[curr.category] = curr.amount;
return acc;
}, {} as Record<string, number>);
// 로컬 스토리지에 저장
localStorage.setItem('categoryBudgets', JSON.stringify(localCategoryBudgets));
console.log('카테고리 예산 로컬 저장 완료', localCategoryBudgets);
// 이벤트 발생시켜 UI 업데이트
window.dispatchEvent(new Event('categoryBudgetsUpdated'));
}