Dashboard Temp Share Shortlinks Frames API

HTMLify

script.js
Views: 16 | Author: karbonsites
  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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
const STORAGE_KEY = 'expenseTrackerData';

// --- Utility Functions ---
const getLocalStorage = () => {
    try {
        const data = localStorage.getItem(STORAGE_KEY);
        return data ? JSON.parse(data) : {
            transactions: [],
            initialized: false
        };
    } catch (e) {
        console.error("Error reading localStorage", e);
        return { transactions: [], initialized: false };
    }
};

const setLocalStorage = (data) => {
    try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    } catch (e) {
        console.error("Error writing to localStorage", e);
    }
};

const formatCurrency = (amount) => {
    // MODIFIED: Changed currency to INR
    return new Intl.NumberFormat('en-IN', {
        style: 'currency',
        currency: 'INR',
    }).format(amount);
};

const formatDate = (dateString) => {
    const date = new Date(dateString);
    // Using 'en-IN' locale for better date formatting consistency if desired, but keeping standard output for compatibility.
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
};

// --- Initialization & Data Management ---

const initializeData = () => {
    const storedData = getLocalStorage();
    if (!storedData.initialized) {
        // Seed some initial data for demonstration
        const today = new Date();
        const lastMonth = new Date(today.setMonth(today.getMonth() - 1));
        storedData.transactions = [
            { id: Date.now() + 1, description: "Monthly Rent", amount: 35000.00, type: "expense", category: "Bills", date: new Date(lastMonth.setDate(1)).toISOString().split('T')[0] },
            { id: Date.now() + 2, description: "Freelance Payment", amount: 50000.00, type: "income", category: "Salary", date: new Date(lastMonth.setDate(15)).toISOString().split('T')[0] },
            { id: Date.now() + 3, description: "Groceries", amount: 2500.50, type: "expense", category: "Food", date: new Date().toISOString().split('T')[0] },
            { id: Date.now() + 4, description: "Movie Tickets", amount: 800.00, type: "expense", category: "Entertainment", date: new Date().toISOString().split('T')[0] },
        ];
        storedData.initialized = true;
        setLocalStorage(storedData);
    }
    return storedData.transactions;
};

let transactions = initializeData();

const saveTransaction = (newTransaction) => {
    const data = getLocalStorage();
    data.transactions.push(newTransaction);
    setLocalStorage(data);
    transactions = data.transactions;
};

const deleteTransaction = (id) => {
    const data = getLocalStorage();
    data.transactions = data.transactions.filter(t => t.id !== id);
    setLocalStorage(data);
    transactions = data.transactions;
};

// --- Dashboard Logic (index.html) ---

const updateSummary = () => {
    const totalIncome = transactions
        .filter(t => t.type === 'income')
        .reduce((sum, t) => sum + t.amount, 0);

    const totalExpense = transactions
        .filter(t => t.type === 'expense')
        .reduce((sum, t) => sum + t.amount, 0);

    const totalBalance = totalIncome - totalExpense;

    document.getElementById('total-income-value').textContent = formatCurrency(totalIncome);
    document.getElementById('total-expense-value').textContent = formatCurrency(totalExpense);
    document.getElementById('total-balance-value').textContent = formatCurrency(totalBalance);
};

const setupExpenseForm = () => {
    const form = document.getElementById('expense-form');
    if (!form) return;

    form.addEventListener('submit', function(e) {
        e.preventDefault();
        const description = document.getElementById('description').value.trim();
        const amount = parseFloat(document.getElementById('amount').value);
        const type = document.getElementById('type').value;
        const category = document.getElementById('category').value;
        const date = new Date().toISOString().split('T')[0];

        if (amount > 0 && description) {
            const newTransaction = {
                id: Date.now(),
                description,
                amount,
                type,
                category,
                date
            };
            saveTransaction(newTransaction);
            updateSummary();
            form.reset();
            // Re-render chart data if possible, or navigate to history to see it immediately
            if (window.updateDashboardChart) {
                window.updateDashboardChart();
            }
        } else {
            alert("Please enter a valid amount and description.");
        }
    });
};

