Dashboard Temp Share Shortlinks Frames API

HTMLify

script.js
Views: 39 | 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
// --- GLOBAL SCRIPT: Handles Navigation, Animations, and Mock Data --- //

// Exchange Rate Service Mock (USD to INR)
const EXCHANGE_RATES = {
    'USD': 83.50, // Default reference rate
    'EUR': 89.85, // Hypothetical Rate updated on sync
    'GBP': 106.05 // Hypothetical Rate updated on sync
};

const DEFAULT_CURRENCY = 'INR'; // Production Ready Default

// 1. Scroll-triggered Animations (Fading elements in)
document.addEventListener('DOMContentLoaded', () => {
    const observerOptions = {
        root: null,
        rootMargin: '0px',
        threshold: 0.05 // Trigger when 5% of the element is visible
    };

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

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

    // Initialize page-specific functions
    if (document.getElementById('spendingChart')) {
        initializeDashboard();
    } else if (document.getElementById('recurring-payments-body')) {
        initializePaymentsPage();
    } else if (document.getElementById('debt-strategy')) {
        initializeDebtPage();
    } else if (document.getElementById('savings-goals-list')) {
        initializeSavingsPage();
    } else if (document.getElementById('incomeExpenseChart')) {
        initializeReportsPage();
    } else if (document.getElementById('theme-select')) {
        initializeSettingsPage();
    }
});

// --- Mock Data Store (Simulating Local Storage/API) ---
const MOCK_DATA = {
    // Data initialized with INR conversion based on 1 USD = 83.50 INR
    prioritizedPayments: [
        { id: 101, name: "Credit Card Minimum", category: "Debt", amount: 10050.25, currency: "INR", dueDate: "2024-08-01", priority: "High" }, // Approx 120 USD
        { id: 102, name: "Rent Payment", category: "Housing", amount: 150300.00, currency: "INR", dueDate: "2024-08-05", priority: "High" }, // Approx 1800 USD
        { id: 103, name: "Software Subscription", category: "Utilities", amount: 1668.00, currency: "INR", dueDate: "2024-08-10", priority: "Medium" }, // Approx 20 USD
        { id: 104, name: "Car Insurance", category: "Transportation", amount: 7087.50, currency: "INR", dueDate: "2024-08-15", priority: "Medium" }, // Approx 85 USD
    ],
    savingsGoals: [
        { id: 201, name: "New Laptop", target: 415000, saved: 269750, deadline: "2025-03-01", interestRate: 1.0 }, // Target adjusted for INR
        { id: 202, name: "Emergency Fund", target: 835000, saved: 125250, deadline: "2025-12-01", interestRate: 4.0 }, // Target adjusted for INR
    ],
    // Mock spending data (already in INR)
    spendingData: {
        labels: ['Utilities', 'Groceries', 'Entertainment', 'Housing', 'Transport', 'Misc'],
        data: [37500, 65000, 20800, 150300, 25000, 12500] // Amounts scaled up for realistic INR budget representation
    },
    debt: {
        principalOwed: 350000, // Total principal for the new debt page
        interestProjected: 78500,
        payoffDate: "2027-06-01",
        strategy: "avalanche"
    },
    settings: {
        theme: 'dark',
        fontSize: 'medium',
        animationsEnabled: true,
        defaultCurrency: 'INR', // Updated to INR
        syncInterval: 60,
        rateSyncEnabled: true,
        debtBudgetIncluded: true
    }
};

/**
 * Utility function to format currency based on the default setting (INR).
 * Assumes INR formatting for the dashboard/payments views.
 */
function formatCurrency(amount, currencySymbol = '₹') {
    // Simple INR formatting: use toLocaleString with Indian number system
    return `${currencySymbol}${Math.round(amount).toLocaleString('en-IN')}`;
}

