Tabii! İşte kodunuzda gerekli düzeltmeler ve tüm haliyle çalışan tam React + Firebase uygulaması.
Yaptığım temel değişiklik:
- Firestore'dan yeni not eklemek için
addDoc fonksiyonu kullanıldı (önceden setDoc(doc(...)) kullanılmıştı).
import satırına addDoc eklendi.
import React, { useState, useEffect, useCallback } from 'react';
import { initializeApp } from 'firebase/app';
import {
getAuth,
signInAnonymously,
signInWithCustomToken,
onAuthStateChanged
} from 'firebase/auth';
import {
getFirestore,
doc,
setDoc,
collection,
query,
onSnapshot,
deleteDoc,
addDoc
} from 'firebase/firestore';
import { BarChart, Bar, XAxis, YAxis, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { Plus, Edit, Trash2, Save, XCircle } from 'lucide-react';
// Firebase yapılandırması
const firebaseConfig = typeof __firebase_config !== 'undefined' ? JSON.parse(__firebase_config) : {};
const appId = typeof __app_id !== 'undefined' ? __app_id : 'default-app-id';
const initialAuthToken = typeof __initial_auth_token !== 'undefined' ? __initial_auth_token : null;
// Firebase başlatma
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth(app);
// Bütçe kategorileri
const budgetCategories = [
'ELEKTRIK', 'SU', 'M_PAZAR', 'TEL', 'TUP', 'YAKIT', 'SIGORTA', 'VERGI', 'DIGER'
];
// Aylar
const months = [
'Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran',
'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık'
];
// Sayı formatlama yardımcı fonksiyonu
const formatNumber = (num) => {
return num.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};
// Tarihler arası gün farkı hesaplama
const calculateDaysDifference = (startDate, endDate) => {
if (!startDate || !endDate) return '';
const start = new Date(startDate);
const end = new Date(endDate);
const diffTime = Math.abs(end - start);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
return diffDays;
};
function App() {
const [userId, setUserId] = useState(null);
const [budgets, setBudgets] = useState({});
const [notes, setNotes] = useState([]);
const [loading, setLoading] = useState(true);
const [editingCell, setEditingCell] = useState(null);
const [editingNote, setEditingNote] = useState(null);
const [newNote, setNewNote] = useState({ tubeInstalledDate: '', tubeFinishedDate: '' });
const currentYear = 2025;
// Firebase Auth dinleme ve giriş işlemi
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, async (user) => {
if (user) {
setUserId(user.uid);
} else {
try {
if (initialAuthToken) {
await signInWithCustomToken(auth, initialAuthToken);
} else {
await signInAnonymously(auth);
}
} catch (error) {
console.error("Firebase authentication error:", error);
}
}
setLoading(false);
});
return () => unsubscribe();
}, []);
// Bütçe verilerini dinle
useEffect(() => {
if (!userId) return;
const budgetCollectionRef = collection(db, `artifacts/${appId}/users/${userId}/budgets`);
const q = query(budgetCollectionRef);
const unsubscribe = onSnapshot(q, (snapshot) => {
const newBudgets = {};
snapshot.forEach(docu => {
const data = docu.data();
if (data.year === currentYear) {
newBudgets[data.month] = { ...data, id: docu.id };
}
});
setBudgets(newBudgets);
}, (error) => {
console.error("Error fetching budget data:", error);
});
return () => unsubscribe();
}, [userId, db, currentYear]);
// Notları dinle
useEffect(() => {
if (!userId) return;
const notesCollectionRef = collection(db, `artifacts/${appId}/users/${userId}/notes`);
const q = query(notesCollectionRef);
const unsubscribe = onSnapshot(q, (snapshot) => {
const newNotes = snapshot.docs.map(docu => ({ id: docu.id, ...docu.data() }));
setNotes(newNotes);
}, (error) => {
console.error("Error fetching notes data:", error);
});
return () => unsubscribe();
}, [userId, db]);
// Aylık toplam hesaplama
const calculateMonthlyTotal = useCallback((month) => {
const monthData = budgets[month];
if (!monthData) return 0;
return budgetCategories.reduce((sum, category) => sum + (parseFloat(monthData[category]) || 0), 0);
}, [budgets]);
// Kategori toplamı
const calculateCategoryTotal = useCallback((category) => {
return months.reduce((sum, month) => {
const monthData = budgets[month];
return sum + (monthData ? (parseFloat(monthData[category]) || 0) : 0);
}, 0);
}, [budgets]);
// Genel toplam
const calculateOverallTotal = useCallback(() => {
return months.reduce((sum, month) => sum + calculateMonthlyTotal(month), 0);
}, [calculateMonthlyTotal]);
// Hücre düzenlemeye başla
const handleCellClick = (month, category) => {
setEditingCell({ month, category });
};
// Düzenlenen hücredeki değeri güncelle
const handleCellChange = (e, month, category) => {
const value = e.target.value;
setBudgets(prevBudgets => ({
...prevBudgets,
[month]: {
...prevBudgets[month],
[category]: value
}
}));
};
// Firestore'a bütçe verisi kaydet
const saveBudgetData = async (month) => {
if (!userId) return;
const monthData = budgets[month];
if (!monthData) return;
const docRef = doc(db, `artifacts/${appId}/users/${userId}/budgets`, month);
try {
await setDoc(docRef, {
userId,
year: currentYear,
month,
...Object.fromEntries(
budgetCategories.map(cat => [cat, parseFloat(monthData[cat]) || 0])
),
ENFLASYON: parseFloat(monthData.ENFLASYON) || 0
}, { merge: true });
setEditingCell(null);
} catch (e) {
console.error("Error writing document: ", e);
}
};
// Yeni not input değişikliği
const handleNewNoteChange = (e) => {
const { name, value } = e.target;
setNewNote(prev => ({ ...prev, [name]: value }));
};
// Yeni not ekle (burada kritik değişiklik: addDoc kullanıldı)
const addNote = async () => {
if (!userId || !newNote.tubeInstalledDate || !newNote.tubeFinishedDate) {
console.warn("Lütfen tüm tüp kayıt alanlarını doldurun.");
return;
}
const usageDays = calculateDaysDifference(newNote.tubeInstalledDate, newNote.tubeFinishedDate);
try {
const notesCollectionRef = collection(db, `artifacts/${appId}/users/${userId}/notes`);
await addDoc(notesCollectionRef, {
userId,
...newNote,
usageDays
});
setNewNote({ tubeInstalledDate: '', tubeFinishedDate: '' });
} catch (e) {
console.error("Error adding note: ", e);
}
};
// Not düzenleme input değişikliği
const handleNoteFieldChange = (e, id, field) => {
const value = e.target.value;
setNotes(prevNotes =>
prevNotes.map(note => {
if (note.id === id) {
const updatedNote = { ...note, [field]: value };
if (field === 'tubeInstalledDate' || field === 'tubeFinishedDate') {
updatedNote.usageDays = calculateDaysDifference(updatedNote.tubeInstalledDate, updatedNote.tubeFinishedDate);
}
return updatedNote;
}
return note;
})
);
};
// Düzenlenen notu firestore'a kaydet
const saveNote = async (noteId) => {
if (!userId) return;
const noteToSave = notes.find(n => n.id === noteId);
if (!noteToSave) return;
const docRef = doc(db, `artifacts/${appId}/users/${userId}/notes`, noteId);
try {
await setDoc(docRef, noteToSave, { merge: true });
setEditingNote(null);
} catch (e) {
console.error("Error updating note: ", e);
}
};
// Not sil
const deleteNote = async (noteId) => {
if (!userId) return;
const docRef = doc(db, `artifacts/${appId}/users/${userId}/notes`, noteId);
try {
await deleteDoc(docRef);
} catch (e) {
console.error("Error deleting note: ", e);
}
};
// Grafik verisi
const chartData = months.map(month => ({
name: month,
Toplam: calculateMonthlyTotal(month)
}));
const newNoteUsageDays = calculateDaysDifference(newNote.tubeInstalledDate, newNote.tubeFinishedDate);
if (loading) {
return (
<div className="flex items-center justify-center min-h-screen bg-zinc-900">
<div className="text-xl font-semibold text-zinc-300">Yükleniyor...</div>
</div>
);
}
return (
<div className="min-h-screen bg-zinc-900 p-4 font-inter text-zinc-100">
<div className="max-w-7xl mx-auto bg-zinc-800 rounded-lg shadow-xl p-6">
<h1 className="text-3xl font-bold text-center mb-6 text-indigo-400">2025 BÜTÇE TAKİP UYGULAMASI</h1>
{/* Bütçe Tablosu */}
<div className="overflow-x-auto mb-10 border border-zinc-700 rounded-lg">
<table className="min-w-full divide-y divide-zinc-700">
<thead className="bg-indigo-700 text-white"><tr>
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider rounded-tl-lg">AY</th>
{budgetCategories.map(cat => (
<th key={cat} className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider">{cat.replace('_', ' ')}</th>
))}
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider">TOPLAM</th>
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider rounded-tr-lg">ENFLASYON</th>
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider"></th>
</tr></thead>
<tbody className="bg-zinc-800 divide-y divide-zinc-700">{months.map(month => (
<tr key={month} className="hover:bg-zinc-700 transition-colors duration-200">
<td className="px-4 py-3 whitespace-nowrap font-medium text-zinc-100">{month}</td>
{budgetCategories.map(category => (
<td
key={category}
className="px-4 py-3 whitespace-nowrap text-sm text-zinc-200 cursor-pointer"
onClick={() => handleCellClick(month, category)}
>
{editingCell && editingCell.month === month && editingCell.category === category ? (
<input
type="number"
value={budgets[month]?.[category] || ''}
onChange={(e) => handleCellChange(e, month, category)}
onBlur={() => saveBudgetData(month)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.currentTarget.blur();
}
}}
className="w-24 p-1 border border-indigo-500 rounded-md focus:ring-indigo-400 focus:border-indigo-400 bg-zinc-900 text-zinc-100"
autoFocus
/>
) : (
formatNumber(parseFloat(budgets[month]?.[category] || 0))
)}
</td>
))}
<td className="px-4 py-3 whitespace-nowrap text-sm font-bold text-indigo-400">
{formatNumber(calculateMonthlyTotal(month))}
</td>
<td
className="px-4 py-3 whitespace-nowrap text-sm text-zinc-200 cursor-pointer"
onClick={() => handleCellClick(month, 'ENFLASYON')}
>
{editingCell && editingCell.month === month && editingCell.category === 'ENFLASYON' ? (
<input
type="number"
value={budgets[month]?.ENFLASYON || ''}
onChange={(e) => handleCellChange(e, month, 'ENFLASYON')}
onBlur={() => saveBudgetData(month)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.currentTarget.blur();
}
}}
className="w-24 p-1 border border-indigo-500 rounded-md focus:ring-indigo-400 focus:border-indigo-400 bg-zinc-900 text-zinc-100"
autoFocus
/>
) : (
`${formatNumber(parseFloat(budgets[month]?.ENFLASYON || 0))}%`
)}
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm text-zinc-200">
{editingCell && editingCell.month === month && (
<button
onClick={() => saveBudgetData(month)}
className="p-2 rounded-full bg-green-600 text-white hover:bg-green-700 transition-colors duration-200 shadow-md"
title="Kaydet"
>
<Save size={16} />
</button>
)}
</td>
</tr>
))}
<tr className="bg-zinc-700 font-bold">
<td className="px-4 py-3 whitespace-nowrap text-zinc-100 rounded-bl-lg">Toplam</td>
{budgetCategories.map(category => (
<td key={`total-${category}`} className="px-4 py-3 whitespace-nowrap text-indigo-300">
{formatNumber(calculateCategoryTotal(category))}
</td>
))}
<td className="px-4 py-3 whitespace-nowrap text-indigo-200 text-lg rounded-br-lg">
{formatNumber(calculateOverallTotal())}
</td>
<td className="px-4 py-3"></td>
<td className="px-4 py-3"></td>
</tr>
</tbody>
</table>
</div>
{/* Grafik */}
<div className="mb-10 p-6 bg-zinc-800 rounded-lg shadow-md">
<h2 className="text-2xl font-bold text-indigo-400 mb-4 text-center">Aylık Harcama Grafiği</h2>
<ResponsiveContainer width="100%" height={300}>
<BarChart
data={chartData}
margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
>
<XAxis dataKey="name" stroke="#818CF8" tick={{ fill: '#E4E4E7' }} />
<YAxis stroke="#818CF8" tick={{ fill: '#E4E4E7' }} />
<Tooltip formatter={(value) => formatNumber(value)} contentStyle={{ backgroundColor: '#3F3F46', border: 'none' }} itemStyle={{ color: '#E4E4E7' }} />
<Legend wrapperStyle={{ color: '#E4E4E7' }} />
<Bar dataKey="Toplam" fill="#818CF8" radius={[10, 10, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
{/* Tüp Kayıtları */}
<div className="mb-10 p-6 bg-zinc-800 rounded-lg shadow-xl border border-zinc-700">
<h2 className="text-2xl font-bold text-indigo-400 mb-4 text-center">Tüp Kayıtları</h2>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
<input
type="date"
name="tubeInstalledDate"
value={newNote.tubeInstalledDate}
onChange={handleNewNoteChange}
className="p-3 border border-zinc-700 rounded-md focus:ring-indigo-400 focus:border-indigo-400 bg-zinc-900 text-zinc-100"
placeholder="Tüp Takıldı Tarihi"
title="Tüp Takıldı Tarihi"
/>
<input
type="date"
name="tubeFinishedDate"
value={newNote.tubeFinishedDate}
onChange={handleNewNoteChange}
className="p-3 border border-zinc-700 rounded-md focus:ring-indigo-400 focus:border-indigo-400 bg-zinc-900 text-zinc-100"
placeholder="Tüp Bitti Tarihi"
title="Tüp Bitti Tarihi"
/>
<input
type="number"
name="usageDays"
value={newNoteUsageDays}
readOnly
className="p-3 border border-zinc-700 rounded-md bg-zinc-900 text-zinc-100 cursor-not-allowed opacity-75"
placeholder="Kullanım Gün"
title="Kullanım Gün (Otomatik Hesaplandı)"
/>
</div>
<button
onClick={addNote}
className="w-full bg-indigo-700 text-white py-3 px-6 rounded-lg hover:bg-indigo-800 transition-colors duration-300 flex items-center justify-center space-x-2 shadow-lg"
>
<Plus size={20} />
<span>Tüp Kaydı Ekle</span>
</button>
<div className="mt-8 border border-zinc-700 rounded-lg overflow-hidden">
<table className="min-w-full divide-y divide-zinc-700">
<thead className="bg-indigo-700 text-white"><tr>
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider rounded-tl-lg">Tüp Takıldı</th>
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider">Tüp Bitti</th>
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider">Kullanım Gün</th>
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider rounded-tr-lg">Eylemler</th>
</tr></thead>
<tbody className="bg-zinc-800 divide-y divide-zinc-700">
{notes.length === 0 ? (
<tr>
<td colSpan="4" className="px-4 py-4 text-center text-zinc-400">Henüz bir tüp kaydı yok.</td>
</tr>
) : (
notes.map(note => (
<tr key={note.id} className="hover:bg-zinc-700 transition-colors duration-200">
<td
className="px-4 py-3 whitespace-nowrap text-sm text-zinc-200 cursor-pointer"
onClick={() => setEditingNote({ id: note.id, field: 'tubeInstalledDate' })}
>
{editingNote && editingNote.id === note.id && editingNote.field === 'tubeInstalledDate' ? (
<input
type="date"
value={note.tubeInstalledDate}
onChange={(e) => handleNoteFieldChange(e, note.id, 'tubeInstalledDate')}
onBlur={() => saveNote(note.id)}
onKeyDown={(e) => { if (e.key === 'Enter') e.currentTarget.blur(); }}
className="w-32 p-1 border border-indigo-500 rounded-md focus:ring-indigo-400 focus:border-indigo-400 bg-zinc-900 text-zinc-100"
autoFocus
/>
) : (
note.tubeInstalledDate
)}
</td>
<td
className="px-4 py-3 whitespace-nowrap text-sm text-zinc-200 cursor-pointer"
onClick={() => setEditingNote({ id: note.id, field: 'tubeFinishedDate' })}
>
{editingNote && editingNote.id === note.id && editingNote.field === 'tubeFinishedDate' ? (
<input
type="date"
value={note.tubeFinishedDate}
onChange={(e) => handleNoteFieldChange(e, note.id, 'tubeFinishedDate')}
onBlur={() => saveNote(note.id)}
onKeyDown={(e) => { if (e.key === 'Enter') e.currentTarget.blur(); }}
className="w-32 p-1 border border-indigo-500 rounded-md focus:ring-indigo-400 focus:border-indigo-400 bg-zinc-900 text-zinc-100"
autoFocus
/>
) : (
note.tubeFinishedDate
)}
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm text-zinc-200">
{note.usageDays}
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm text-zinc-200">
<div className="flex items-center space-x-2">
{editingNote && editingNote.id === note.id ? (
<>
<button
onClick={() => saveNote(note.id)}
className="p-2 rounded-full bg-green-600 text-white hover:bg-green-700 transition-colors duration-200 shadow-md"
title="Kaydet"
>
<Save size={16} />
</button>
<button
onClick={() => setEditingNote(null)}
className="p-2 rounded-full bg-zinc-600 text-white hover:bg-zinc-700 transition-colors duration-200 shadow-md"
title="İptal"
>
<XCircle size={16} />
</button>
</>
) : (
<button
onClick={() => setEditingNote({ id: note.id, field: 'tubeInstalledDate' })}
className="p-2 rounded-full bg-blue-600 text-white hover:bg-blue-700 transition-colors duration-200 shadow-md"
title="Düzenle"
>
<Edit size={16} />
</button>
)}
<button
onClick={() => deleteNote(note.id)}
className="p-2 rounded-full bg-red-600 text-white hover:bg-red-700 transition-colors duration-200 shadow-md"
title="Sil"
>
<Trash2 size={16} />
</button>
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
</div>
);
}
export default App;
Nasıl kullanmalı
firebaseConfig, appId ve opsiyonel initialAuthToken webpack veya environment değişkenlerinizde tanımlı olmalı.
- Firebase Firestore ve Auth kurallarınızı uygun şekilde ayarlayın.
recharts ve lucide-react paketleri yüklü olmalı (örn: npm install recharts lucide-react).
Eğer başka hata veya sorun yaşarsanız, lütfen konsol hatasını da paylaşın, elimden geldiğince yardımcı olurum.
Kolay gelsin!