-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenesis.py
8078 lines (7117 loc) · 448 KB
/
Genesis.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Codename Genesis - 5674/87394.050-9
GENESIS BM
©2017-2019 Cortex™ - a direct subsidiary of Vortex Enterprise International™ - all rights reserved.
"""
try:
import tkinter as tk
from tkinter import ttk, messagebox, filedialog, scrolledtext, simpledialog
except ImportError:
import Tkinter as tk
from Tkinter import ttk, messagebox, filedialog, scrolledtext, simpledialog
paypal_mode = 'paypal_live'
version = '5.67'
website = "http://vortexenterpriseco.wixsite.com/vortex"
#user access levels:
# 1 = teacher/supervisor
# 2 = CEO
# 3 = Chief Officers
# 4 = Key Employees
# 5 = Basic employees
# 4 and 5 are just status', they do not differ in restrictions
class Main:
def __init__(self, parent):
#parent is the root window - Tk()
self._top = parent
parent.title("Starting Up...")
#following lines catch if user tries to close the window
parent.protocol('WM_DELETE_WINDOW', self.file_exit)
#the icon for the root window: .xbm for linux; .ico for windows
try:
parent.wm_iconbitmap("Images/young enterprise 1.ico")
except:
parent.wm_iconbitmap("@Images/young enterprise 1.xbm")
parent.geometry("800x600")
self.showDebug = tk.StringVar()
#accelerators are the shortcuts
self.accelerators(parent)
#fonts stored for a consistent UI
self.fonts = ['Helvetica 14 bold', 'Helvetica 11 bold italic', 'Helvetica 10', 'Helvetica 10 italic',
'Helvetica 11 bold', 'Helvetica 22 bold']
#the following are characters that inputted names cannot have. This list is used in the validName function
self.invalidChar = ['0','1','2','3','4','5','6','7','8','9','!','£','$','%','^','&','*','(',')','+','=','{','}',
'[',']',';','@','~','#','<','>','?','/','\\','|','¬','`','¦','"',"'"]
#used for the treeview sorting algorithm
self.lastCol = [None, 1]
#used to generate pseudo random unique IDs
self.IDCounter = 1
#initialising certain variables for a user currently not logged in
self.registrationProgress = False
self.create_user = False
self.user_details = {}
self.login_status = False
self.redirect = []
self.metadata = {}
#parses the config.ini file to get the mysql data, the ebay public and private key and the email addresses for
# email functionality
self.db_config = self.parse_file('config.ini', 'mysql')
self.ini_db = self.db_config.copy()
self.ebay_config = self.parse_file('config.ini', 'eBay_key')
self.main_db = self.db_config.copy()
self.mail_details = self.parse_file('config.ini', 'company')
self.MailServer = (self.mail_details['server_email'],
"".join([x for x in self.mail_details['server_email_password'] if
x not in ['*', '&', '9', '7', '3',
'4', '5', '6', '8', '|',
'~', '^', '+', '?', '#',
'l', 's']])
)
self.frames = {}
self.currentFrame = ""
#this initialises all the frames needed before logging in. It instantiates these classes and creates the
# frames
self._pendingF = [[Load, '#ffffff'], [Login, '#ffffff'], [Create, '#ffffff']]
for F in self._pendingF:
self.instantiateFrame(F)
#loads the loading frame which introduces the program and starts the 'cinematic' entrance
self.changePage("Load", 'Starting Up...')
#calls the method 'configure' from the module paypalrestsdk and configures it with the client secret and ID
paypal.configure(self.parse_file(filename='config.ini', section=paypal_mode))
logging.basicConfig(level=logging.INFO)
def registrationTicker(self, companyName=False):
#a variable that is false when a user is not in the process of registering a company, and true when they are.
self.registrationProgress = companyName
def getCreateUser(self):
#outputs to other frame classes whether a new user is being created
return self.create_user
def getDBdetails(self):
#get db details for the particular company
return self.db_config.copy()
def getInitDB(self):
#get the global db details which stores the data on each company, each username and the corresponding
# company, and the general stock information of each company. It helps link the user to their corresponding
# company and load their company's database
return self.ini_db.copy()
def getEbayDetails(self):
# returns the ebay api key
return self.ebay_config
def output_user(self):
# returns the user's details if a user is logged in. Otherwise, just returns false
if self.login_status:
return self.user_details.copy()
else:
return False
def update_user(self, details):
# updates the Main classes copy of the user's details with the argument for 'details'
self.user_details = details.copy()
def get_company_metadata(self):
#returns the data stored on the company from the main gobal database
return self.metadata.copy()
def getRedirect(self):
#gets the item from the top of the redirection stack
if len(self.redirect) >= 1:
return self.redirect.pop(-1)
else:
return False
def getAppearance(self, type):
#returns the appearance data structure requested. Currently, only returns font since that is the only data
# consistent appearance element I have implemented, but if a future developer wants to add a colour scheme
# element, then they could easily edit this and get the colour scheme for each frame class.
if type == 'font':
return self.fonts
def changePage(self, new, head):
# this whole method works to change the frame and remove the old frame (but still hold it in memory) so that
# only the active class's frames is displayed at any one time.
#checks if there is a frame open and if that frame is one of the class frames and if so, removes it from
# the display
if self.currentFrame and self.currentFrame in self.frames:
self.frames[self.currentFrame].place_forget()
#changes the root window title
self._top.title(head)
# checks if the frame that needs to be raised is the instance of a user defined class or the child of one
# if it is the class it is displayed and the currentFrame variable is updated
if new in self.frames:
self.frames[new].place(relx=0, rely=0, relheight=1, relwidth=1)
self.currentFrame = new
else:
#if it is a child, it is just raised to the front
self.frames[new].tkraise()
def parse_file(self, filename, section):
#function that gets the specific configuration details for different elements of the program from the
# config.ini file
self._parser = ConfigParser()
self._parser.read(filename)
self._config = {}
# if the specified section argument exists in the .ini file, it iterates through all the items and adds them
# to _config as a dictionary
if self._parser.has_section(section):
item = self._parser.items(section)
for x in item:
self._config[x[0]] = x[1]
else:
# in case the section doesn't exist since the .ini file is designed to be end user configurable
raise Exception('{0} not found in the {1} file'.format(section, filename))
return self._config
def addFrame(self, frames):
# frames given as a list of lists (with frames and background colour)
# iterates through the passed list of frames and adds them to the frames dictionary
self.recentFrames = []
for F in frames:
if not F[0].__name__ in self.frames:
frame_name = F[0].__name__
frame = F[0](self._top, self, F[1])
self.frames[frame_name] = frame
self.recentFrames.append(frame)
#used to call a method of one of the instantiated classes
return self.recentFrames
def destroyFrames(self, frames):
# frames given as a list to be completely removed
for F in frames:
self.frames[F].destroy()
del self.frames[F]
def load_company(self, companyDB, personalData, IDheaders, loginData, LoginHeaders):
#called after login to to setup the program for that user
#sets the database so that program can load details for the user's company
self.setCompanyDatabase(companyDB)
self.login_status = True
#destroys all the pre-login frames as they are not needed anymore
self.destroyFrames(['Load', 'Login', 'Create'])
#adds everything from the global database on the user to the user_details dictionary
self.user_details = {}
for column, data in zip(IDheaders, personalData):
self.user_details[column] = data
for column, data in zip(LoginHeaders, loginData):
self.user_details[column] = data
#passes each list item to instantiate all the classes to get the frames which display the company's data
self._pendingF = [[HomePage, '#ffffff'], [EventPage, '#ffffff'], [NotificationPage, '#ffffff'],
[EmployeePage, '#ffffff'],
[TransactionsPage,'#ffffff'],[BuyInventoryPage, '#ffffff'], [StocksPage, '#ffffff'],
[RefundsPage,'#ffffff'], [InventoryPage, '#ffffff'], [SettingsPage, '#ffffff']]
if self.user_details['Access_Level'] <= 2:
self._pendingF.append([CompanySettings, '#ffffff'])
for F in self._pendingF:
self.instantiateFrame(F)
#calls the method to create the menu to navigate between all the frames
self.build_menu(self._top, self.metadata['Company_Name'], self.user_details['Access_Level'])
def instantiateFrame(self, frameDet):
#actually takes a list : [frame, background Colour] and instantiates the frame with the specified background
# colour
#currently all BGs are white, but offers a quick colour change for someone trying to change the design layout
frame_name = frameDet[0].__name__
frame = frameDet[0](self._top, self, frameDet[1])
self.frames[frame_name] = frame
frame.place_forget()
def setCompanyDatabase(self, compDB):
# sets the company database configuration dictionary with the user's company so the right database is accessed
self.db_config['database'] = compDB
def set_company_metadata(self, companyName):
#accesses the global database with the company's name and accesses all their details and stores it as a
# distionary to be accessed by other classes later
#Throughout the program I automatically get the headers rather than manually entering them in case the
# database changes in the future to make it easier for s future developer
try:
self.conn = MySQLConnection(**self.ini_db)
if self.conn.is_connected() != True:
self.log_event(self.lineno(), "Database not connected contact the network admin.")
self.c = self.conn.cursor()
self.c.execute("SELECT * FROM companies WHERE Company_Name = %(name)s", {'name': companyName})
self.headers = self.c.description
self.metadata = {}
for a, b in zip(self.headers, self.c.fetchone()):
self.metadata[a[0]] = b
except Error as e:
#adds error with mysql to debug log
self.log_event(e, self.lineno())
finally:
self.conn.close()
return self.metadata
def setCreateUser(self, create=False):
#user is being created
self.create_user = create
def setRedirect(self, sFrame, sTitle, dFrame, dTitle, function=None):
# adds to redirection stack: [source frame, source title, destination frame, destination title, function to
# be called when redirected back]
self.redirect.append([sFrame, sTitle, dFrame, dTitle, function])
# changes the frame to the specified destination
self.changePage(dFrame, dTitle)
def accelerators(self, root):
# creates the global keyboard shortcut bindings
root.bind('<Control-h>', lambda event: webb.open(website))
root.bind('<Control-a>', lambda e: self.aboutInfo())
root.bind('<Control-q>', lambda e: self.file_exit())
def build_menu(self, root, title, UsrLevel):
# creates the menu bar used to move between frames/pages
self.menubar = tk.Menu(root)
self.filemenu = tk.Menu(self.menubar, tearoff=0)
self.filemenu.add_command(label="Home", command=lambda: self.changePage('HomePage', title + ": Home"))
self.filemenu.add_command(label="User Settings",
command=lambda: self.changePage('SettingsPage', title + ": User "
"Settings"))
self.filemenu.add_separator()
self.filemenu.add_command(label="Website", command=lambda: webb.open(website), accelerator='Ctrl+H')
self.filemenu.add_command(label="About", command=lambda: self.aboutInfo(), accelerator='Ctrl+A')
self.filemenu.add_separator()
self.filemenu.add_command(label="Exit", command=lambda: self.file_exit(), accelerator='Ctrl+Q')
self.menubar.add_cascade(label="Application", menu=self.filemenu)
self.companymenu = tk.Menu(self.menubar, tearoff=0)
self.companymenu.add_command(label="Notifications",
command=lambda: self.changePage('NotificationPage', title + ": Notifications"))
self.companymenu.add_command(label="Employees", command=lambda: self.changePage('EmployeePage',
title + ": Employees"))
self.companymenu.add_command(label="Project Management",
command=lambda: self.changePage('EventPage', title + ": Project Management"))
#access level conditional statement means any user at a level 2 or lower will not even see an option to edit
# company settings
if UsrLevel <= 2:
self.companymenu.add_separator()
self.companymenu.add_command(label="Company Settings", command=lambda: self.setRedirect('HomePage',
title + ": Home",
'CompanySettings',
title + ': Company Settings'))
self.menubar.add_cascade(label="Company", menu=self.companymenu)
self.financemenu = tk.Menu(self.menubar, tearoff=0)
self.financemenu.add_command(label="Stocks", command=lambda: self.changePage('StocksPage',
title + ": Stocks"))
self.financemenu.add_command(label="Transactions", command=lambda: self.changePage('TransactionsPage',
title + ": Transactions"))
self.menubar.add_cascade(label="Finance", menu=self.financemenu)
self.inventorymenu = tk.Menu(self.menubar, tearoff=0)
self.inventorymenu.add_command(label="Buying", command=lambda: self.changePage('BuyInventoryPage',
title + ": Buying"))
self.inventorymenu.add_command(label="Sales",
command=lambda: self.changePage('RefundsPage', title + ": Sales"))
self.inventorymenu.add_command(label="Graphs and Data", command=lambda: self.changePage('InventoryPage',
title + ": Inventory "
"Data"))
self.menubar.add_cascade(label="Inventory", menu=self.inventorymenu)
#adds the menubar created in the function to the Tk() instance - root
root.config(menu=self.menubar)
def file_exit(self):
#function to confirm quitting the program
if messagebox.askokcancel('Quit', 'Really Quit?'):
if self.registrationProgress:
#
try:
self.conn = MySQLConnection(**self.ini_db)
if self.conn.is_connected() != True:
self.log_event(self.lineno(),"Database not connected contact the network admin.")
return
self.c = self.conn.cursor()
self.c.execute("DELETE FROM companies WHERE Company_Name=%(name)s", {'name':self.registrationProgress})
except Error as e:
self.log_event(e, self.lineno())
finally:
self.conn.commit()
self.conn.close()
self._top.quit()
def isfloat(self, value):
#checks if a value is a float
try:
float(value)
return True
except ValueError:
return False
def validName(self, name):
for i in self.invalidChar:
if i in name:
return False
return True
def sortItem(self, column, tree, alternateSort=True):
# sorts a treeview widget by the column that is passed on function call. This function is called throughout
# the program from different classes
self.data = []
money = False
#gets all tree rows
#converts data to integer, float or (keep as) string to ensure accurate sorting of data
for k in tree.get_children(''):
item = tree.set(k, column)
if not money:
if list(item)[0] == '£':
money = True
if money:
item = list(item)
del item[0]
item = ''.join(item)
if item.isnumeric():
self.data.append([int(item), k])
elif self.isfloat(item):
self.data.append([float(item), k])
else:
self.data.append([item, k])
#checks if the column was sorted before. This small algorithm causes the treeview list to be sorted in
# reverse every even number of times the column header is clicked
if self.lastCol[0] == column and alternateSort:
if self.lastCol[1] % 2 == 0:
self.data.sort(reverse=False, key=lambda v: v[0])
else:
self.data.sort(reverse=True, key=lambda v: v[0])
self.lastCol[1] += 1
else:
self.data.sort(reverse=False, key=lambda v: v[0])
self.lastCol = [column, 1]
if money:
for x in self.data:
x[0] = '£'+str(x[0])
#moves the items back into the treeview in the sorted order
for index, (val, k) in enumerate(self.data):
tree.move(k, '', index)
def searchItem(self, column, word, tree, treelist):
#searches through the treeview and removes all the items that do not contain the specified keyword
word = word.lower()
self.data = [(tree.set(k, column), k) for k in treelist]
tree.detach(*treelist)
self.index = 0
for (val, k) in self.data:
if word in val.lower():
tree.detach(k)
tree.move(k, '', self.index)
self.index += 1
def getID(self):
#creates a psuedo-random id based on the date and the number of function calls (looped between 1 and 20)
date = dt.datetime.now()
uniqueIDlist = [str(date.year), str(date.month), str(date.day), str(date.hour), str(date.minute),
str(date.second), "%02d" % (self.IDCounter,)]
id = "".join(uniqueIDlist)
#this value added to the end stops data collisions where multiple users might be adding a piece of data at
# the same time
if self.IDCounter < 20:
self.IDCounter += 1
else:
self.IDCounter = 1
return id
def email_compiler(self, *mailList):
#each mailList item should be a list in the form: [From, To, Subject, Body, Cc]
#establishes an SMTP connection to the gmail smtp servers on the port 587
self.server = SMTP('smtp.gmail.com', 587)
self.server.ehlo()
self.server.starttls()
# uses the configuration details taken from the config.ini file, stored in the MailServer dictionary,
# to login to the gmail mail server to send emails from that account
self.server.login(self.MailServer[0], self.MailServer[1])
#sends multiple emails on the same connection
for x in range(len(mailList)):
#constructs the email
self.msg = MIMEMultipart()
self.msg['From'] = "Vortex Enterprise International"
self.msg['To'] = mailList[x][1]
# if a 5th item is provided for the list item, it adds this list of names to be CC'd
if len(mailList[x]) == 5:
self.msg['Cc'] = ",".join(mailList[x][4])
self.msg['Subject'] = mailList[x][2]
#also sends the details of the user that performed this action. This helps not only prevent abuse of the
# system, but also helps the recipient know who they need to reply to
if self.login_status is True:
self.user_info = "Username: {0}\nFirst Name: {1}\nLast Name: {2}\nEmail: {3}\nRole: {4}" \
.format(self.user_details['Username'], self.user_details['First_Name'],
self.user_details['Last_Name'], self.user_details['Email'], self.user_details['Role'])
else:
self.user_info = 'Unknown - Sender did not login'
#the message skeleton
self.body = """
Please DO NOT REPLY to this email. The sender is: {0}
************************************************************************************
{1}
----Details----
{2}
""".format(mailList[x][0], mailList[x][3], self.user_info)
#creates the email
self.msg.attach(MIMEText(self.body, 'plain'))
self.text = self.msg.as_string()
#sends the email (with or without the CC depending on arguments)
try:
if len(mailList[x]) == 5:
self.server.sendmail(self.MailServer[0], [mailList[x][1]]+mailList[x][4], self.text)
else:
self.server.sendmail(self.MailServer[0], mailList[x][1], self.text)
except:
tk.messagebox.showerror("Error", "That email is invalid. The program will now exit. Use the access "
"code to create a new user when next opening the application.")
self._top.quit()
#closes server
self.server.quit()
def aboutInfo(self):
#display info about the program
messagebox.showinfo("About Genesis™ BM", """Genesis™ Business Management
Version: {}
© Adrian Soosaipillai 2020
""".format(version))
def lineno(self):
# Returns current line number in program
return inspect.currentframe().f_back.f_lineno
def log_event(self, event, line="Unknown"):
#add text and the line number (if passed) to the debug log
self.debug_event = [dt.datetime.now(), line, event]
self.debug_string = "{0}: {1} -- Line: {2}".format(dt.datetime.now(), event, line)
print(self.debug_string)
class Load(tk.Frame):
def __init__(self, parent, controller, _bg):
#initialising the frame with some key variables including the root (Tk()), controller ('Main' class), and fonts
super().__init__(parent, bg=_bg)
self.place(relx=0, rely=0, relheight=1, relwidth=1)
self._top = parent
self._controller = controller
self.fonts = controller.getAppearance('font')
# creating all the label widgets for the booting up page
self._title = tk.Label(self, text="Genesis BM", fg="black", font=self.fonts[0], bg=_bg)
self._details = tk.Label(self,
text="Business Management Solution\n\nDeveloped for: Young Enterprise\n Created by: "
"Adrian",font=self.fonts[1], bg=_bg)
#adding the logo image
self.IMG = tk.PhotoImage(file='Images/young enterprise 2.gif')
self._Logo = tk.Label(self, image=self.IMG, bg=_bg)
self._Logo.image = self.IMG
#creating the button widgets for the booting up page. These widgets navigate to a registration page for a new
# user or a log in page for an existing user
self._login = tk.Button(self, bg=_bg, text="Login to your company", command=lambda: self._controller.changePage(
"Login","Login"),fg='black', font=self.fonts[1])
self._new = tk.Button(self, text="Register a new company", command=lambda: self._controller.changePage(
"Create","Create New Company"), bg='white', fg='black', font=self.fonts[1])
#placing all widgets onto the frame
self._title.place(relx=0.5, rely=0.1, anchor='center')
self._details.place(relx=0.5, rely=0.25, anchor='center')
self._Logo.place(relx=0.5, rely=0.55, anchor='center')
self._login.place(relx=0.3, rely=0.75, anchor='center', height=50)
self._new.place(relx=0.7, rely=0.75, anchor='center', height=50)
class Login(tk.Frame):
def __init__(self, parent, controller, _bg):
# create the login frame - setting values for the root window, controlling class (Main), default
# background colour, fonts and database configuration details
super().__init__(parent, bg=_bg)
self.place(x=0, y=0, relheight=1, relwidth=1)
self._top = parent
self._controller = controller
self.fonts = controller.getAppearance('font')
self.db = self._controller.getDBdetails()
self.ini_db = self._controller.getInitDB()
self._bg = _bg
# variables to stored the username and password entries
self.Username = tk.StringVar()
self.Password = tk.StringVar()
#counter to stop brute force
self.attempts = 0
#creates the widgets that make up the frame including the title, entry elements and labels instructing
# users what to enter
self._head = tk.Label(self, text="Welcome. Please login.", bg=_bg,
font=self.fonts[0])
self._head.place(relx=0.35, rely=0.1, relheight=0.05, relwidth=0.3)
self._usernameL = tk.Label(self, text="Username", bg=_bg, font=self.fonts[1], anchor='e')
self._usernameL.place(relx=0.2, rely=0.2, relheight=0.05, relwidth=0.15)
self._usernameE = tk.Entry(self, textvariable=self.Username, bg=_bg, font=self.fonts[2])
self._usernameE.place(relx=0.38, rely=0.2, relheight=0.05, relwidth=0.32)
self._usernameE.focus_set()
self._passwordL = tk.Label(self, text="Password", bg=_bg, font=self.fonts[1],
anchor='e')
self._passwordL.place(relx=0.2, rely=0.28, relheight=0.05, relwidth=0.15)
self._passwordE = tk.Entry(self, textvariable=self.Password, bg=_bg, font=self.fonts[2], show="•")
self._passwordE.place(relx=0.38, rely=0.28, relheight=0.05, relwidth=0.32)
#button to show and hide the password plaintext
self._showPassB = tk.Checkbutton(self, text="Show/Hide Password", bg=_bg, activebackground=_bg,
command=self.show_password,font=self.fonts[2])
self._showPassB.place(relx=0.23, rely=0.35, relheight=0.05, relwidth=0.2)
#binding means that it will login by just pressing enter after en
self._passwordE.bind("<Return>", lambda e: self.check_login())
self._usernameE.bind("<Return>", lambda e: self.check_login())
# buttons to call the login, create user and forgotten password functions respectively
self._loginB = tk.Button(self, text="Login", bg=_bg, command=self.check_login, font=self.fonts[2])
self._loginB.place(relx=0.6, rely=0.35, relheight=0.05, relwidth=0.1)
self._createUserB = tk.Button(self, text="Create User", bg=_bg, command=self.create_user, font=self.fonts[2],
activebackground=_bg, highlightthickness=0, bd=0)
self._createUserB.place(relx=0.27, rely=0.5, relheight=0.05, relwidth=0.1)
self._forgotB = tk.Button(self, text="Forgotten Password", bg=_bg, command=self.forgotten_password,
font=self.fonts[2], activebackground=_bg, highlightthickness=0, bd=0)
self._forgotB.place(relx=0.52, rely=0.5, relheight=0.05, relwidth=0.15)
def forgotten_password(self):
# frame to reset password - it is called when the forgotten password button is pressed to create the frame
# for the user to enter their email, passphrase and username so the program can reset their password
self.ForgotFrame = tk.Frame(self, bg=self._bg)
self.ForgotFrame.place(relx=0, rely=0, relheight=1, relwidth=1)
self._head = tk.Label(self.ForgotFrame, text="Reset your Password", bg=self._bg, font=self.fonts[0])
self._head.place(relx=0.35, rely=0.07, relheight=0.05, relwidth=0.3)
self._email = tk.StringVar()
self._emailL = tk.Label(self.ForgotFrame, text="Email", bg=self._bg, font=self.fonts[1], anchor='w')
self._emailL.place(relx=0.3, rely=0.15, relheight=0.05, relwidth=0.13)
self._emailE = tk.Entry(self.ForgotFrame, textvariable=self._email, bg=self._bg, font=self.fonts[2])
self._emailE.place(relx=0.44, rely=0.15, relheight=0.05, relwidth=0.24)
self._user = tk.StringVar()
self._UserL = tk.Label(self.ForgotFrame, text="Username", bg=self._bg, font=self.fonts[1], anchor='w')
self._UserL.place(relx=0.3, rely=0.22, relheight=0.05, relwidth=0.13)
self._UserE = tk.Entry(self.ForgotFrame, textvariable=self._user, bg=self._bg, font=self.fonts[2])
self._UserE.place(relx=0.44, rely=0.22, relheight=0.05, relwidth=0.24)
self._passphrase = tk.StringVar()
self._passphraseL = tk.Label(self.ForgotFrame, text="Passphrase", bg=self._bg, font=self.fonts[1], anchor='w')
self._passphraseL.place(relx=0.3, rely=0.29, relheight=0.05, relwidth=0.13)
self._passphraseE = tk.Entry(self.ForgotFrame, textvariable=self._passphrase, bg=self._bg, font=self.fonts[2])
self._passphraseE.place(relx=0.44, rely=0.29, relheight=0.05, relwidth=0.24)
#calls the function to validate all the information entered into the above three fields
self._submitB = tk.Button(self.ForgotFrame, text="Submit", bg=self._bg, font=self.fonts[2], command=self.reset_password)
self._submitB.place(relx=0.46, rely=0.39, relheight=0.05, relwidth=0.08)
#when the enter button is pressed on the forgotten password frame, the program proceeds to reset the password
self._passphraseE.bind("<Return>", lambda e: self.reset_password())
#returns back to the main login part of the frame class
self._backB2 = tk.Button(self.ForgotFrame, text="Back", bg=self._bg, font=self.fonts[2],
command=lambda: self.back(self.ForgotFrame))
self._backB2.place(relx=0.4, rely=0.39, relheight=0.05, relwidth=0.05)
def reset_password(self):
#creates a random password string
self._randPassword = ''.join(choice(ascii_uppercase + ascii_lowercase + digits)
for _ in range(10))
# connect to general mysql database
try:
self.conn = MySQLConnection(**self.ini_db)
if self.conn.is_connected() != True:
self._controller.log_event(self._controller.lineno(),
"Database not connected contact the network admin.")
return
self.c = self.conn.cursor()
#get the records where the username and email match the inputs
self.c.execute("SELECT * FROM users WHERE (Username, Email)=(%(usr)s,%(email)s)",
{'usr': self._user.get(), 'email': self._email.get()})
self.company_Name = self.c.fetchall()
#if there is a match, change the database value in the db dictionary to the user's company name
if self.company_Name:
self.db['database'] = self.company_Name[0][1]
else:
tk.messagebox.showerror("Invalid Input", "One of the entered details is incorrect.")
except Error as e:
self._controller.log_event(e, self._controller.lineno())
finally:
self.conn.close()
#connect to the user's company's private database
try:
self.conn = MySQLConnection(**self.db)
if self.conn.is_connected() != True:
self._controller.log_event(self._controller.lineno(),
"Database not connected contact the network admin.")
return
self.c = self.conn.cursor()
# find a matching record for the inputted username and passphrase
self.c.execute("SELECT * FROM login WHERE (Username, Passphrase)=(%(usr)s,%(pass)s)",
{'usr': self._user.get(), 'pass': self._passphrase.get()})
if self.c.fetchall():
#if record exists, alter password to random one created and set account status to 1, which means the
# next time the user logs in, they will be directed to the user settings page where they can change
# that random password to something more memorable
self.c.execute("UPDATE login SET Password=%(passw)s, Account_Status=1 WHERE Username=%(usr)s",
{'passw': self._randPassword, 'usr': self._user.get()})
#email that will be sent to the user
self._reset_email_body = """
Dear {0},
You have recently requested a password reset for the Genesis Business Management Application.
Your password: {1}
If you did not authorise this, you do not need to do anything, because this email is needed to access your account.
However, you will have to log in with this password next time regardless and change it under User Settings.
""".format(self._user.get(), self._randPassword)
#send the email
self._controller.email_compiler(["Vortex Enterprise International", self._email.get(),
"Genesis BM Password Reset",
self._reset_email_body])
# confirmation of email success
tk.messagebox.showinfo("Success",
"The password has been reset successfully. Please check your email for the "
"new password to login.")
self.back(self.ForgotFrame)
else:
#message to user to say that an input is invalid and does not match a record
tk.messagebox.showerror("Invalid Input", "One of the entered details is incorrect.")
except Error as e:
self._controller.log_event(e, self._controller.lineno())
finally:
self.conn.commit()
self.conn.close()
def create_user(self):
#creates the frame that gets the access code input in order to create a new user
self.CreateUsrFrame = tk.Frame(self, bg=self._bg)
self.CreateUsrFrame.place(relx=0, rely=0, relheight=1, relwidth=1)
#label, entry and button widgets are created and placed on the CreateUsrFrame frame
self._head = tk.Label(self.CreateUsrFrame, text="Create New User", bg=self._bg, font=self.fonts[0])
self._head.place(relx=0.4, rely=0.2, relheight=0.05, relwidth=0.2)
# instructions to guide new users of the system to create their account
self._instruct1 = tk.Label(self.CreateUsrFrame, text="Enter the access code of the company you wish to join. "
"If you wish to create a new company for your user, please restart this "
"application and choose 'Register a new company'.",
bg=self._bg, font=self.fonts[2],
wraplength=350, justify='center')
self._instruct1.place(relx=0.28, rely=0.28, relheight=0.11, relwidth=0.44)
self._access = tk.StringVar()
self._accessL = tk.Label(self.CreateUsrFrame, text="Access Code", bg=self._bg, font=self.fonts[1], anchor='w')
self._accessL.place(relx=0.3, rely=0.43, relheight=0.05, relwidth=0.13)
self._accessE = tk.Entry(self.CreateUsrFrame, textvariable=self._access, bg=self._bg, font=self.fonts[2])
self._accessE.place(relx=0.44, rely=0.43, relheight=0.05, relwidth=0.24)
self._accessE.focus_set()
self._confirmB = tk.Button(self.CreateUsrFrame, text="Go", bg=self._bg, font=self.fonts[2],
command=self.add_user)
self._confirmB.place(relx=0.49, rely=0.53, relheight=0.05, relwidth=0.05)
self._backB1 = tk.Button(self.CreateUsrFrame, text="Back", bg=self._bg, font=self.fonts[2],
command=lambda: self.back(self.CreateUsrFrame))
self._backB1.place(relx=0.43, rely=0.53, relheight=0.05, relwidth=0.05)
#the user doesn't have to press the 'Go' button. The bind function allows the user to just hit enter after
# entering their access code to proceed intuitively
self._accessE.bind("<Return>", lambda e: self.add_user())
def back(self, frame):
#destroys the passed frame instance and removes it from display
frame.destroy()
def add_user(self):
# validation to ensure a valid access code is entered
if not 0 < len(self._access.get()) <= 10:
tk.messagebox.showerror('Invalid Input',
'Ensure the access code does not exceed 10 characters.')
return
#connection to the general company database
try:
self.conn = MySQLConnection(**self.ini_db)
if self.conn.is_connected() != True:
self._controller.log_event(self._controller.lineno(),
"Database not connected contact the network admin.")
return
self.c = self.conn.cursor()
#get the record for the company with a matching access code
self.c.execute("SELECT Company_Name FROM companies WHERE BINARY Access_Code=%(access)s",
{'access':self._access.get()})
self._accessCompName = self.c.fetchall()
if not self._accessCompName:
tk.messagebox.showerror('Invalid Input','That access code is invalid.')
return
else:
#if there is a match, set _accessCompName equal to the company name only - a string
self._accessCompName = self._accessCompName[0][0]
except Error as e:
self._controller.log_event(e, self._controller.lineno())
#outputs the company associated with that access code and checks if the user really wants to register for
# that company
if not tk.messagebox.askyesno("Create User", "Do you want create a user for the "+self._accessCompName+" "
"company?"):
self._access.set("")
return
#navigate to the Create Employee frame and set some of the attributes of the Main class to contain the
# metadata of the company corresponding with the input access code
self._controller.setCreateUser(create=True)
self._controller.setCompanyDatabase(self._accessCompName)
self._controller.set_company_metadata(self._accessCompName)
self._controller.addFrame([[CreateEmployee, '#ffffff']])
self._controller.setRedirect("Login", "Login", "CreateEmployee", "Create New User")
#close the current create user frame
self.back(self.CreateUsrFrame)
def show_password(self):
#if the password field is currently showing '•', change it to plaintext, and vice versa
if self._passwordE.cget('show') == "":
self._passwordE.config(show="•")
else:
self._passwordE.config(show="")
def check_login(self):
#function logs in the user after they enter the username and password inputs
#connects to the general company database
try:
self.conn = MySQLConnection(**self.db)
if self.conn.is_connected() != True:
self._controller.log_event("Database not connected contact the network admin.",
self._controller.lineno())
self.c = self.conn.cursor()
#gets the corresponding company name for the username input
self.c.execute("SELECT Company_Name FROM users WHERE BINARY Username = %(user)s",
{'user': self.Username.get()})
self.company_ = self.c.fetchone()
except Error as e:
self._controller.log_event(e, self._controller.lineno())
self.conn.close()
return
finally:
self.conn.close()
if not self.company_:
tk.messagebox.showerror("Incorrect Input", "Your username or password is incorrect.")
#increment attempt counter to stop brute force attacks
self.attempts += 1
if self.attempts >= 3:
self.tooManyAttempts()
return
#if record is present, username is valid database is changed to the corresponding company name
if self.company_:
self.comp_db = self.db.copy()
self.comp_db['database'] = self.company_[0]
#connection to private, company database
self.conn = MySQLConnection(**self.comp_db)
if self.conn.is_connected() != True:
self._controller.log_event(self._controller.lineno(),
"Database not connected contact the network admin.")
self.c = self.conn.cursor()
#checks for records matching both username and password
self.c.execute("SELECT ID, Account_Status FROM login WHERE BINARY Username=%(user)s AND BINARY Password="
"%(pass)s",
{'user': self.Username.get(), 'pass': self.Password.get()})
self.id = self.c.fetchone()
if self.id:
#if record exists and inputs are valid...
if self.id[1] == 2:
#if Account Status = 2, do not allow user to login. Used to quickly block off a user's access in
# an emergency
tk.messagebox.showwarning('Account Locked', 'Your account has been locked by an admin. Please '
'contact them regarding this account ban.')
return
#update the last access time to the current one for the user's record
self.c.execute("UPDATE login SET Last_Accessed=CURRENT_TIMESTAMP WHERE Username = (%(user)s)",
{'user': self.Username.get()})
#get all data about the user
self.c.execute("SELECT * FROM staff WHERE ID=(%(id)s)",
{'id': self.id[0]})
self.personalID = self.c.fetchall()[0]
self.id_headers = self.c.description
self.id_headers = [elem[0] for elem in self.id_headers]
if not self.personalID:
self._controller.log_event("Fatal database error please contact company IT admin.",
self._controller.lineno())
tk.messagebox.showerror("Program Error", "There is an error with the database. Please contact the "
"system admin")
return
# get all data about the user's account
self.c.execute("SELECT * FROM login WHERE ID=(%(id)s)",
{'id': self.id[0]})
self.personalLogin = self.c.fetchall()[0]
self.login_headers = self.c.description
self.login_headers = [elem[0] for elem in self.login_headers]
self.personalLogin = list(self.personalLogin)
self.personalID = list(self.personalID)
self.company = self._controller.set_company_metadata(self.company_[0])
#output successful login
tk.messagebox.showinfo("Success", "You have successfully logged in.")
self.attempts = 0
#call the load company function of the Main class to load all the company's data for the user to access
self._controller.load_company(self.company_[0], self.personalID, self.id_headers,
self.personalLogin, self.login_headers)
self.redirection = self._controller.getRedirect()
if not self.redirection:
#change dimensions of the window
self._top.geometry("1100x700")
if self.id[1] == 0:
# if Account Status = 0, navigate to the home page
self._controller.changePage("HomePage", self.company['Company_Name'])
elif self.id[1] == 1:
# if Account Status = 1, navigate to the settings page and change account status to 0
self._controller.changePage("SettingsPage", self.company['Company_Name']+": User Settings")
self.c.execute("UPDATE login SET Account_Status=0 WHERE ID=%(id)s", {'id':self.id[0]})
else:
#navigate to the frame specified in the list from the redirection stack
self._controller.changePage(self.redirection[0], self.redirection[1])
self.redirection[4](self.personalLogin[0])
else:
tk.messagebox.showerror("Incorrect Input", "Your username or password is incorrect.")
#increment attempt counter
self.attempts += 1
if self.attempts >= 3:
self.tooManyAttempts()
self.conn.commit()
self.conn.close()
def tooManyAttempts(self):
#if 3 failed attempts, the program will output an error message and exit the application
tk.messagebox.showerror("Too many failed attempts", "You have performed too many failed attempts to log in. "
"The program will exit now. If you have forgotten your "
"password, please re-open the app and click "
"'Forgotten Password'.")
self._top.quit()
class CreateEmployee(tk.Frame):
def __init__(self, parent, controller, _bg):
# create the 'Create Employee' page - setting values for the root window, controlling class (Main), default
# background colour, fonts and database configuration details for both the specific company database and the
# general 'company' database
super().__init__(parent, bg=_bg)
self.place(relx=0, rely=0, relheight=1, relwidth=1)
self._top = parent
self._controller = controller
self.fonts = controller.getAppearance('font')
self._bg = _bg
self.db = controller.getDBdetails()
self.ini_db = controller.getInitDB()
self._currentUser = self._controller.output_user()
#newUser values:
# 1 = new user for existing company
# 2 = new user for new company
# 0 = editing existing user
if self._controller.getCreateUser():
self.NewUser = 1
else:
self.NewUser = 0
if not self._currentUser:
self.NewUser = 2
#data frame is the first page of details that the user needs to fill in. The following are labels, entry and
# combobox widgets that allow the user to input their data
self.dataFrame = tk.Frame(self, bg=_bg)
self.dataFrame.place(relx=0, rely=0, relheight=1, relwidth=1)
self._head1 = tk.Label(self.dataFrame, text="User Details", bg=_bg, font=self.fonts[0])
self._head1.place(relx=0.4, rely=0.03, relheight=0.05, relwidth=0.2)
self.initValues()
self._usernameL = tk.Label(self.dataFrame, text="Username", bg=_bg, font=self.fonts[1], anchor='w')
self._usernameL.place(relx=0.3, rely=0.1, relwidth=0.15, relheight=0.05)
self._usernameE = tk.Entry(self.dataFrame, textvariable=self._username, bg=_bg, font=self.fonts[2])
self._usernameE.place(relx=0.45, rely=0.1, relwidth=0.2, relheight=0.05)
self._usernameForm = tk.Label(self.dataFrame, text="Max. 15 char", bg=_bg, fg='gray', font=self.fonts[3],
anchor='w')
self._usernameForm.place(relx=0.66, rely=0.1, relheight=0.05, relwidth=0.14)
self._FNameL = tk.Label(self.dataFrame, text="First Name", bg=_bg, font=self.fonts[1], anchor='w')
self._FNameL.place(relx=0.3, rely=0.16, relwidth=0.15, relheight=0.05)
self._FNameE = tk.Entry(self.dataFrame, textvariable=self._FName, bg=_bg, font=self.fonts[2])
self._FNameE.place(relx=0.45, rely=0.16, relwidth=0.2, relheight=0.05)
self._FNameForm = tk.Label(self.dataFrame, text="Max. 25 char", bg=_bg, fg='gray', font=self.fonts[3],
anchor='w')
self._FNameForm.place(relx=0.66, rely=0.16, relheight=0.05, relwidth=0.14)
self._LNameL = tk.Label(self.dataFrame, text="Last Name", bg=_bg, font=self.fonts[1], anchor='w')
self._LNameL.place(relx=0.3, rely=0.22, relwidth=0.15, relheight=0.05)
self._LNameE = tk.Entry(self.dataFrame, textvariable=self._LName, bg=_bg, font=self.fonts[2])
self._LNameE.place(relx=0.45, rely=0.22, relwidth=0.2, relheight=0.05)
self._LNameForm = tk.Label(self.dataFrame, text="Max. 25 char", bg=_bg, fg='gray', font=self.fonts[3],
anchor='w')
self._LNameForm.place(relx=0.66, rely=0.22, relheight=0.05, relwidth=0.14)
self._EmailL = tk.Label(self.dataFrame, text="Email", bg=_bg, font=self.fonts[1], anchor='w')
self._EmailL.place(relx=0.3, rely=0.28, relwidth=0.15, relheight=0.05)
self._EmailE = tk.Entry(self.dataFrame, textvariable=self._Email, bg=_bg, font=self.fonts[2])
self._EmailE.place(relx=0.45, rely=0.28, relwidth=0.2, relheight=0.05)
self._EmailForm = tk.Label(self.dataFrame, text="Max. 100 char", bg=_bg, fg='gray', font=self.fonts[3],
anchor='w')
self._EmailForm.place(relx=0.66, rely=0.28, relheight=0.05, relwidth=0.14)
self._PhoneL = tk.Label(self.dataFrame, text="Phone Number", bg=_bg, font=self.fonts[1], anchor='w')
self._PhoneL.place(relx=0.3, rely=0.34, relwidth=0.15, relheight=0.05)
self._PhoneE = tk.Entry(self.dataFrame, textvariable=self._Phone, bg=_bg, font=self.fonts[2])