// --- Dashboard Page Logic ---
function initializeDashboard() {
    // Calculate total balance based on mock data (for production readiness)
    const totalBalance = 1035010.50; // Hardcoded based on index.html placeholder value
    document.getElementById('total-balance').textContent = formatCurrency(totalBalance);

    // Since default currency is INR, show 3 pending payments
    document.getElementById('pending-payments').textContent = MOCK_DATA.prioritizedPayments.filter(p => p.dueDate > '2024-07-20').length;

    // Savings progress matches goal 201 (65%)
    document.getElementById('savings-progress').textContent = '65%';
    // document.getElementById('budget-used').textContent = `₹${(MOCK_DATA.spendingData.data.reduce((a, b) => a + b, 0)).toLocaleString('en-IN')} / ₹250,000`; // Removed from HTML

    // New: Display Debt summary
    document.getElementById('total-debt').textContent = formatCurrency(MOCK_DATA.debt.principalOwed);

    // NEW: Calculate Net Worth
    const totalAssets = totalBalance + MOCK_DATA.savingsGoals.reduce((sum, goal) => sum + goal.saved, 0);
    const netWorth = totalAssets - MOCK_DATA.debt.principalOwed;
    document.getElementById('net-worth').textContent = formatCurrency(netWorth);

    renderPrioritizedPayments(MOCK_DATA.prioritizedPayments.slice(0, 4));
    renderSpendingChart();
}

function renderPrioritizedPayments(payments) {
    const list = document.getElementById('prioritized-list');
    if (!list) return;
    list.innerHTML = '';

    payments.forEach(p => {
        const item = document.createElement('li');
        item.className = 'priority-item';
        item.innerHTML = `
            <div class="priority-info">
                <span class="priority-tag ${p.priority.charAt(0).toUpperCase() + p.priority.slice(1)}">${p.priority}</span>
                <div>
                    <strong>${p.name}</strong>
                    <span style="font-size: 0.8rem; opacity: 0.7;">Due: ${p.dueDate.substring(5)}</span>
                </div>
            </div>
            <span>${formatCurrency(p.amount)}</span>
        `;
        list.appendChild(item);
    });
}

function renderSpendingChart() {
    const ctx = document.getElementById('spendingChart').getContext('2d');
    const data = MOCK_DATA.spendingData;
    // Scale data slightly for visual variance if needed, but here we use the mock data directly.

    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: data.labels.map(l => l.substring(0, 3)), // Shorten labels
            datasets: [{
                label: 'Spending (INR)',
                data: data.data,
                backgroundColor: [
                    'rgba(103, 80, 164, 0.7)', // Primary
                    'rgba(125, 82, 96, 0.7)', // Tertiary
                    'rgba(98, 91, 113, 0.7)', // Secondary
                    'rgba(255, 216, 255, 0.7)', // Primary Container
                    'rgba(207, 102, 121, 0.7)', // Error
                    'rgba(230, 225, 229, 0.7)' // On Background
                ],
                borderColor: [
                    'rgba(103, 80, 164, 1)',
                    'rgba(125, 82, 96, 1)',
                    'rgba(98, 91, 113, 1)',
                    'rgba(255, 216, 255, 1)',
                    'rgba(207, 102, 121, 1)',
                    'rgba(230, 225, 229, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                title: { display: false }
            },
            scales: {
                y: { beginAtZero: true, grid: { color: 'rgba(230, 225, 229, 0.1)' }, ticks: { color: 'var(--md3-sys-color-on-surface-variant)', callback: function(value) { return formatCurrency(value, '\u20B9').replace(/\..*|00$/, ''); } } }, // Format Y-axis ticks for INR
                x: { grid: { display: false }, ticks: { color: 'var(--md3-sys-color-on-surface-variant)' } }
            }
        }
    });
}

// --- Payments Page Logic ---
function initializePaymentsPage() {
    renderPaymentsTable(MOCK_DATA.prioritizedPayments);
}

function renderPaymentsTable(payments) {
    const tbody = document.getElementById('recurring-payments-body');
    if (!tbody) return;
    tbody.innerHTML = '';

    payments.forEach(p => {
        const row = tbody.insertRow();
        
        const isPastDue = new Date(p.dueDate) < new Date('2024-07-20') && p.name !== 'Rent Payment'; // Mocking 'Past Due' for older dates
        const statusClass = isPastDue ? 'error-text' : (p.name === 'Rent Payment' ? 'warning-text' : 'success-text');
        const statusText = isPastDue ? 'Past Due' : (p.name === 'Rent Payment' ? 'Awaiting Approval' : 'Scheduled');

        row.innerHTML = `
            <td>${p.name}</td>
            <td><span class="badge">${p.category}</span></td>
            <td>${formatCurrency(p.amount)}</td>
            <td>${p.dueDate.substring(5)}</td>
            <td><span class="priority-tag ${p.priority.charAt(0).toUpperCase() + p.priority.slice(1)}">${p.priority}</span></td>
            <td><span class="${statusClass}">${statusText}</span></td>
            <td><button class="btn btn-secondary" style="padding: 4px 10px; font-size: 0.75rem;">View Detail</button></td>
        `;
    });
}

