This repository has been archived by the owner on Jul 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
428 lines (342 loc) · 16.6 KB
/
main.py
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
from __init__ import conn, start_connection
from funcs import *
import PySimpleGUI as sg
import datetime
import matplotlib.pyplot as plt
'''
NOTE (25-06-2019; 00:30): Use the layout from the multi_window.py file and modify it to the application's requirement. The thing is, that's working.
And I think one of the major causes for my crashes is that I just haven't implemented it properly (e.g. the timeouts for the second ('Signup') window and the active flags). So, I'll try to get this up and running in about a week or so, if I'm lucky. Wish me luck! Also, don't worry, Raghav, it'll work eventually, and you're going to be smashing others projects in the face in the end. Believe in yourself. I'll go to sleep now, its 00:40. I'll have another go at this in the morning.
'''
'''
TODO (29/06/2019 19:46): Divide the dashboard and signup sections into seperate functions and call them in the main event loop.
'''
'''
NOTE (04-09-2019; 22:13): Sooo, I showed it to my techer and she said that the 'Notebook' part that I was thinking of can be put on hold for a while, which I totally agree too. I have no clue where to even start on building that thing, and I'm sure as hell not wasting my limited time on figuring it out.
'''
start_connection()
def strike(text):
result = ''
for c in text:
result = result + c + '\u0336'
return result
seven_july = '7th July'
user_fields = '(username,passwd,email_id,first_name,last_name)'
# login_window = sg.Window('Xpnsit v0.1')
# Tabs so that I could justify the fields and buttons
space1 = ' '
space2 = ' '
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Window states -> A check that's been applied so two instances of the same window don't occur. #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
newTransActive = False
notebookActive = False
analyticsActive = False
historyActive = False
dash_active = False
signup_active = False
# # # # # # # #
# Handy dates #
# # # # # # # #
today_date = str(datetime.date.today())
year = int(today_date[0:4])
month = int(today_date[5:7])
day = int(today_date[9:])
sg.ChangeLookAndFeel('NeutralBlue')
tooltips = [
'Log a new transaction',
'Quickly jot down transactions and make calculations. Export them to a csv file',
'View graphs of your expenditure and income history',
'See all of your transactions'
]
# # # # # # # # # # # # # # # # # # # #
# LOGIN AREA #
# # # # # # # # # # # # # # # # # # # #
layout = [
[sg.Text('Xpnsit', font=('Helvetica', 15), justification='center')],
[sg.T(space1), sg.Text('Username', size=(15, 1)),
sg.InputText(key='_name_')],
[sg.T(space1), sg.Text('Password', size=(15, 1)),
sg.InputText(key='_password_', password_char='*')],
[sg.T('')],
[sg.T(space2), sg.Button('Login', tooltip='Login', bind_return_key=True),
sg.Button('Signup', tooltip='Signup (if you haven\'t already)')]
]
login_window = sg.Window('Xpnsit v0.1').Layout(layout)
# Calling the login window and starting an event loop
i = 0
while True:
# if not dash_active or not signup_active:
event, values = login_window.Read(timeout=100)
if event != sg.TIMEOUT_KEY:
print(i, event, values)
if event is None or event == 'Exit':
break
if event == 'Signup' and not signup_active:
signup_active = True
signup_layout = [
[sg.Text('Signup', justification='center', font='Verdana, 15')],
[sg.Text('Fields marked with an asterisk (*) are compulsory')],
[sg.Text('Username * :'), sg.Input(do_not_clear=False,
key='u_name'), sg.Text(' ', key='name_check')],
[sg.Text('Password * :'), sg.Input(do_not_clear=False,
key='pass', password_char='*')],
[sg.Text('Confirm Password * :'), sg.Input(do_not_clear=False,
key='pass_conf', password_char='*'), sg.Text(' ', key='pass_check')],
[sg.Text('E-mail ID :'),
sg.Input(do_not_clear=False, key='email')],
[sg.Text('First Name * :'),
sg.Input(do_not_clear=False, key='fname')],
[sg.Text('Last Name * :'),
sg.Input(do_not_clear=False, key='lname')],
[sg.Button('Cancel'), sg.Text(space1), sg.Button(
'Create account', button_color=('white', '#008000'))]
]
signup = sg.Window('Signup').Layout(signup_layout)
if not dash_active and event == 'Login':
# dash_active = True
print(event, values)
u_name = values['_name_']
pwd = values['_password_']
login_cursor = conn.cursor()
login_cursor.execute(f"select username,passwd from users;")
if (u_name, pwd) in login_cursor.fetchall():
login_window.Hide()
dash_active = True
# __From here begins the dashboard page__
details = conn.cursor()
details.execute(f"select * from users where username = '{u_name}'")
current_user_details = cud = details.fetchall()
'''
TODO:Change the layout such that it shows the users transaction history on login, and having the other functions in or tabs to the side. Yes, it'll be a pain in the arse, but the current layout looks hideously preposterous, you can't deny that. I'll keep this as a todo till I first figure out the functions themselve and create at least a working model of the app. (25/06/2019 15:04)
'''
dashboard_butt_col_layout = [
[sg.Text("XPNSIT", font=("Helvetica", 25), justification='center')],
[sg.Button('Manage Transactions', size=(10, 3),tooltip = tooltips[0]),
sg.Button('Notebook', size=(10, 3),tooltip = tooltips[1])],
[sg.Button('Analytics', size=(10, 3),tooltip = tooltips[2]), sg.Button(
'Transaction History', size=(10, 3),tooltip = tooltips[3])],
]
dash_layout = [
[sg.Column(dashboard_butt_col_layout)],
# [sg.Text("Welcome to Xpnsit, {}!".format(u_name) )],
# [sg.Text(" Take a look around to make yourself at home")],
# [sg.T('')]
]
dashboard = sg.Window('Dashboard - Xpnsit v0.1', dash_layout, default_button_element_size=(10, 3),
size=(512, 200), text_justification='center')
# break
else:
sg.PopupError(
"Invalid username or password. Please try again.", title='Error')
# Event loop which corresponds to each button function
##########
# Signup #
##########
if signup_active:
butt_event_signup, sign_details = signup.Read(timeout=0)
if butt_event_signup != sg.TIMEOUT_KEY:
print('Signup Event -->', butt_event_signup)
print(butt_event_signup, sign_details)
if butt_event_signup == 'Cancel' or butt_event_signup is None:
# login_window.UnHide()
signup_active = False
signup.Hide()
# break
if check_of_existence_of(sign_details['u_name']) is True:
signup.FindElement('name_check').Update('Available!')
else:
signup.FindElement('name_check').Update(
'Username taken already')
if butt_event_signup == 'Create account':
sign_dets = []
dets = ''
if sign_details['email'] == '':
sign_details['email'] = 'NULL'
correct_info = False
for (key, value) in sign_details.items():
if value == '' and (key != 'email' or 'pass_conf'):
correct_info = False
error = 'incorrect_vals'
break
elif key == 'pass_conf':
if value != sign_details['pass']:
correct_info = False
error = 'no_pass_match'
break
else:
correct_info = True
print(sign_dets)
if correct_info == True:
for (key, value) in sign_details.items():
if key not in ('pass_conf', 'name_check', 'pass_check'):
sign_dets.append(value)
if key != 'u_name':
dets = dets + ',' + repr(value)
else:
dets += repr(value)
print(dets)
query = f'insert into users {user_fields} values ({dets});'
print(query)
signup_cursor = conn.cursor()
signup_cursor.execute(query)
conn.commit()
if check_of_existence_of(sign_details['u_name']):
lt = [
[sg.Text('Signup Success!')],
[sg.Button('Return to Login')]
]
success = sg.Window('Success', lt)
while True:
s_eve, s_val = success.Read()
if s_eve == 'Return to Login' or s_eve is None:
success.Close()
signup.Hide()
login_window.UnHide()
signup_active = False
break
elif correct_info == False and error == 'incorrect_vals':
signup_active = False
sg.PopupError('Please fill required fields')
elif correct_info == False and error == 'no_pass_match':
signup_active = False
sg.PopupError("Passwords don't match")
#############
# Dashboard #
#############
if dash_active:
'''
TODO: Make the second dashboard column a sort of mini guide about what the button leads to. Look for some on_hover function if available and link it to the button and button info
(EDIT (04/08/19): No, we're not doing that. Instead I've added tooltips to the main buttons.)
'''
dash_event, values = dashboard.Read()
if dash_event != sg.TIMEOUT_KEY:
print('Dashboard', dash_event)
if dash_event in ('Exit', 'Log Out', None):
dash_active = False
dashboard.Close()
login_window.UnHide()
login_window.Refresh()
# """
# _ _
# | | __ _ _ _ ___ _ _| |_ ___
# | | / _` | | | |/ _ \| | | | __/ __|
# | |__| (_| | |_| | (_) | |_| | |_\__ |
# |_____\__,_|\__, |\___/ \__,_|\__|___/
# |___/
# """
#############################
# New/Manage Transaction(s):-
#############################
elif not newTransActive and dash_event == 'Manage Transactions':
newTransActive = True
dash_active = False
dashboard.Hide()
new_trans_layout = [
[sg.Text(space1), sg.Txt("New Transaction")],
[sg.T('')],
[sg.Text('Name/Particulars:'), sg.Input()],
[sg.Text('Amount:'), sg.Input(do_not_clear=True, default_text='0', size=(10, 2), key='whole'), sg.T('.'), sg.Input(do_not_clear=True, default_text='00', size=(10, 2), key='deci')],
[sg.Text('Type:'), sg.InputCombo(['Income', 'Expense'],key = 'type',readonly = True)],
[sg.Text('Date of Transaction:'), sg.CalendarButton(button_text=None, target='date', format='%Y-%m-%d', default_date_m_d_y=(month, day,year), key='calendar',image_filename='git\Xpnsit\Expense Mangement System [Half Yearly]\calendar1.png',image_subsample = 20), sg.Text(" ", size=(15, 1), key='date')],
[sg.Button("Enter"), sg.T(' '), sg.Button('Exit')]
]
new_trans = sg.Window('New Transaction', new_trans_layout)
############
# Notebook :-
############
elif not notebookActive and dash_event == 'Notebook':
sg.Popup('Under construction!','Deadline '+ strike(seven_july) + ' early to mid September')
#############
# Analytics :-
#############
elif not analyticsActive and dash_event == 'Analytics':
sg.Popup('Under construction!', 'Deadline ' + strike(seven_july) + ' early to mid September')
#######################
# Transaction History:-
#######################
elif not historyActive and dash_event == 'Transaction History':
historyActive = True
dash_active = False
dashboard.Hide()
# sg.PopupAnimated('833.gif',message='Loading',)
hist_cursor = conn.cursor()
# param = 'particulars'
hist_query = f"select particulars,exp_type,amount,exp_date from transactions where user_id = {cud[0][0]} order by particulars desc;"
hist_cursor.execute(hist_query)
history_values = hist_cursor.fetchall()
headings = ['Particulars','Type','Amount','Date']
rec_no = len(history_values)
hist_lt = create_hist_layout()
##right_click_menu = ['Delete','Modify']
history = sg.Window('Transaction History',hist_lt)
#############################
# New/Manage Transaction(s):- (Layout on line 280 or somewhere around there)
#############################
while newTransActive:
nt_event, nt_values = new_trans.Read()
print(repr(nt_event), nt_values)
# imwatchingyou.refresh_debugger()
if nt_event is None or nt_event == 'Exit':
print('Exited from the New Transaction window')
dash_active = True
new_trans.Close()
dashboard.UnHide()
newTransActive = False
break
# newTransActive = True
if 'date' in nt_values.keys():
print(nt_values['date'])
######################################################################
# Dates: For verifying that the user hasn't put a date AHEAD of time #
######################################################################
dated_date = repr(nt_values['date'])
todays_date = repr(datetime.date.today())
print(todays_date)
if dated_date < todays_date:
# nt_values['date'] = nt_values['date'].strftime()
new_trans.FindElement('date').Update(
nt_values['date'].strftime('%d-%m-&y'))
print(nt_values['date'])
elif dated_date > todays_date:
error = 'invalid_date'
sg.PopupError(
f"Please enter valid date (Today's date : {todays_date})")
if nt_values['type'] == 'Income':
# nt_values['type'] = 'CR'
exp_type = 'CR'
elif nt_values['type'] == 'Expense':
# nt_values['type'] = 'DR'
exp_type = 'DR'
if nt_event == 'Enter':
amt = str(nt_values['whole']) + '.' + str(nt_values['deci'])
nt_cursor = conn.cursor()
trans_vals = list(nt_values.values())
q = f"insert into transactions (user_id,username,particulars,exp_type,amount,exp_date) values ({cud[0][0]}, '{cud[0][1]}', '{trans_vals[0]}', '{exp_type}', {amt} , '{nt_values['date']}' );"
print(q)
try:
nt_cursor.execute(q)
except:
sg.PopupError('Transaction not entered')
finally:
conn.commit()
vals = (cud[0][1], trans_vals[0], exp_type, float(amt))
print(vals)
temp_cursor = conn.cursor()
query1 = f"select username,particulars,exp_type,amount from transactions where user_id = {cud[00[0]][0]};"
temp_cursor.execute(query1)
fetch = temp_cursor.fetchall()
for i in fetch:
print(i)
if vals == fetch[-1]:
sg.Popup('Operation Successful!')
newTransActive = False
new_trans.Close()
break
else:
sg.PopupError('Operation Cancelled due to technical failure.', 'Please try again')
#######################
# Transaction History:-
#######################
if historyActive:
action_history()
login_window.Close()