Refactor data initialization process

Review and adjust the data initialization logic to ensure proper functionality.
This commit is contained in:
gpt-engineer-app[bot]
2025-03-16 07:52:45 +00:00
parent 23ba0f7e90
commit c5a5a20d36
6 changed files with 342 additions and 247 deletions

View File

@@ -13,11 +13,21 @@ export const useBudgetReset = (
try {
console.log('BudgetContext에서 데이터 리셋 시작');
// 로컬 스토리지 초기화
// 데이터 초기화 순서 중요
resetTransactions();
resetCategoryBudgets();
resetBudgetDataInternal();
// 이벤트 발생
try {
window.dispatchEvent(new Event('transactionUpdated'));
window.dispatchEvent(new Event('budgetDataUpdated'));
window.dispatchEvent(new Event('categoryBudgetsUpdated'));
window.dispatchEvent(new StorageEvent('storage'));
} catch (e) {
console.error('이벤트 발생 오류:', e);
}
console.log('BudgetContext에서 데이터 리셋 완료');
// 토스트 알림
@@ -25,6 +35,8 @@ export const useBudgetReset = (
title: "모든 데이터 초기화",
description: "예산과 지출 내역이 모두 초기화되었습니다.",
});
return true;
} catch (error) {
console.error('데이터 초기화 중 오류:', error);
toast({
@@ -32,6 +44,8 @@ export const useBudgetReset = (
description: "데이터를 초기화하는 중 오류가 발생했습니다.",
variant: "destructive"
});
return false;
}
}, [resetTransactions, resetCategoryBudgets, resetBudgetDataInternal]);

View File