// --- Debt Page Logic (NEW) ---
function initializeDebtPage() {
    const debtData = MOCK_DATA.debt;
    
    document.getElementById('total-principal').textContent = formatCurrency(debtData.principalOwed);
    document.getElementById('total-interest').textContent = formatCurrency(debtData.interestProjected);
    document.getElementById('payoff-date').textContent = debtData.payoffDate.substring(0, 7).replace('-', '/'); // Display YYYY/MM

    // Update settings/strategy simulation
    document.getElementById('debt-strategy').value = debtData.strategy;
    
    const debtBudgetToggle = document.getElementById('debt-budget-toggle');
    // Assume debt budget inclusion is true by default
    if(MOCK_DATA.settings.debtBudgetIncluded) debtBudgetToggle.classList.add('active');
    
    debtBudgetToggle.onclick = () => {
        debtBudgetToggle.classList.toggle('active');
        MOCK_DATA.settings.debtBudgetIncluded = debtBudgetToggle.classList.contains('active');
    };
}


// --- Savings Page Logic ---
function initializeSavingsPage() {
    renderSavingsGoals(MOCK_DATA.savingsGoals);
}

function renderSavingsGoals(goals) {
    const container = document.getElementById('savings-goals-list');
    if (!container) return;
    container.innerHTML = '';

    goals.forEach(goal => {
        const percentage = Math.min(100, (goal.saved / goal.target) * 100);
        const card = document.createElement('div');
        card.className = 'goal-card animate-in';
        card.setAttribute('data-delay', '0.2');

        card.innerHTML = `
            <h4>${goal.name}</h4>
            <p class="small-text mb-16">Deadline: ${goal.deadline.substring(0, 4)}/${goal.deadline.substring(5, 7)}</p>
            
            <div class="savings-widget">
                <div class="progress-bar-container">
                    <div class="progress-bar" style="width: ${percentage}%;"></div>
                </div>
                <p class="savings-amount mt-8">${formatCurrency(goal.saved)} saved of ${formatCurrency(goal.target)}</p>
                <p class="small-text">Est. Interest Earned: ${formatCurrency(goal.saved * (goal.interestRate/100), '')} (${goal.interestRate}% rate)</p>
                <button class="btn btn-secondary" style="margin-top: 12px;">Contribute</button>
            </div>
        `;
        container.appendChild(card);
    });
    // Re-apply observer logic to newly added elements (if any)
    document.querySelectorAll('.goal-card').forEach(el => {
        const observer = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('visible');
                    observer.unobserve(entry.target);
                }
            });
        }, observerOptions);
        observer.observe(el);
    });
}

// --- Reports Page Logic ---
function initializeReportsPage() {
    renderIncomeExpenseChart();
    renderCategoryPieChart();
}

function renderIncomeExpenseChart() {
    const ctx = document.getElementById('incomeExpenseChart').getContext('2d');
    // Mock data for trend: Income consistently higher than expenses (in INR)
    const trendData = {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        income: [417500, 434000, 425750, 500500, 458250, 517000], // Scaled income
        expense: [300000, 316500, 300000, 341550, 325050, 334000] // Scaled expenses
    };

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: trendData.labels,
            datasets: [
                {
                    label: 'Income (INR)',
                    data: trendData.income,
                    borderColor: 'rgba(103, 80, 164, 1)', // Primary
                    backgroundColor: 'rgba(103, 80, 164, 0.2)',
                    fill: true,
                    tension: 0.3
                },
                {
                    label: 'Expenses (INR)',
                    data: trendData.expense,
                    borderColor: 'rgba(207, 102, 121, 1)', // Error/Tertiary
                    backgroundColor: 'rgba(207, 102, 121, 0.2)',
                    fill: false,
                    tension: 0.3
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { position: 'top', labels: { color: 'var(--md3-sys-color-on-surface-variant)' } }
            },
            scales: {
                y: { 
                    beginAtZero: true, 
                    grid: { color: 'rgba(230, 225, 229, 0.1)' }, 
                    ticks: { 
                        color: 'var(--md3-sys-color-on-surface-variant)',
                        callback: function(value) { return formatCurrency(value, '\u20B9').replace(/\..*|00$/, ''); } // INR formatting
                    }
                },
                x: { grid: { display: false }, ticks: { color: 'var(--md3-sys-color-on-surface-variant)' } }
            }
        }
    });
}

