Clear persistent budget data

Clear persistent budget data to ensure a clean state.
This commit is contained in:
gpt-engineer-app[bot]
2025-03-15 23:03:44 +00:00
parent 2ba8fdc31b
commit f8abebcac6
4 changed files with 166 additions and 78 deletions

View File

@@ -2,14 +2,14 @@
import { BudgetData, BudgetPeriod, CategoryBudget, Transaction } from './types';
import { EXPENSE_CATEGORIES } from '@/constants/categoryIcons';
// 기본 데이터 상수
// 기본 데이터 상수 (기본값을 0으로 변경)
export const DEFAULT_CATEGORY_BUDGETS: Record<string, number> = {
식비: 400000,
생활비: 600000,
교통비: 200000
식비: 0,
생활비: 0,
교통비: 0
};
export const DEFAULT_MONTHLY_BUDGET = 1200000;
export const DEFAULT_MONTHLY_BUDGET = 0;
// 카테고리별 지출 계산
export const calculateCategorySpending = (
@@ -126,19 +126,19 @@ export const calculateSpentAmounts = (
export const getInitialBudgetData = (): BudgetData => {
return {
daily: {
targetAmount: Math.round(DEFAULT_MONTHLY_BUDGET / 30),
targetAmount: 0,
spentAmount: 0,
remainingAmount: Math.round(DEFAULT_MONTHLY_BUDGET / 30)
remainingAmount: 0
},
weekly: {
targetAmount: Math.round(DEFAULT_MONTHLY_BUDGET / 4.3),
targetAmount: 0,
spentAmount: 0,
remainingAmount: Math.round(DEFAULT_MONTHLY_BUDGET / 4.3)
remainingAmount: 0
},
monthly: {
targetAmount: DEFAULT_MONTHLY_BUDGET,
targetAmount: 0,
spentAmount: 0,
remainingAmount: DEFAULT_MONTHLY_BUDGET
remainingAmount: 0
}
};
};

View File

@@ -20,7 +20,7 @@ const Analytics = () => {
const savings = Math.max(0, totalBudget - totalExpense);
const savingsPercentage = totalBudget > 0 ? Math.round(savings / totalBudget * 100) : 0;
// 카테고리별 지출 차트 데이터 생성 (실제 데이터 사용)
// 카테고리별 지출 차트 데이터 생성 (데이터 초기화 고려)
const categorySpending = getCategorySpending();
const expenseData = categorySpending.map(category => ({
name: category.title,
@@ -30,30 +30,33 @@ const Analytics = () => {
category.title === '교통비' ? '#2E7D32' : '#4CAF50'
}));
// 최근 6개월 데이터를 위한 상태
// 최근 6개월 데이터를 위한 상태 (빈 데이터로 초기화)
const [monthlyData, setMonthlyData] = useState<any[]>([]);
// 월별 데이터 생성 (실제 데이터 + 예상 데이터)
// 월별 데이터 생성 (초기화 로직 개선)
useEffect(() => {
// 현재 월 가져오기
const today = new Date();
const currentMonth = today.getMonth();
if (totalBudget === 0 && totalExpense === 0) {
// 모든 데이터가 초기화된 상태라면 빈 배열 사용
setMonthlyData([]);
return;
}
// 최근 6개월 데이터 배열 생성
const last6Months = [];
for (let i = 5; i >= 0; i--) {
const monthIndex = (currentMonth - i + 12) % 12; // 순환적으로 이전 월 계산
const month = MONTHS_KR[monthIndex]; // 월 이름 가져오기
// 현재 달은 실제 데이터 사용, 이전 달은 예상 데이터 사용
const isCurrentMonth = i === 0;
const expense = isCurrentMonth
? totalExpense
: totalBudget * (0.5 + Math.random() * 0.3); // 예상 데이터 (총 예산의 50~80%)
// 현재 달은 실제 데이터 사용, 다른 달은 0으로 설정
const expense = i === 0 ? totalExpense : 0;
last6Months.push({
name: month.split(' ')[0], // '8월' 형식으로 변환
budget: totalBudget,
budget: i === 0 ? totalBudget : 0,
expense: expense
});
}
@@ -85,6 +88,14 @@ const Analytics = () => {
console.log('다음 기간으로 이동');
};
// 그래프 데이터 없을 때 표시할 빈 상태 메시지
const EmptyGraphState = () => (
<div className="flex flex-col items-center justify-center h-48 text-gray-400">
<p> </p>
<p className="text-sm mt-2"> </p>
</div>
);
return (
<div className="min-h-screen bg-neuro-background pb-24">
<div className="max-w-md mx-auto px-6">
@@ -149,54 +160,70 @@ const Analytics = () => {
<div className="mb-8">
<h2 className="text-lg font-semibold mb-3"> </h2>
<div className="neuro-card h-72">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={monthlyData} margin={{
top: 20,
right: 10,
left: -10,
bottom: 5
}} style={{
fontSize: '11px'
}}>
<XAxis dataKey="name" />
<YAxis tickFormatter={formatYAxisTick} />
<Tooltip formatter={formatTooltip} />
<Legend />
<Bar dataKey="budget" name="예산" fill="#C8C8C9" radius={[4, 4, 0, 0]} />
<Bar dataKey="expense" name="지출" fill="#81c784" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
{monthlyData.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<BarChart data={monthlyData} margin={{
top: 20,
right: 10,
left: -10,
bottom: 5
}} style={{
fontSize: '11px'
}}>
<XAxis dataKey="name" />
<YAxis tickFormatter={formatYAxisTick} />
<Tooltip formatter={formatTooltip} />
<Legend />
<Bar dataKey="budget" name="예산" fill="#C8C8C9" radius={[4, 4, 0, 0]} />
<Bar dataKey="expense" name="지출" fill="#81c784" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
) : (
<EmptyGraphState />
)}
</div>
</div>
{/* Category Pie Chart - MOVED DOWN */}
<h2 className="text-lg font-semibold mb-3"> </h2>
<ExpenseChart data={expenseData} />
{expenseData.some(item => item.value > 0) ? (
<ExpenseChart data={expenseData} />
) : (
<div className="neuro-card h-52 flex items-center justify-center text-gray-400">
<p> </p>
</div>
)}
{/* Top Spending Categories */}
<h2 className="text-lg font-semibold mb-3 mt-6"> </h2>
<div className="neuro-card mb-6">
<div className="space-y-4">
{categorySpending.map((category) => (
<div key={category.title} className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-6 h-6 rounded-full" style={{
backgroundColor: category.title === '식비' ? '#81c784' :
category.title === '생활비' ? '#AED581' : '#2E7D32'
}}></div>
<span>{category.title}</span>
{categorySpending.some(cat => cat.current > 0) ? (
<div className="space-y-4">
{categorySpending.map((category) => (
<div key={category.title} className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-6 h-6 rounded-full" style={{
backgroundColor: category.title === '비' ? '#81c784' :
category.title === '생활비' ? '#AED581' : '#2E7D32'
}}></div>
<span>{category.title}</span>
</div>
<div className="text-right">
<p className="font-medium">
{formatCurrency(category.current)}
</p>
<p className="text-xs text-gray-500">
{totalExpense > 0 ? Math.round(category.current / totalExpense * 100) : 0}%
</p>
</div>
</div>
<div className="text-right">
<p className="font-medium">
{formatCurrency(category.current)}
</p>
<p className="text-xs text-gray-500">
{totalExpense > 0 ? Math.round(category.current / totalExpense * 100) : 0}%
</p>
</div>
</div>
))}
</div>
))}
</div>
) : (
<div className="py-8 text-center text-gray-400">
<p> </p>
</div>
)}
</div>
</div>

View File

@@ -27,14 +27,32 @@ const Index = () => {
const { user } = useAuth();
const [showWelcome, setShowWelcome] = useState(false);
const [isInitialized, setIsInitialized] = useState(false);
// 화면이 처음 로드될 때 데이터 초기화
useEffect(() => {
// 데이터를 완전히 초기화 (두 가지 초기화 함수 모두 호출)
resetAllData();
resetAllStorageData();
if (!isInitialized) {
// 모든 데이터 완전히 삭제 및 초기화 (두 가지 초기화 함수 모두 반복 호출)
resetAllData();
resetAllStorageData();
resetAllData(); // 한번 더 실행해서 확실히 지움
// 환영 다이얼로그 표시 여부 결정
// localStorage 직접 초기화 (추가 보호)
localStorage.removeItem('budget');
localStorage.removeItem('budgetData');
localStorage.removeItem('categoryBudgets');
localStorage.removeItem('transactions');
localStorage.removeItem('monthlyExpenses');
localStorage.removeItem('monthlyData');
// 데이터를 비운 후 빈 값 저장
localStorage.setItem('transactions', JSON.stringify([]));
setIsInitialized(true);
console.log('모든 데이터 초기화 완료');
}
// 환영 다이얼로그 표시 여부 결정 (데이터 초기화 후)
const dontShowWelcome = localStorage.getItem('dontShowWelcome') === 'true';
if (!dontShowWelcome) {
setShowWelcome(true);
@@ -42,7 +60,7 @@ const Index = () => {
// 방문 기록 저장 (초기화 후에 저장)
localStorage.setItem('hasVisitedBefore', 'true');
}, []);
}, [isInitialized]);
// 환영 팝업 닫기
const handleCloseWelcome = (dontShowAgain: boolean) => {
@@ -52,6 +70,14 @@ const Index = () => {
}
};
// 빈 데이터 상태 메시지
const EmptyState = () => (
<div className="neuro-card py-8 text-center text-gray-400 mb-4">
<p> </p>
<p className="text-sm mt-2"> </p>
</div>
);
return (
<div className="min-h-screen bg-neuro-background pb-24">
<div className="max-w-md mx-auto px-6">
@@ -69,13 +95,24 @@ const Index = () => {
/>
{/* 지출 카테고리 */}
<BudgetCategoriesSection categories={getCategorySpending()} />
{getCategorySpending().some(cat => cat.current > 0 || cat.total > 0) ? (
<BudgetCategoriesSection categories={getCategorySpending()} />
) : (
<EmptyState />
)}
{/* 최근 지출 */}
<RecentTransactionsSection
transactions={transactions.slice(0, 5)}
onUpdateTransaction={updateTransaction}
/>
{transactions.length > 0 ? (
<RecentTransactionsSection
transactions={transactions.slice(0, 5)}
onUpdateTransaction={updateTransaction}
/>
) : (
<div className="mt-4">
<h2 className="text-lg font-semibold mb-3"> </h2>
<EmptyState />
</div>
)}
</div>
<AddTransactionButton />
<NavBar />

View File

@@ -26,23 +26,47 @@ export const loadBudgetFromStorage = (): number => {
const budgetData = localStorage.getItem('budget');
if (budgetData) {
const parsedBudget = JSON.parse(budgetData);
return parsedBudget.total || 1000000;
return parsedBudget.total || 0; // 기본값을 0으로 변경
}
return 1000000; // 기본 예산
return 0; // 기본값 0으로 변경
};
// 모든 데이터 완전히 초기화
export const resetAllStorageData = (): void => {
// 트랜잭션 초기화
localStorage.removeItem('transactions');
// 모든 Storage 키 삭제
const keysToRemove = [
'transactions',
'budget',
'monthlyExpenses',
'budgetData',
'categoryBudgets',
'analyticData',
'expenseData',
'chartData',
'monthlyData',
'spendingData'
];
// 명시적으로 알려진 키들 삭제
keysToRemove.forEach(key => localStorage.removeItem(key));
// 명시적으로 트랜잭션 초기화
localStorage.setItem('transactions', JSON.stringify([]));
// 월별 지출 데이터 초기화
localStorage.removeItem('monthlyExpenses');
// 모든 예산 관련, 지출 관련 데이터 검색 및 삭제
const keywordsToFind = ['budget', 'expense', 'transaction', 'analytic', 'spending', 'chart', 'financial', 'money', 'category'];
// 예산 초기화
localStorage.removeItem('budget');
// 모든 localStorage 순회하며 키워드 포함된 항목 삭제
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key) {
const lowerKey = key.toLowerCase();
if (keywordsToFind.some(keyword => lowerKey.includes(keyword))) {
console.log(`추가 데이터 삭제: ${key}`);
localStorage.removeItem(key);
}
}
}
console.log('모든 저장소 데이터가 초기화되었습니다.');
console.log('모든 저장소 데이터가 완전히 초기화되었습니다.');
};