132 lines
3.9 KiB
TypeScript
132 lines
3.9 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);
|
|
}
|
|
|
|
// 카테고리 예산 데이터 처리
|
|
if (categoryData && categoryData.length > 0) {
|
|
await processCategoryBudgetData(categoryData);
|
|
}
|
|
|
|
console.log('예산 데이터 다운로드 완료');
|
|
} catch (error) {
|
|
console.error('예산 데이터 다운로드 실패:', error);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 예산 데이터 조회
|
|
*/
|
|
async function fetchBudgetData(userId: string) {
|
|
const { data, error } = await supabase
|
|
.from('budgets')
|
|
.select('*')
|
|
.eq('user_id', userId)
|
|
.maybeSingle(); // 사용자당 하나의 예산 데이터만 존재
|
|
|
|
if (error && error.code !== 'PGRST116') {
|
|
console.error('예산 데이터 조회 실패:', error);
|
|
throw error;
|
|
}
|
|
|
|
return data;
|
|
}
|
|
|
|
/**
|
|
* 카테고리 예산 데이터 조회
|
|
*/
|
|
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: budgetData.daily_target,
|
|
spentAmount: localBudgetData.daily.spentAmount,
|
|
remainingAmount: budgetData.daily_target - localBudgetData.daily.spentAmount
|
|
},
|
|
weekly: {
|
|
targetAmount: budgetData.weekly_target,
|
|
spentAmount: localBudgetData.weekly.spentAmount,
|
|
remainingAmount: budgetData.weekly_target - localBudgetData.weekly.spentAmount
|
|
},
|
|
monthly: {
|
|
targetAmount: budgetData.monthly_target,
|
|
spentAmount: localBudgetData.monthly.spentAmount,
|
|
remainingAmount: budgetData.monthly_target - localBudgetData.monthly.spentAmount
|
|
}
|
|
};
|
|
|
|
// 로컬 스토리지에 저장
|
|
localStorage.setItem('budgetData', JSON.stringify(updatedBudgetData));
|
|
console.log('예산 데이터 로컬 저장 완료');
|
|
|
|
// 이벤트 발생시켜 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('카테고리 예산 로컬 저장 완료');
|
|
|
|
// 이벤트 발생시켜 UI 업데이트
|
|
window.dispatchEvent(new Event('categoryBudgetsUpdated'));
|
|
}
|