const setupMonthFilter = () => {
    const filter = document.getElementById('month-filter');
    if (!filter) return;

    const currentYear = new Date().getFullYear();
    // Populate months dynamically (1 to 12)
    for (let i = 1; i <= 12; i++) {
        const date = new Date(currentYear, i - 1, 1);
        const monthName = date.toLocaleString('en-US', { month: 'long' });
        const monthValue = date.toISOString().substring(0, 7); // YYYY-MM
        const option = document.createElement('option');
        option.value = monthValue;
        option.textContent = monthName;
        filter.appendChild(option);
    }

    filter.addEventListener('change', () => { 
        if (window.updateDashboardChart) {
            window.updateDashboardChart();
        }
    });
};

// --- Charting Logic ---

const setupDashboardChart = () => {
    const ctx = document.getElementById('expenseChart')?.getContext('2d');
    if (!ctx) return;

    const monthFilter = document.getElementById('month-filter');
    const selectedMonthValue = monthFilter ? monthFilter.value : 'all';

    const filteredTransactions = transactions.filter(t => {
        if (selectedMonthValue === 'all') return true;
        // Filter by YYYY-MM
        return t.date.startsWith(selectedMonthValue);
    });

    const monthlyData = {
        labels: [], // Days or Month Names
        income: [],
        expenses: []
    };

    if (selectedMonthValue !== 'all') {
        // If a specific month is selected (YYYY-MM), show daily breakdown
        const daysInMonth = new Date(selectedMonthValue.split('-')[0], selectedMonthValue.split('-')[1], 0).getDate();
        for (let day = 1; day <= daysInMonth; day++) {
            const dayStr = String(day).padStart(2, '0');
            const dateKey = `${selectedMonthValue}-${dayStr}`;
            monthlyData.labels.push(day);
            
            const dayTransactions = filteredTransactions.filter(t => t.date === dateKey);
            const dayIncome = dayTransactions.filter(t => t.type === 'income').reduce((sum, t) => sum + t.amount, 0);
            const dayExpense = dayTransactions.filter(t => t.type === 'expense').reduce((sum, t) => sum + t.amount, 0);
            
            monthlyData.income.push(dayIncome);
            monthlyData.expenses.push(dayExpense);
        }
    } else {
        // If 'All Time' or aggregated view is needed, group by month name for simplicity in this setup
        const aggregated = {};
        filteredTransactions.forEach(t => {
            const monthKey = t.date.substring(0, 7); // YYYY-MM
            if (!aggregated[monthKey]) {
                aggregated[monthKey] = { income: 0, expense: 0, label: new Date(monthKey + '-01').toLocaleString('en-US', { month: 'short', year: '2-digit' }) };
            }
            if (t.type === 'income') aggregated[monthKey].income += t.amount;
            else aggregated[monthKey].expense += t.amount;
        });

        Object.keys(aggregated).sort().forEach(key => {
            monthlyData.labels.push(aggregated[key].label);
            monthlyData.income.push(aggregated[key].income);
            monthlyData.expenses.push(aggregated[key].expense);
        });
    }

    if (window.expenseChartInstance) {
        window.expenseChartInstance.destroy();
    }

    window.expenseChartInstance = new Chart(ctx, {
        type: selectedMonthValue !== 'all' ? 'bar' : 'line',
        data: {
            labels: monthlyData.labels,
            datasets: [{
                label: 'Income',
                data: monthlyData.income,
                backgroundColor: 'rgba(0, 200, 151, 0.7)',
                borderColor: 'rgba(0, 200, 151, 1)',
                borderWidth: 2,
                tension: selectedMonthValue !== 'all' ? 0 : 0.3, // Smoother curve for time series
                fill: selectedMonthValue !== 'all' ? false : true, // Fill area for line chart
                type: 'line'
            }, {
                label: 'Expenses',
                data: monthlyData.expenses,
                backgroundColor: 'rgba(255, 82, 82, 0.7)',
                borderColor: 'rgba(255, 82, 82, 1)',
                borderWidth: 2,
                type: selectedMonthValue !== 'all' ? 'bar' : 'line'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    grid: { color: 'rgba(255, 255, 255, 0.1)' },
                    ticks: { color: 'var(--color-text-muted)' }
                },
                x: {
                    grid: { display: false },
                    ticks: { color: 'var(--color-text-muted)' }
                }
            },
            plugins: {
                legend: { labels: { color: 'var(--color-text-light)' } },
                title: { display: false }
            }
        }
    });
};

