-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxpenseSQL.py
More file actions
345 lines (248 loc) · 10.7 KB
/
xpenseSQL.py
File metadata and controls
345 lines (248 loc) · 10.7 KB
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
#This is designed to implement the use of SQLlite to increase code optimization and use of IDs for easy implentation
# I decided to use SQL because comapared to CSV I don't have to create files for each user.
from datetime import datetime
import sqlite3
import bcrypt
#Creating db tables to store all user's data
def user_table():
connector = sqlite3.connect('expense_database.db')
cursor = connector.cursor()
cursor.execute(''' CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
name TEXT,
email TEXT NOT NULL UNIQUE,
phone_no TEXT,
address TEXT) ''')
cursor.execute(''' CREATE TABLE IF NOT EXISTS income(
id INTEGER PRIMARY KEY AUTOINCREMENT,
userId INTEGER,
amount REAL,
timestamp DATETIME DEFUALT CURRENT_TIMESTAMP,
FOREIGN KEY(userId) REFERENCES users(id))''')
cursor.execute(''' CREATE TABLE IF NOT EXISTS savings(
id INTEGER PRIMARY KEY AUTOINCREMENT,
userId INTEGER,
amount REAL,
timestamp DATETIME DEFUALT CURRENT_TIMESTAMP,
FOREIGN KEY(userId) REFERENCES users(id))''')
cursor.execute('''CREATE TABLE IF NOT EXISTS expenses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
userId INTEGER,
category TEXT,
amount REAL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(userId) REFERENCES users(id))''')
connector.commit()
connector.close()
user_table()
def user_registration():
#Code to collect user data upon registration.
name = input("NAME: ")
email = input("EMAIL: ")
phone_no = input("PHONE NUMBER: ")
address = input("ADDRESS: ")
username = input("USERNAME: ")
password = input("PASSWORD: ")
#Hashing password for east comparison later
password_hash = bcrypt.hashpw(password.encode('utf-8'),bcrypt.gensalt()) #Converted the password to bytes and generated a salt(Ensures identical passwords have diff. hashes).
#Store User Data in created database
connector = sqlite3.connect('expense_database.db')
cursor = connector.cursor()
try:
cursor.execute (''' INSERT INTO users
(name, email, phone_no, address, username, password_hash)
VALUES (?, ?, ?, ?, ?, ?)''', (name, email, phone_no, address, username, password_hash))
connector.commit()
print(f"{name}, Welcome to Expense Tracker")
except sqlite3.IntegrityError:
print("Username or email already exists!")
finally:
connector.close()
#This function to make sure users don't have to register everytime
def user_login():
username = input("USERNAME: ")
password = input("PASSWORD: ")
connector = sqlite3.connect("expense_database.db")
cursor = connector.cursor()
cursor.execute('''SELECT password_hash FROM users WHERE username=?''', (username,))
res = cursor.fetchone()
if res:
password_hash = res[0]
if bcrypt.checkpw(password.encode('utf-8'), password_hash):
print(f"Welcome {username}!")
cursor.execute('''SELECT id FROM users WHERE username = ?''', (username,))
userId = cursor.fetchone()[0]
connector.close()
return userId
else:
print("Incorrect Password!")
return None
else:
print("Username does not exist")
return None
#-------------Income Operations-------------
def add_income(userId):
try:
connector = sqlite3.connect('expense_database.db')
cursor = connector.cursor()
new_income = float(input("INCOME: $"))
#Fetch existing data
cursor.execute('''SELECT amount FROM income WHERE userId=?''', (userId,))
res = cursor.fetchone()
if res:
exIncome = res[0]
total_income = exIncome + new_income
cursor.execute('''UPDATE income SET amount = ? WHERE userId = ?''', (total_income, userId))
print(f"Updated! ${total_income} is in your account")
else:
cursor.execute('''INSERT INTO income (userId, amount) VALUES (?, ?)''', (userId, new_income))
print(f"Added ${new_income}")
connector.commit()
except ValueError:
print("Invalid!")
except sqlite3.Error as e:
print(f"Error: {e}")
finally:
connector.close()
#------------Savings Operations----------------
def add_savings(userId):
try:
connector = sqlite3.connect('expense_database.db')
cursor = connector.cursor()
saving_option = input("Do you want to add savings in 1. amount or 2. percentage: ")
if saving_option == "1":
new_savings = float(input("SAVINGS: $"))
elif saving_option == "2":
percentage = int(input("Percentage of income/100: "))
cursor.execute('''SELECT amount FROM income WHERE userId = ?''', (userId,))
amount = cursor.fetchone()[0] or 0.0
new_savings = amount * (percentage/100)
else:
print("Error try again!")
#Update Income also
cursor.execute('''SELECT amount FROM income WHERE userId = ?''', (userId,))
amount = cursor.fetchone()[0] or 0.0
total_income = amount - new_savings
cursor.execute('''UPDATE income SET amount = ? WHERE userId = ?''', (total_income, userId))
#Fetch savings amount if it alread existed
cursor.execute('''SELECT amount FROM savings WHERE userId = ?''', (userId,))
res = cursor.fetchone()
if res:
ex_savings = res[0]
total_savings = ex_savings + new_savings
cursor.execute('''UPDATE savings SET amount = ? WHERE userId = ?''', (total_savings, userId))
print(f"${total_savings} is savings balance")
else:
cursor.execute('''INSERT INTO savings(userId, amount) VALUES(?, ?)''', (userId, new_savings))
print(f"Added ${new_savings} to savings")
connector.commit()
except ValueError:
print("Invalid!")
except sqlite3.Error as e:
print(f"Error: {e}")
finally:
connector.close()
print("\n")
#-----------Expenses Operations------------
def add_expenses(userId):
connector = sqlite3.connect('expense_database.db')
cursor = connector.cursor()
cursor.execute('''SELECT amount FROM income WHERE userId=?''', (userId,))
amount = cursor.fetchone()
if amount[0] == 0:
print("No available Income")
return None
else:
category = input("CATEGORY (e.g Entertainment, Rent, Food): ")
new_expense = float(input("EXPENSE: $"))
#Fetch expenses that already existed for the category
cursor.execute('''SELECT amount FROM expenses WHERE userId = ? AND category = ?''', (userId, category))
res = cursor.fetchone()
if res:
X_expense = res[0]
total_expense = new_expense + X_expense
cursor.execute('''UPDATE expenses SET amount = ? WHERE userId = ? AND category = ?''', (total_expense, userId, category))
print(f"${category} expense is updated!")
else:
cursor.execute('''INSERT INTO expenses(userId, category, amount) VALUES(?, ?, ?)''', (userId, category, new_expense))
print(f"${new_expense} on ${category} is added")
connector.commit()
connector.close()
print("\n")
#Display All Accounts
def account_summary(userId):
connector = sqlite3.connect('expense_database.db')
cursor = connector.cursor()
#Program to fetch user total income
cursor.execute('''SELECT amount FROM income WHERE userId=?''', (userId,))
res = cursor.fetchone()
if res: income = res[0]
else: income = 0.0
#Program to fetch user total savings
cursor.execute('''SELECT amount FROM savings WHERE userId=?''', (userId,))
res = cursor.fetchone()
if res: savings = res[0]
else: savings = 0.0
#Program to fetch user's total expense
cursor.execute('''SELECT SUM(amount) FROM expenses WHERE userId = ?''', (userId,))
res = cursor.fetchone()
total_expenses = res[0] if res[0] is not None else 0
current = income - total_expenses
print("\n------ Finance Summary ------")
print(f"Total Income: ${income}")
print(f"Savings: ${savings}")
print(f"Total Expenses: ${total_expenses}\n")
print(f"Current: ${current}\n")
print("--- Expenses BreakDown ---")
cursor.execute('''SELECT category, amount FROM expenses WHERE userId=?''', (userId,))
res = cursor.fetchall()
if not res:
print("No available expense")
else:
for category, amount in res:
print(f"{category} : ${amount}\n")
connector.close()
#-------Loop for user interaction---------
def main_menu():
userId = None
while not userId:
print("1. Register", " 2. Login", " 3. Exit")
login_status = input("OPTION: ")
if login_status == "1":
user_registration()
userId = user_login()
elif login_status == "2":
userId = user_login() #If successful, userId = True
# print(f"userId: {userId}")
elif login_status == "3":
print("Thank you for visiting")
return #Exits
else:
print("Invalid Option. Try again!")
while True:
print("---------------Expense Tracker----------\n")
print("1. Add Income")
print("2. Create Expense")
print("3. Add Savings")
print("4. View Account Summary")
print("5. Logout")
pick = input("OPTION: ")
if pick == "1":
add_income(userId)
elif pick == "2":
add_expenses(userId)
elif pick == "3":
add_savings(userId)
elif pick == "4":
account_summary(userId)
elif pick == "5":
userId = None
print("Logged out!")
break
else:
print("Invalid option, please try again!")
main_menu()
print("---------------Welcome to Expense Tracker----------\n")
main_menu()