-
Notifications
You must be signed in to change notification settings - Fork 0
/
save.js
180 lines (162 loc) · 5.62 KB
/
save.js
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
import { updateBudget, updateTableFromLocalStorage } from "./index.js";
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.6.0/firebase-app.js";
import {
getDatabase,
ref,
set,
remove,
child,
get,
update,
} from "https://www.gstatic.com/firebasejs/10.6.0/firebase-database.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyD-REg91GmdqlgXbPD0fcWE43FOhv5E898",
authDomain: "open-source-tsquare.firebaseapp.com",
databaseURL: "https://open-source-tsquare-default-rtdb.firebaseio.com",
projectId: "open-source-tsquare",
storageBucket: "open-source-tsquare.appspot.com",
messagingSenderId: "852914490414",
appId: "1:852914490414:web:4a5d771ed704d7775363bf",
measurementId: "G-27162N4PPC",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
let autoSave = localStorage.getItem("autoSave") || false;
autoSave = JSON.parse(autoSave);
const autoSaveCheckbox = document.getElementById("auto-save-to-db");
let userToggled = localStorage.getItem("checked") || false;
userToggled = JSON.parse(userToggled);
const autoSaveField = document.getElementById("auto-save");
let messageFired = JSON.parse(localStorage.getItem("messageFired")) || null;
async function setData(email) {
const id = email.replace(/[.]/g, "");
const currency = localStorage.getItem("currency") || null;
const spending = localStorage.getItem("spending") || null;
let financeData = localStorage.getItem("financeData") || {};
const rowId = localStorage.getItem("rowId") || null;
const income = localStorage.getItem("income") || null;
if (isValidEmail(email)) {
set(ref(db, "financeBuddy/" + id), {
email: email,
income: income,
spending: spending,
currency: currency,
financeData: JSON.parse(financeData),
rowId: rowId,
})
.then(() => {
if (!messageFired) {
console.log("Data saved successfully");
alert(`Your budget was saved to the database successfully`);
JSON.stringify(
localStorage.setItem("messageFired", (messageFired = true))
);
}
})
.catch((err) => {
console.error(err);
console.log(err);
alert(err);
});
} else {
console.log("Something went wrong");
}
}
async function sendData(email) {
const income = localStorage.getItem("income") || null;
if (isValidEmail(email)) {
if (income) {
setData(email);
console.log("Saved");
} else {
alert("Something went wrong, try again later.");
}
} else {
alert("Invalid email");
}
}
autoSaveCheckbox.addEventListener("change", () => {
let email = localStorage.getItem("email") || getEmailFromUser();
localStorage.setItem("email", email);
if (autoSaveCheckbox.checked) {
sendData(email);
autoSaveField.textContent = "ON";
JSON.stringify(localStorage.setItem("autoSave", (autoSave = true)));
localStorage.setItem("checked", JSON.stringify((userToggled = true)));
} else {
localStorage.setItem("checked", JSON.stringify((userToggled = false)));
autoSaveField.textContent = "OFF";
JSON.stringify(localStorage.setItem("autoSave", (autoSave = false)));
}
});
if (!userToggled) {
autoSaveCheckbox.checked = false;
} else {
autoSaveCheckbox.checked = true;
autoSaveField.textContent = "ON";
}
function isValidEmail(email) {
// Regular expression for a simple email validation
const emailInspector = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailInspector.test(email);
}
function saveFinanceData() {
let email = localStorage.getItem("email") || getEmailFromUser();
alert("Saving...");
if (email) {
sendData(email).then(alert("Saved!"));
}
}
function getEmailFromUser() {
let userEmail;
do {
// Prompt the user for an email
userEmail = prompt("Enter email to retrieve your budget from the cloud or save new budget:");
// Check if the email is valid
if (!isValidEmail(userEmail)) {
alert("Invalid email. Please enter a valid email address.");
}
} while (!isValidEmail(userEmail));
localStorage.setItem("email", userEmail);
return userEmail;
}
document.getElementById("save-data").addEventListener("click", saveFinanceData);
async function retriveDataFromDatabase(email) {
if (!isValidEmail(email)) {
email = getEmailFromUser();
}
let data;
const id = email.replace(/[.]/g, "");
const dbref = ref(db);
get(child(dbref, "financeBuddy/" + id))
.then((snapshot) => {
if (snapshot.exists()) {
data = snapshot.val();
localStorage.setItem("financeData", JSON.stringify(data.financeData));
localStorage.setItem("income", data.income);
localStorage.setItem("rowId", data.rowId);
localStorage.setItem("spending", data.spending);
localStorage.setItem("currency", data.currency);
setTimeout(() => {
updateBudget();
updateTableFromLocalStorage()
}, 2000);
} else {
console.log("Data not found");
setTimeout(() => {
updateBudget();
updateTableFromLocalStorage()
}, 1000);
}
})
.catch((err) => {
console.log(err);
});
}
export { sendData, getEmailFromUser, retriveDataFromDatabase, isValidEmail };