window.updateDashboardChart = setupDashboardChart;

// --- History Page Logic (history.html) ---

const renderHistoryList = (list) => {
    const ul = document.getElementById('transaction-list-ul');
    const noMessage = document.getElementById('no-transactions-message');
    if (!ul) return;

    // Clear existing list items except the header
    while (ul.children.length > 1) {
        ul.removeChild(ul.lastChild);
    }

    if (list.length === 0) {
        noMessage.style.display = 'block';
        return;
    }
    noMessage.style.display = 'none';

    list.sort((a, b) => new Date(b.date) - new Date(a.date)); // Sort newest first

    list.forEach(t => {
        const li = document.createElement('li');
        li.className = 'transaction-item';
        
        const amountClass = t.type === 'income' ? 'income' : 'expense';

        li.innerHTML = `
            <span>${formatDate(t.date)}</span>
            <span>${t.description}</span>
            <span>${t.category}</span>
            <span>${t.type.charAt(0).toUpperCase() + t.type.slice(1)}</span>
            <span class="amount ${amountClass}">${formatCurrency(t.amount)}</span>
            <span class="delete-col"><button class="delete-btn" data-id="${t.id}">&times;</button></span>
        `;
        ul.appendChild(li);
    });

    // Attach delete listeners
    document.querySelectorAll('.delete-btn').forEach(button => {
        button.addEventListener('click', (e) => {
            const id = parseInt(e.target.dataset.id);
            if (confirm("Are you sure you want to delete this transaction?")) {
                deleteTransaction(id);
                // Re-render filtered list
                applyHistoryFilters();
            }
        });
    });
};

const applyHistoryFilters = () => {
    const typeFilter = document.getElementById('history-type-filter')?.value || 'all';
    const categoryFilter = document.getElementById('history-category-filter')?.value || 'all';
    const searchTerm = document.getElementById('history-search')?.value.toLowerCase() || '';

    const filtered = transactions.filter(t => {
        const matchesType = typeFilter === 'all' || t.type === typeFilter;
        const matchesCategory = categoryFilter === 'all' || t.category === categoryFilter;
        const matchesSearch = t.description.toLowerCase().includes(searchTerm);
        return matchesType && matchesCategory && matchesSearch;
    });

    renderHistoryList(filtered);
};

const setupHistoryFilters = () => {
    const filters = [
        'history-type-filter',
        'history-category-filter',
        'history-search'
    ];

    filters.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', applyHistoryFilters);
        }
    });
};

// --- Report Page Logic (report.html) ---

const getCategoryAggregates = (periodTransactions) => {
    const aggregates = {};
    
    periodTransactions.forEach(t => {
        if (!aggregates[t.category]) {
            aggregates[t.category] = { total: 0, type: t.type };
        }
        aggregates[t.category].total += t.amount;
    });
    return aggregates;
};

const setupReportFilters = () => {
    const filter = document.getElementById('report-month-filter');
    if (!filter) return;

    // Populate months dynamically
    const allMonths = [...new Set(transactions.map(t => t.date.substring(0, 7)))]; // Get unique YYYY-MM
    allMonths.sort().reverse();

    allMonths.forEach(monthValue => {
        const date = new Date(monthValue + '-01');
        const monthName = date.toLocaleString('en-US', { month: 'long', year: 'numeric' });
        const option = document.createElement('option');
        option.value = monthValue;
        option.textContent = monthName;
        filter.appendChild(option);
    });

    filter.addEventListener('change', renderReport);
};

