File size: 8,090 Bytes
24e6f5b | 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 | import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import api from '../api/axios';
const SettingsContext = createContext();
export const useSettings = () => useContext(SettingsContext);
export const SettingsProvider = ({ children }) => {
// --- State Initialization ---
// Load from local storage or set defaults
const [currency, setCurrency] = useState(localStorage.getItem('app_currency') || 'INR');
const [theme, setTheme] = useState(localStorage.getItem('app_theme') || 'cosmic');
const [privacyMode, setPrivacyMode] = useState(localStorage.getItem('app_privacy') === 'true');
// Pro Features (Realistic)
const [savingsGoal, setSavingsGoal] = useState(parseInt(localStorage.getItem('app_savings_goal')) || 20); // % Target
const [notifications, setNotifications] = useState(JSON.parse(localStorage.getItem('app_notifications')) || {
email: true,
push: false,
budget_alerts: true,
monthly_reports: true
});
// --- Currency Logic ---
const getSymbol = (curr) => {
switch (curr) {
case 'INR': return '₹';
case 'USD': return '$';
case 'EUR': return '€';
case 'GBP': return '£';
default: return '$';
}
};
const [currencySymbol, setCurrencySymbol] = useState(getSymbol(currency));
useEffect(() => {
setCurrencySymbol(getSymbol(currency));
localStorage.setItem('app_currency', currency);
}, [currency]);
// --- Theme Logic ---
const themes = {
cosmic: { primary: '#6366f1', secondary: '#ec4899', name: 'Cosmic Indigo' },
emerald: { primary: '#10b981', secondary: '#34d399', name: 'Emerald Forest' },
rose: { primary: '#f43f5e', secondary: '#fb7185', name: 'Rose Gold' },
amber: { primary: '#f59e0b', secondary: '#fbbf24', name: 'Amber Sunset' },
azure: { primary: '#0ea5e9', secondary: '#38bdf8', name: 'Azure Sky' }
};
useEffect(() => {
const root = document.documentElement;
const selectedTheme = themes[theme] || themes.cosmic;
// Update CSS Variables
root.style.setProperty('--primary-color', selectedTheme.primary);
root.style.setProperty('--secondary-color', selectedTheme.secondary);
localStorage.setItem('app_theme', theme);
}, [theme]);
// --- Privacy & Notifications Persistence ---
useEffect(() => {
localStorage.setItem('app_privacy', privacyMode);
}, [privacyMode]);
useEffect(() => {
localStorage.setItem('app_savings_goal', savingsGoal);
}, [savingsGoal]);
useEffect(() => {
localStorage.setItem('app_notifications', JSON.stringify(notifications));
}, [notifications]);
// --- Actions ---
const updateNotification = (key) => {
setNotifications(prev => ({ ...prev, [key]: !prev[key] }));
};
// --- Background Reporting States ---
const [generatingPDF, setGeneratingPDF] = useState(false);
const [sendingEmail, setSendingEmail] = useState(false);
const handleDownloadReport = useCallback(async (format, type, provider) => {
if (generatingPDF) return;
setGeneratingPDF(true);
try {
const payload = provider && provider !== 'Auto Mode' ? { provider } : {};
const initRes = await api.post(`finance/generate-report/?type=${type}`, payload);
const { task_id } = initRes.data;
let pollCount = 0;
const pollInterval = setInterval(async () => {
try {
pollCount++;
const statusRes = await api.get(`finance/generate-report/?task_id=${task_id}`);
if (statusRes.data.status === 'completed') {
clearInterval(pollInterval);
const fileRes = await api.get(`finance/generate-report/?task_id=${task_id}&download=true`, {
responseType: 'blob'
});
const url = window.URL.createObjectURL(new Blob([fileRes.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `Pro_Financial_Report_${new Date().toISOString().split('T')[0]}.pdf`);
document.body.appendChild(link);
link.click();
link.remove();
setGeneratingPDF(false);
alert("PDF Report Generated Successfully!");
} else if (statusRes.data.status === 'failed') {
clearInterval(pollInterval);
setGeneratingPDF(false);
alert(`Generation Failed: ${statusRes.data.error || 'Unknown error'}`);
} else {
if (pollCount > 60) {
clearInterval(pollInterval);
setGeneratingPDF(false);
alert("Report generation is taking longer than expected. It will continue in the background.");
}
}
} catch (pollErr) {
console.error("Polling error:", pollErr);
}
}, 5000);
} catch (err) {
alert(`Report Initiation Failed: ${err.message}`);
setGeneratingPDF(false);
}
}, [generatingPDF]);
const handleSendEmailReport = useCallback(async (recipient, provider) => {
if (!recipient) {
alert("Please enter an email address.");
return false;
}
setSendingEmail(true);
try {
const payload = { email: recipient };
if (provider && provider !== 'Auto Mode') {
payload.provider = provider;
}
const initRes = await api.post('finance/send-email-report/', payload);
const { task_id } = initRes.data;
(async () => {
let pollCount = 0;
const pollInterval = setInterval(async () => {
try {
pollCount++;
const statusRes = await api.get(`finance/generate-report/?task_id=${task_id}`);
if (statusRes.data.status === 'completed') {
clearInterval(pollInterval);
setSendingEmail(false);
alert("Email Report Sent Successfully!");
} else if (statusRes.data.status === 'failed') {
clearInterval(pollInterval);
setSendingEmail(false);
alert(`Email Failed: ${statusRes.data.error || 'Unknown error'}`);
} else {
if (pollCount > 120) {
clearInterval(pollInterval);
setSendingEmail(false);
alert("Email report is taking longer than expected. It will continue in the background.");
}
}
} catch (pollErr) {
console.error("Polling error:", pollErr);
}
}, 5000);
})();
return true;
} catch (err) {
alert(`Email Initiation Failed: ${err.message}`);
setSendingEmail(false);
return false;
}
}, []);
const value = {
currency, setCurrency, currencySymbol,
theme, setTheme, themes,
privacyMode, setPrivacyMode,
savingsGoal, setSavingsGoal,
notifications, updateNotification,
generatingPDF, sendingEmail,
handleDownloadReport, handleSendEmailReport
};
return (
<SettingsContext.Provider value={value}>
{children}
</SettingsContext.Provider>
);
};
|