@@ -10,31 +10,43 @@ export const loadBudgetDataFromStorage = (): BudgetData => {
try {
const storedBudgetData = localStorage.getItem('budgetData');
if (storedBudgetData) {
const parsed = JSON.parse(storedBudgetData);
console.log('예산 데이터 로드 완료', parsed);
// 데이터 유효성 검사 추가
if (!parsed || !parsed.monthly || !parsed.daily || !parsed.weekly) {
throw new Error('잘못된 형식의 예산 데이터');
try {
const parsed = JSON.parse(storedBudgetData);
console.log('예산 데이터 로드 완료', parsed);
// 데이터 유효성 검사 추가
if (!parsed || !parsed.monthly || !parsed.daily || !parsed.weekly) {
console.warn('불완전한 예산 데이터, 백업에서 복구 시도');
throw new Error('잘못된 형식의 예산 데이터');
}
return parsed;
} catch (error) {
console.error('예산 데이터 파싱 오류:', error);
// 백업에서 복구 시도
const backupData = localStorage.getItem('budgetData_backup');
if (backupData) {
try {
const parsed = JSON.parse(backupData);
console.log('백업에서 예산 데이터 복구 완료', parsed);
// 백업 데이터 유효성 검사
if (!parsed || !parsed.monthly || !parsed.daily || !parsed.weekly) {
console.warn('백업 예산 데이터도 불완전함, 새 데이터 생성');
throw new Error('백업 데이터도 잘못된 형식');
}
localStorage.setItem('budgetData', backupData); // 메인 스토리지에 복구
return parsed;
} catch (backupError) {
console.error('백업 데이터 복구 실패:', backupError);
}
}
}
return parsed;
}
} catch (error) {
console.error('예산 데이터 파싱 오류:', error);
// 백업에서 복구 시도
try {
const backupData = localStorage.getItem('budgetData_backup');
if (backupData) {
const parsed = JSON.parse(backupData);
console.log('백업에서 예산 데이터 복구 완료', parsed);
localStorage.setItem('budgetData', backupData); // 메인 스토리지에 저장
return parsed;
}
} catch (backupError) {
console.error('백업 데이터 복구 실패:', backupError);
}
console.error('예산 데이터 로드 중 오류:', error);
}
// 새 사용자를 위한 기본 예산 데이터 저장
@@ -49,6 +61,12 @@ export const loadBudgetDataFromStorage = (): BudgetData => {
*/
export const saveBudgetDataToStorage = (budgetData: BudgetData): void => {
try {
// 유효성 검사
if (!budgetData || !budgetData.monthly || !budgetData.daily || !budgetData.weekly) {
console.error('잘못된 예산 데이터 저장 시도:', budgetData);
throw new Error('잘못된 예산 데이터');
}
// 데이터 문자열로 변환
const dataString = JSON.stringify(budgetData);
@@ -60,7 +78,7 @@ export const saveBudgetDataToStorage = (budgetData: BudgetData): void => {
localStorage.setItem('budgetData_backup', dataString);
localStorage.setItem('lastBudgetSaveTime', new Date().toISOString());
// 스토리지 이벤트 수동 트리거 (동일 창에서도 감지하기 위함)
// 이벤트 발생
try {
window.dispatchEvent(new Event('budgetDataUpdated'));
window.dispatchEvent(new StorageEvent('storage', {
@@ -70,8 +88,8 @@ export const saveBudgetDataToStorage = (budgetData: BudgetData): void => {
} catch (e) {
console.error('이벤트 발생 오류:', e);
}
// toast 알림은 즉시 표시
// toast 알림
if (budgetData.monthly.targetAmount > 0) {
toast({
title: "예산 저장 완료",
@@ -106,18 +124,21 @@ export const clearAllBudgetData = (): void => {
console.log('예산 데이터가 초기화되었습니다.');
// 스토리지 이벤트 수동 트리거
// 이벤트 발생
window.dispatchEvent(new Event('budgetDataUpdated'));
window.dispatchEvent(new StorageEvent('storage', {
key: 'budgetData',
newValue: dataString
}));
// 토스트 알림
toast({
title: "예산 초기화",
description: "모든, 예산 데이터가 초기화되었습니다.",
});
// 토스트 알림 (사용자가 직접 초기화한 경우만)
const isUserInitiated = document.visibilityState === 'visible';
if (isUserInitiated) {
toast({
title: "예산 초기화",
description: "모든 예산 데이터가 초기화되었습니다.",
});
}
} catch (error) {
console.error('예산 데이터 삭제 오류:', error);
toast({

View File

@@ -12,10 +12,10 @@ import { toast } from '@/components/ui/use-toast';
export const resetAllData = (): void => {
console.log('완전 초기화 시작 - resetAllData');
// dontShowWelcome 설정 값 백업
// 중요: 사용자 설정 관련 값 백업
const dontShowWelcomeValue = localStorage.getItem('dontShowWelcome');
const hasVisitedBefore = localStorage.getItem('hasVisitedBefore');
console.log('resetAllData - dontShowWelcome 백업 값:', dontShowWelcomeValue);
console.log('resetAllData - 사용자 설정 백업:', { dontShowWelcome: dontShowWelcomeValue, hasVisitedBefore });
// 모든 관련 데이터 키 목록 (분석 페이지의 데이터 포함)
const dataKeys = [
@@ -35,79 +35,68 @@ export const resetAllData = (): void => {
'weeklyBudget', // 주간 예산
'monthlyBudget', // 월간 예산
'chartData', // 차트 데이터
// 'hasVisitedBefore', // 방문 여부 - 제외
// 'dontShowWelcome' 키는 삭제 목록에서 제외
];
// 모든 관련 데이터 키 삭제
dataKeys.forEach(key => {
console.log(`삭제 중: ${key}`);
localStorage.removeItem(key);
});
// 기본 데이터로 초기화
clearAllTransactions();
clearAllCategoryBudgets();
clearAllBudgetData();
// 추가적으로 사용자 기기에 저장된 모든 데이터 검사 (역순으로 루프)
for (let i = localStorage.length - 1; i >= 0; i--) {
const key = localStorage.key(i);
if (key &&
key !== 'dontShowWelcome' &&
key !== 'hasVisitedBefore' && // hasVisitedBefore 키도 제외
(key.includes('expense') ||
key.includes('budget') ||
key.includes('transaction') ||
key.includes('analytics') ||
key.includes('spending') ||
key.includes('financial') ||
key.includes('chart') ||
key.includes('month') ||
key.includes('sync') ||
key.includes('total'))
) {
console.log(`추가 데이터 삭제: ${key}`);
localStorage.removeItem(key);
}
}
// 강제로 빈 데이터로 초기화
localStorage.setItem('transactions', JSON.stringify([]));
localStorage.setItem('budget', JSON.stringify({total: 0}));
const initialBudgetData = getInitialBudgetData();
localStorage.setItem('budgetData', JSON.stringify(initialBudgetData));
localStorage.setItem('categoryBudgets', JSON.stringify(DEFAULT_CATEGORY_BUDGETS));
// 이벤트 발생시켜 데이터 로드 트리거
try {
window.dispatchEvent(new Event('transactionUpdated'));
window.dispatchEvent(new Event('budgetDataUpdated'));
window.dispatchEvent(new Event('categoryBudgetsUpdated'));
window.dispatchEvent(new StorageEvent('storage'));
} catch (e) {
console.error('이벤트 발생 오류:', e);
}
// dontShowWelcome 값 복원 (백업한 값이 있는 경우)
if (dontShowWelcomeValue) {
console.log('resetAllData - dontShowWelcome 값 복원:', dontShowWelcomeValue);
localStorage.setItem('dontShowWelcome', dontShowWelcomeValue);
}
// hasVisitedBefore 값 복원 (백업한 값이 있는 경우)
if (hasVisitedBefore) {
console.log('resetAllData - hasVisitedBefore 값 복원:', hasVisitedBefore);
localStorage.setItem('hasVisitedBefore', hasVisitedBefore);
}
// 초기화 알림은 첫 방문인 경우에는 표시하지 않음
if (hasVisitedBefore === 'true') {
// 모든 관련 데이터 키 삭제
dataKeys.forEach(key => {
console.log(`삭제 중: ${key}`);
localStorage.removeItem(key);
});
// 파일별 초기화 함수 호출
clearAllTransactions();
clearAllCategoryBudgets();
clearAllBudgetData();
// 기본 데이터로 초기화 (중복 삭제 방지를 위해 한 번만 실행)
const initialBudgetData = getInitialBudgetData();
localStorage.setItem('budgetData', JSON.stringify(initialBudgetData));
localStorage.setItem('categoryBudgets', JSON.stringify(DEFAULT_CATEGORY_BUDGETS));
localStorage.setItem('transactions', JSON.stringify([]));
// 중요: budgetData_backup도 설정하여 복구 가능하게 함
localStorage.setItem('budgetData_backup', JSON.stringify(initialBudgetData));
localStorage.setItem('categoryBudgets_backup', JSON.stringify(DEFAULT_CATEGORY_BUDGETS));
localStorage.setItem('transactions_backup', JSON.stringify([]));
// 이벤트 발생시켜 데이터 로드 트리거
try {
window.dispatchEvent(new Event('transactionUpdated'));
window.dispatchEvent(new Event('budgetDataUpdated'));
window.dispatchEvent(new Event('categoryBudgetsUpdated'));
window.dispatchEvent(new StorageEvent('storage'));
} catch (e) {
console.error('이벤트 발생 오류:', e);
}
// 중요: 사용자 설정 값 복원 (백업한 값이 있는 경우)
if (dontShowWelcomeValue) {
console.log('resetAllData - dontShowWelcome 값 복원:', dontShowWelcomeValue);
localStorage.setItem('dontShowWelcome', dontShowWelcomeValue);
}
if (hasVisitedBefore) {
console.log('resetAllData - hasVisitedBefore 값 복원:', hasVisitedBefore);
localStorage.setItem('hasVisitedBefore', hasVisitedBefore);
}
// 첫 방문이 아닌 경우에만 토스트 알림 표시
if (hasVisitedBefore === 'true') {
toast({
title: "데이터 초기화 완료",
description: "모든 예산 및 지출 데이터가 초기화되었습니다.",
});
}
console.log('모든 데이터가 초기화되었습니다.');
} catch (error) {
console.error('데이터 초기화 중 오류 발생:', error);
// 오류 발생 시 토스트 알림
toast({
title: "데이터 초기화 완료",
description: "모든 예산 및 지출 데이터 초기화되었습니다.",
title: "초기화 실패",
description: "데이터 초기화하는데 문제가 발생했습니다.",
variant: "destructive"
});
}
console.log('모든 데이터가 초기화되었습니다.');
};