const renderReport = () => {
    const monthFilter = document.getElementById('report-month-filter');
    const selectedMonthValue = monthFilter ? monthFilter.value : 'all';

    const periodTransactions = transactions.filter(t => {
        if (selectedMonthValue === 'all') return true;
        return t.date.startsWith(selectedMonthValue);
    });

    const aggregates = getCategoryAggregates(periodTransactions);

    // Update Summary Totals
    const totalIncome = periodTransactions.filter(t => t.type === 'income').reduce((sum, t) => sum + t.amount, 0);
    const totalExpense = periodTransactions.filter(t => t.type === 'expense').reduce((sum, t) => sum + t.amount, 0);

    document.getElementById('report-income-total').textContent = formatCurrency(totalIncome);
    document.getElementById('report-expense-total').textContent = formatCurrency(totalExpense);

    // Render Detailed List
    const listUl = document.getElementById('category-totals-list');
    if (listUl) {
        listUl.innerHTML = '';
        Object.keys(aggregates).sort((a, b) => aggregates[b].total - aggregates[a].total).forEach(category => {
            const data = aggregates[category];
            const item = document.createElement('li');
            item.className = 'category-total-item';
            item.innerHTML = `
                <h4>${category}</h4>
                <p>${formatCurrency(data.total)} (${data.type})</p>
            `;
            listUl.appendChild(item);
        });
    }

    // Render Doughnut Chart
    const expenseData = Object.entries(aggregates)
        .filter(([, data]) => data.type === 'expense')
        .map(([category, data]) => ({ category, total: data.total }));

    const chartCtx = document.getElementById('categoryDoughnutChart')?.getContext('2d');
    if (chartCtx) {
        if (window.doughnutChartInstance) {
            window.doughnutChartInstance.destroy();
        }

        const labels = expenseData.map(item => item.category);
        const dataValues = expenseData.map(item => item.total);
        
        // Simple color mapping based on category for consistency
        const baseColors = ['#00C897', '#FF9800', '#FF5252', '#2196F3', '#9C27B0', '#FFC107'];
        const backgroundColors = labels.map((_, i) => baseColors[i % baseColors.length] + 'AA');
        const borderColors = labels.map((_, i) => baseColors[i % baseColors.length]);

        window.doughnutChartInstance = new Chart(chartCtx, {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: dataValues,
                    backgroundColor: backgroundColors,
                    borderColor: borderColors,
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { 
                        position: 'right', 
                        labels: { color: 'var(--color-text-light)' }
                    },
                    title: { display: false }
                }
            }
        });
    }
};

// --- Observer for Scroll Animations (Figma Polish) ---

const setupIntersectionObserver = () => {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('visible');
                observer.unobserve(entry.target);
            }
        });
    }, { threshold: 0.1 });

    document.querySelectorAll('[data-animate]').forEach(el => {
        observer.observe(el);
    });
};

// --- Page Initialization Router ---

const init = () => {
    transactions = initializeData(); // Ensure transactions are loaded
    setupIntersectionObserver();

    // Identify page context based on URL path used in HTML links
    const path = window.location.pathname;
    
    // Check for dashboard (index.html is often just '/')
    if (path.endsWith('index.html') || path.endsWith('/') || path === '') {
        document.body.classList.add('dashboard-page');
        updateSummary();
        setupExpenseForm();
        setupMonthFilter();
        setupDashboardChart();
    } else if (path.endsWith('history.html')) {
        document.body.classList.add('history-page');
        setupHistoryFilters();
        applyHistoryFilters(); // Initial render
    } else if (path.endsWith('report.html')) {
        document.body.classList.add('report-page');
        setupReportFilters();
        renderReport(); // Initial render
    }
};

// Execute initialization when DOM is fully loaded
window.addEventListener('DOMContentLoaded', init);