Fix data loss on sync after reset
Addresses an issue where budget data was lost after a data reset, logout, and subsequent synchronization. The fix ensures budget data is correctly restored in such scenarios.
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
|
||||
import { supabase } from '@/lib/supabase';
|
||||
import { isSyncEnabled } from '../syncSettings';
|
||||
import {
|
||||
@@ -20,10 +21,16 @@ export const uploadBudgets = async (userId: string): Promise<void> => {
|
||||
// 예산 데이터 업로드
|
||||
if (budgetDataStr) {
|
||||
const budgetData = JSON.parse(budgetDataStr);
|
||||
await uploadBudgetData(userId, budgetData);
|
||||
|
||||
// 업로드 성공 후 수정 추적 정보 초기화
|
||||
clearModifiedBudget();
|
||||
// 월간 예산이 0보다 클 때만 업로드
|
||||
if (budgetData.monthly && budgetData.monthly.targetAmount > 0) {
|
||||
console.log('유효한 월간 예산 발견:', budgetData.monthly.targetAmount);
|
||||
await uploadBudgetData(userId, budgetData);
|
||||
// 업로드 성공 후 수정 추적 정보 초기화
|
||||
clearModifiedBudget();
|
||||
} else {
|
||||
console.log('월간 예산이 0 이하거나 없어서 업로드 건너뜀');
|
||||
}
|
||||
} else {
|
||||
console.log('업로드할 예산 데이터가 없음');
|
||||
}
|
||||
@@ -31,10 +38,17 @@ export const uploadBudgets = async (userId: string): Promise<void> => {
|
||||
// 카테고리 예산 업로드
|
||||
if (categoryBudgetsStr) {
|
||||
const categoryBudgets = JSON.parse(categoryBudgetsStr);
|
||||
await uploadCategoryBudgets(userId, categoryBudgets);
|
||||
|
||||
// 업로드 성공 후 수정 추적 정보 초기화
|
||||
clearModifiedCategoryBudgets();
|
||||
// 총 카테고리 예산이 0보다 클 때만 업로드
|
||||
const totalCategoryBudget = Object.values(categoryBudgets).reduce((sum: number, val: number) => sum + val, 0);
|
||||
if (totalCategoryBudget > 0) {
|
||||
console.log('유효한 카테고리 예산 발견:', totalCategoryBudget);
|
||||
await uploadCategoryBudgets(userId, categoryBudgets);
|
||||
// 업로드 성공 후 수정 추적 정보 초기화
|
||||
clearModifiedCategoryBudgets();
|
||||
} else {
|
||||
console.log('카테고리 예산이 모두 0이어서 업로드 건너뜀');
|
||||
}
|
||||
} else {
|
||||
console.log('업로드할 카테고리 예산이 없음');
|
||||
}
|
||||
@@ -73,28 +87,42 @@ async function uploadBudgetData(userId: string, parsedBudgetData: Record<string,
|
||||
// 월간 타겟 금액 가져오기
|
||||
const monthlyTarget = parsedBudgetData.monthly.targetAmount;
|
||||
|
||||
// 예산이 0 이하면 업로드하지 않음
|
||||
if (monthlyTarget <= 0) {
|
||||
console.log('월간 예산이 0 이하여서 업로드 건너뜀:', monthlyTarget);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('업로드할 월간 예산:', monthlyTarget);
|
||||
|
||||
// 현재 타임스탬프
|
||||
const currentTimestamp = new Date().toISOString();
|
||||
|
||||
// 업데이트 또는 삽입 결정
|
||||
// 가능한 경우 서버 데이터와 비교하여 필요한 경우만 업데이트
|
||||
if (existingBudgets && existingBudgets.length > 0) {
|
||||
// 기존 데이터 업데이트
|
||||
const { error } = await supabase
|
||||
.from('budgets')
|
||||
.update({
|
||||
total_budget: monthlyTarget,
|
||||
updated_at: currentTimestamp
|
||||
})
|
||||
.eq('id', existingBudgets[0].id);
|
||||
const existingBudget = existingBudgets[0];
|
||||
// 새 예산이 기존 예산보다 클 때만 업데이트
|
||||
if (monthlyTarget > existingBudget.total_budget) {
|
||||
console.log(`새 예산(${monthlyTarget})이 기존 예산(${existingBudget.total_budget})보다 큼, 업데이트 실행`);
|
||||
|
||||
if (error) {
|
||||
console.error('예산 데이터 업데이트 실패:', error);
|
||||
throw error;
|
||||
// 기존 데이터 업데이트
|
||||
const { error } = await supabase
|
||||
.from('budgets')
|
||||
.update({
|
||||
total_budget: monthlyTarget,
|
||||
updated_at: currentTimestamp
|
||||
})
|
||||
.eq('id', existingBudget.id);
|
||||
|
||||
if (error) {
|
||||
console.error('예산 데이터 업데이트 실패:', error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
console.log('예산 데이터 업데이트 성공');
|
||||
} else {
|
||||
console.log(`새 예산(${monthlyTarget})이 기존 예산(${existingBudget.total_budget})보다 작거나 같음, 업데이트 건너뜀`);
|
||||
}
|
||||
|
||||
console.log('예산 데이터 업데이트 성공');
|
||||
} else {
|
||||
// 새 데이터 삽입
|
||||
const { error } = await supabase
|
||||
@@ -123,6 +151,40 @@ async function uploadBudgetData(userId: string, parsedBudgetData: Record<string,
|
||||
async function uploadCategoryBudgets(userId: string, parsedCategoryBudgets: Record<string, number>): Promise<void> {
|
||||
console.log('카테고리 예산 업로드:', parsedCategoryBudgets);
|
||||
|
||||
// 기존 카테고리 예산 확인
|
||||
const { data: existingCategoryBudgets, error: fetchError } = await supabase
|
||||
.from('category_budgets')
|
||||
.select('*')
|
||||
.eq('user_id', userId);
|
||||
|
||||
if (fetchError) {
|
||||
console.error('기존 카테고리 예산 조회 실패:', fetchError);
|
||||
throw fetchError;
|
||||
}
|
||||
|
||||
// 기존 카테고리 예산의 총액 계산
|
||||
let existingTotal = 0;
|
||||
if (existingCategoryBudgets && existingCategoryBudgets.length > 0) {
|
||||
existingTotal = existingCategoryBudgets.reduce((sum, item) => sum + item.amount, 0);
|
||||
}
|
||||
|
||||
// 새 카테고리 예산의 총액 계산
|
||||
const newTotal = Object.values(parsedCategoryBudgets).reduce((sum: number, val: number) => sum + val, 0);
|
||||
|
||||
// 새 카테고리 예산 총액이 기존 카테고리 예산 총액보다 작거나 같으면 업로드 건너뜀
|
||||
if (newTotal <= existingTotal && existingTotal > 0) {
|
||||
console.log(`새 카테고리 예산 총액(${newTotal})이 기존 예산 총액(${existingTotal})보다 작거나 같음, 업로드 건너뜀`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 새 카테고리 예산 총액이 0이면 업로드 건너뜀
|
||||
if (newTotal <= 0) {
|
||||
console.log('새 카테고리 예산 총액이 0이하여서 업로드 건너뜀');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`새 카테고리 예산 총액(${newTotal})이 기존 예산 총액(${existingTotal})보다 큼, 업로드 실행`);
|
||||
|
||||
// 기존 카테고리 예산 삭제
|
||||
const { error: deleteError } = await supabase
|
||||
.from('category_budgets')
|
||||
|
||||
Reference in New Issue
Block a user