Files
zellyy-finance/src/utils/sync/budgetSync.ts
gpt-engineer-app[bot] d74acdbbb8 Refactor syncUtils module
Refactor the syncUtils module to improve code organization and maintainability by breaking it down into smaller, more focused utility functions.
2025-03-15 05:12:43 +00:00

128 lines
3.7 KiB
TypeScript

import { supabase } from '@/lib/supabase';
import { isSyncEnabled } from './syncSettings';
/**
* Upload budget data from local storage to Supabase
*/
export const uploadBudgets = async (userId: string): Promise<void> => {
if (!isSyncEnabled()) return;
try {
const budgetData = localStorage.getItem('budgetData');
const categoryBudgets = localStorage.getItem('categoryBudgets');
if (budgetData) {
const parsedBudgetData = JSON.parse(budgetData);
// 기존 예산 데이터 삭제
await supabase
.from('budgets')
.delete()
.eq('user_id', userId);
// 새 예산 데이터 삽입
const { error } = await supabase.from('budgets').insert({
user_id: userId,
daily_target: parsedBudgetData.daily.targetAmount,
weekly_target: parsedBudgetData.weekly.targetAmount,
monthly_target: parsedBudgetData.monthly.targetAmount
});
if (error) throw error;
}
if (categoryBudgets) {
const parsedCategoryBudgets = JSON.parse(categoryBudgets);
// 기존 카테고리 예산 삭제
await supabase
.from('category_budgets')
.delete()
.eq('user_id', userId);
// 카테고리별 예산 데이터 변환 및 삽입
const categoryEntries = Object.entries(parsedCategoryBudgets).map(
([category, amount]) => ({
user_id: userId,
category,
amount
})
);
const { error } = await supabase
.from('category_budgets')
.insert(categoryEntries);
if (error) throw error;
}
console.log('예산 데이터 업로드 완료');
} catch (error) {
console.error('예산 데이터 업로드 실패:', error);
}
};
/**
* Download budget data from Supabase to local storage
*/
export const downloadBudgets = async (userId: string): Promise<void> => {
if (!isSyncEnabled()) return;
try {
// 예산 데이터 가져오기
const { data: budgetData, error: budgetError } = await supabase
.from('budgets')
.select('*')
.eq('user_id', userId)
.single();
if (budgetError && budgetError.code !== 'PGRST116') throw budgetError;
// 카테고리 예산 가져오기
const { data: categoryData, error: categoryError } = await supabase
.from('category_budgets')
.select('*')
.eq('user_id', userId);
if (categoryError) throw categoryError;
if (budgetData) {
// 예산 데이터 로컬 형식으로 변환
const localBudgetData = {
daily: {
targetAmount: budgetData.daily_target,
spentAmount: 0, // 지출액은 로컬에서 계산
remainingAmount: budgetData.daily_target
},
weekly: {
targetAmount: budgetData.weekly_target,
spentAmount: 0,
remainingAmount: budgetData.weekly_target
},
monthly: {
targetAmount: budgetData.monthly_target,
spentAmount: 0,
remainingAmount: budgetData.monthly_target
}
};
localStorage.setItem('budgetData', JSON.stringify(localBudgetData));
}
if (categoryData && categoryData.length > 0) {
// 카테고리 예산 로컬 형식으로 변환
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('예산 데이터 다운로드 완료');
} catch (error) {
console.error('예산 데이터 다운로드 실패:', error);
}
};