Spaces:
Sleeping
Sleeping
File size: 7,331 Bytes
547e29e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | // β
Fetch Transactions from API and Update UI
async function loadTransactions() {
const response = await fetch("/api/transactions");
const transactions = await response.json();
// β
Populate Transaction Table
document.getElementById("transactions").innerHTML = transactions
.map(t => `
<tr>
<td>$${t.amount}</td>
<td>${t.date}</td>
<td>${t.description}</td>
<td>${t.category}</td>
<td><button onclick="deleteTransaction(${t.id})">Delete</button></td>
</tr>
`).join("");
updateChart(transactions);
updateDashboard(transactions);
loadBudgetChart();
loadSpendingInsights();
loadMonthlyExpensesChart();
}
// β
Add Transaction with Validation
async function addTransaction() {
const amount = document.getElementById("amount").value;
const date = document.getElementById("date").value;
const description = document.getElementById("description").value;
const category = document.getElementById("category").value;
// Validation
if (!amount || !date || !description || !category) {
alert("Please fill in all fields!");
return;
}
const data = { amount, date, description, category };
await fetch("/api/transactions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
// Clear input fields after submission
document.getElementById("amount").value = "";
document.getElementById("date").value = "";
document.getElementById("description").value = "";
loadTransactions();
}
// β
Delete Transaction
async function deleteTransaction(id) {
await fetch(`/api/transactions/${id}`, { method: "DELETE" });
loadTransactions();
}
// β
Set Budget for a Category
async function setBudget() {
const category = document.getElementById("budget-category").value;
const amount = document.getElementById("budget-amount").value;
if (!amount) {
alert("Please enter a budget amount!");
return;
}
await fetch("/api/budget", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ category, amount })
});
alert("Budget set successfully!");
loadBudgetChart();
}
// β
Load Budget vs Actual Spending Chart
async function loadBudgetChart() {
const transactions = await (await fetch("/api/transactions")).json();
const budgets = await (await fetch("/api/budget")).json();
const actualSpending = {};
const budgetLimits = {};
transactions.forEach(t => {
actualSpending[t.category] = (actualSpending[t.category] || 0) + t.amount;
});
budgets.forEach(b => {
budgetLimits[b.category] = b.amount;
});
const categories = Array.from(new Set([...Object.keys(actualSpending), ...Object.keys(budgetLimits)]));
const actualData = categories.map(cat => actualSpending[cat] || 0);
const budgetData = categories.map(cat => budgetLimits[cat] || 0);
const ctx = document.getElementById('budgetChart').getContext('2d');
if (window.budgetChartInstance) {
window.budgetChartInstance.destroy();
}
window.budgetChartInstance = new Chart(ctx, {
type: 'bar',
data: {
labels: categories,
datasets: [
{ label: "Actual Spending", data: actualData, backgroundColor: "red" },
{ label: "Budget Limit", data: budgetData, backgroundColor: "green" }
]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
}
// β
Load Monthly Expenses Bar Chart
async function loadMonthlyExpensesChart() {
const transactions = await (await fetch("/api/transactions")).json();
const monthlyTotals = {};
transactions.forEach(t => {
const month = t.date.substring(0, 7);
monthlyTotals[month] = (monthlyTotals[month] || 0) + t.amount;
});
const months = Object.keys(monthlyTotals).sort();
const monthlyData = months.map(month => monthlyTotals[month]);
const ctx = document.getElementById('monthlyExpensesChart').getContext('2d');
if (window.monthlyChartInstance) {
window.monthlyChartInstance.destroy();
}
window.monthlyChartInstance = new Chart(ctx, {
type: 'bar',
data: {
labels: months,
datasets: [
{
label: "Monthly Expenses",
data: monthlyData,
backgroundColor: "#007BFF"
}
]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
}
// β
Load Spending Insights
async function loadSpendingInsights() {
const response = await fetch("/api/spending-insights");
const insights = await response.json();
let insightsText = "";
for (const [category, message] of Object.entries(insights)) {
insightsText += `<p>${category}: ${message}</p>`;
}
document.getElementById("spendingInsights").innerHTML = insightsText;
}
// β
Update Pie Chart for Category-wise Spending
let expenseChart;
function updateChart(transactions) {
const ctx = document.getElementById('expenseChart').getContext('2d');
const categoryTotals = transactions.reduce((acc, t) => {
acc[t.category] = (acc[t.category] || 0) + t.amount;
return acc;
}, {});
if (expenseChart) {
expenseChart.destroy();
}
expenseChart = new Chart(ctx, {
type: 'pie',
data: {
labels: Object.keys(categoryTotals),
datasets: [{
data: Object.values(categoryTotals),
backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56", "#4CAF50", "#FF9F40", "#9966FF"]
}]
}
});
}
// β
Update Dashboard Summary (Total Expenses, Top Category, Recent Transaction)
function updateDashboard(transactions) {
let totalExpenses = transactions.reduce((sum, t) => sum + t.amount, 0);
let categoryTotals = transactions.reduce((acc, t) => {
acc[t.category] = (acc[t.category] || 0) + t.amount;
return acc;
}, {});
let topCategory = Object.keys(categoryTotals).reduce((a, b) => categoryTotals[a] > categoryTotals[b] ? a : b, "None");
let recentTransaction = transactions.length > 0 ? transactions[transactions.length - 1].description : "None";
document.getElementById("totalExpenses").innerText = `$${totalExpenses.toFixed(2)}`;
document.getElementById("topCategory").innerText = topCategory;
document.getElementById("recentTransaction").innerText = recentTransaction;
}
// β
Load All Data on Page Load
window.onload = function () {
loadTransactions();
loadBudgetChart();
loadSpendingInsights();
loadMonthlyExpensesChart();
}; |