function renderCategoryPieChart() {
    const ctx = document.getElementById('categoryPieChart').getContext('2d');
    const data = MOCK_DATA.spendingData;

    const backgroundColors = [
        'rgba(103, 80, 164, 0.8)', // Primary
        'rgba(125, 82, 96, 0.8)',  // Tertiary
        'rgba(98, 91, 113, 0.8)',  // Secondary
        'rgba(150, 200, 255, 0.8)', // Blue Accent
        'rgba(255, 200, 150, 0.8)', // Orange Accent
        'rgba(180, 180, 180, 0.8)'  // Gray Accent
    ];

    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: data.labels,
            datasets: [{
                label: 'Spending by Category (INR)',
                data: data.data,
                backgroundColor: backgroundColors,
                hoverOffset: 10,
                borderWidth: 2
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { 
                    position: 'right', 
                    labels: { 
                        color: 'var(--md3-sys-color-on-surface-variant)',
                        generateLabels: function(chart) {
                            const data = chart.data;
                            const total = data.datasets[0].data.reduce((a, b) => a + b, 0);
                            return data.labels.map(function(label, index) {
                                const value = data.datasets[0].data[index];
                                const percentage = ((value / total) * 100).toFixed(1);
                                return {
                                    text: `${label}: ${formatCurrency(value, '\u20B9').replace(/\..*|00$/, '')} (${percentage}%)`,
                                    fillStyle: backgroundColors[index],
                                    hidden: false,
                                    // Add color property for styling
                                    strokeStyle: backgroundColors[index],
                                    // You might need to adjust legend item styling manually if default colors are overridden by Chart.js theme settings
                                };
                            });
                        }
                    }
                }
            }
        }
    });
}

// --- Settings Page Logic ---
function initializeSettingsPage() {
    const settings = MOCK_DATA.settings;

    // 1. Load current state
    document.getElementById('theme-select').value = settings.theme;
    document.getElementById('font-size-select').value = settings.fontSize;
    document.getElementById('default-currency').value = settings.defaultCurrency;
    document.getElementById('default-sync').value = settings.syncInterval;
    
    // Initialize Toggles
    const animationToggle = document.getElementById('animation-toggle');
    if(settings.animationsEnabled) animationToggle.classList.add('active');
    animationToggle.onclick = () => { 
        animationToggle.classList.toggle('active');
        settings.animationsEnabled = animationToggle.classList.contains('active');
    };

    const rateSyncToggle = document.getElementById('rate-sync-toggle');
    if(settings.rateSyncEnabled) rateSyncToggle.classList.add('active');
    rateSyncToggle.onclick = () => { 
        rateSyncToggle.classList.toggle('active');
        settings.rateSyncEnabled = rateSyncToggle.classList.contains('active');
    };

    // 2. Handle Saving
    document.getElementById('save-settings').addEventListener('click', () => {
        settings.theme = document.getElementById('theme-select').value;
        settings.fontSize = document.getElementById('font-size-select').value;
        settings.defaultCurrency = document.getElementById('default-currency').value;
        settings.syncInterval = parseInt(document.getElementById('default-sync').value);
        settings.debtStrategy = document.getElementById('debt-strategy').value;
        
        // Update MOCK_DATA with the new default currency and debt strategy
        MOCK_DATA.settings.defaultCurrency = settings.defaultCurrency;
        MOCK_DATA.debt.strategy = settings.debtStrategy;

        alert(`Settings saved successfully! Default currency set to ${settings.defaultCurrency}. Debt strategy updated.`);
        
        // In a real production app, this would trigger a sync or data update.
        console.log("Updated Settings:", settings);
    });
}