· 5 years ago · Nov 09, 2020, 06:52 PM
1import sqlite3
2import sys
3import os
4import os.path
5import time
6
7current_time = time.asctime(time.localtime(time.time()))
8
9
10class files_s:
11 def __init__(self):
12
13 print(10 * "=" + "Initialize logFiles" + "=" * 10)
14 self.rexists = os.path.isfile(".rec.txt")
15 self.lexists = os.path.isfile(".log.txt")
16 if self.rexists:
17
18 self.recFile = open(".rec.txt", "r") # this should always open in readmode
19 # if data is to be written to the file then it shoul be appended to the last line
20 # this is to ensure that the contents of the file isnt overwritten once the class is
21 # instantiated
22 else:
23 print("[+] Creating records file ")
24 self.recFile = open(".rec.txt", "w+")
25 # version 2 would be for handling logs
26 if self.lexists:
27
28 self.logFiles = open(".log.txt", "r")
29 else:
30 print("[+] Creating logs file")
31 self.logFiles = open(".log.txt", "w+")
32
33 def read_records(self):
34 for line in self.recFile:
35 text = line.strip()
36 commandList = text.split("#")
37 command = commandList[0]
38 casesLIST = commandList[-1]
39 casesLIST = casesLIST.split(" ")
40
41 if command == "RECORD":
42 # RECORD#1000#1#TIME#8,000#124#12,000#
43 i_d = int(commandList[1])
44 version = commandList[2]
45 time = commandList[3]
46 total_cases = commandList[4]
47 total_deaths = commandList[5]
48 total_visitors = commandList[6]
49 print(f"=" * 10 + "COVID RECORD " + f"verison:{version}" + "=" * 10)
50 print(f"The id number: {i_d}")
51 print(f"record version: {version}")
52 print(f"The time: {time}")
53 print(f"total cases: {total_cases}")
54 print(f"total deaths: {total_deaths}")
55 print(f"total visitors: {total_visitors}")
56 print(10 * "-" + "Cases per parish:" + "-" * 10)
57 for i in range(len(casesLIST)):
58 print(f"{casesLIST[i]}")
59
60 elif command == "endfill":
61 continue
62 # covidrecords.close()
63
64 def view_logs(self):
65
66 for line in self.logFiles:
67 text = line.strip()
68 commandList = text.split(",")
69 command = commandList[0]
70
71 if command == "LOG":
72 time = commandList[6] # deals with TIME
73 i_d = int(commandList[2])
74 usage = int(commandList[4])
75 print("=" * 10 + "LOG" + "=" * 10)
76
77 print(f"The id number: {i_d}")
78 print(f"program usage count: {usage}")
79 print(f"The time: {time}")
80
81 elif command == "CHANGES":
82 firstname = commandList[2]
83 lastname = commandList[4]
84 i_d = int(commandList[6])
85
86 print("=" * 10 + "CHANGE" + "=" * 10)
87 print(f"Firstname is: {firstname}")
88 print(f"Lastname is: {lastname}")
89 print(f"ID is: {i_d}")
90 elif command == "endfill":
91 print("End of file ")
92 self.logFiles.close()
93
94 def write_records(self, recordQry, cppList):
95 # this function can be seen as the edit records function due to its implementation
96 # this function should never overwrite a record
97 # this should only add a new record while incrementing the version and saving
98 # the admin id which was used to create that record
99 # rewrite this finction based on the write logs function
100 # thi should have 2 versions
101 # version 2 would accomodate editing records
102 # version 2 suggests that there should be a correlation between
103 # cases per parish to total number of cases
104 # i.e total number of cases should be calculated by adding all cases per parish
105 # cases per parish would have to be retrieved in a list
106 # cases per parish should be calculated before sent in the list
107 recFiles = open(".rec.txt", "r")
108 for line in recFiles:
109 text = line.strip()
110 commandList = text.split(",")
111 command = commandList[0]
112 if command == "endfill":
113 end = True
114
115 if end:
116 print("the end is true")
117 recFiles = open(".rec.txt", "a+")
118 recFiles.writelines(recordQry + cppList + "\n")
119 recFiles.close()
120 else:
121 recFiles.close()
122
123 print("writelogs ")
124
125 def write_logs(self, log_qry):
126
127 logFiles = open(".log.txt", "r")
128 for line in logFiles:
129 text = line.strip()
130 commandList = text.split(",")
131 command = commandList[0]
132 if command == "endfill":
133 end = True
134
135 if end:
136 print("the end is true")
137 logFiles = open(".log.txt", "a+")
138 logFiles.writelines(log_qry + "\n")
139 logFiles.close()
140 else:
141 logFiles.close()
142
143
144class database_s(files_s):
145 def __init__(self):
146 self.connnect = sqlite3.connect("CoIMaDS.db") # extablishes connection to database
147 # print(f"Established connection at: {self.connnect}")
148 self.cursor = self.connnect.cursor()
149 self.cursor.execute("""CREATE TABLE IF NOT EXISTS user (id_num PRIMARY KEY,
150 firstname TEXT,
151 lastname TEXT,
152 date_of_birth TEXT,
153 address TEXT,
154 parish TEXT,
155 gender TEXT,
156 date_of_arival TEXT,
157 lengh_of_stay int,
158 precondition TEXT,
159 covid_status TEXT,
160 date_of_last_labtest TEXT,
161 violator_status TEXT)
162 """)
163 # lengh of stay needs to be evaluated with checks
164 # all date attriutes should be evaluated with checks
165 # id is used to represent trn or ven respectively
166
167 # this class deals with the database
168 def add_user(self, args, ident):
169 self.args = args
170 self.ident = ident # ident test
171 try:
172 if self.args == 1:
173 # self.ident = input("Enter id: ") #ident test
174 firstname = input("Enter fistname: ")
175 lastname = input("Enter lastname: ")
176 date_of_birth = input("Enter date of birth: ")
177 address = input("Enter address: ")
178 parish = input("Enter parish: ")
179 gender = input("Enter gender: ")
180 date_of_arrival = input("Enter date of arival status: ")
181 length_of_stay = int(input("Enter length of stay: ")) # if trn user then this should be empty
182 precondition = input("Enter medical precondition: ")
183 covid_status = input("Enter covid status: ")
184 date_of_last_labtest = input("Enter date of recent labtest: ")
185 violator_status = input("Enter violator status: ")
186
187 update_qry = """UPDATE user SET id_num=?,firstname=?,lastname=?,date_of_birth=?,address=?,parish=?,gender=?,date_of_arrival=?,length_of_stay=?,precondition=?,covid_status=?,date_of_last_labtest=?,violator_status=? WHERE id_num=? """
188 data = (self.ident, firstname, lastname, date_of_birth, address, parish, gender, date_of_arrival,
189 length_of_stay, precondition, covid_status, date_of_last_labtest, violator_status,
190 self.ident) # last value is the idnum for the WHERE clause
191 self.cursor.execute(update_qry, data)
192 #################################
193 # possible add functionality to add tablenames to a flat file before
194 # they are sent to the database i.e firstname wille be appended to the file
195 # because the user has to add something to firstname
196
197 self.connnect.commit()
198 self.cursor.close() # closed curser
199 self.connnect.close() # closes database connection
200 print("[+] New user was added to the database")
201
202 elif self.args == 2: # admin level
203 # version 2 or the adduser functions takes the id from user input///
204 # this verison should only be used when all data is to be entered at once
205 # reguardless of if the user already initiated the program
206 id_num = input("Enter the id: ")
207 firstname = input("Enter fistname: ") # all other values should be added
208 self.cursor.execute("""INSERT INTO user (id_num,
209 firstname,
210 lastname,
211 date_of_birth,
212 address,
213 parish,
214 gender,
215 date_of_arrival,
216 length_of_stay,
217 precondition,
218 covid_status,
219 date_of_last_labtest,
220 violator_status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"""
221 , (id_num, firstname, lastname, date_of_birth, address, parish, gender,
222 date_of_arrival, length_of_stay, precondition, covid_status,
223 date_of_last_labtest, violator_status))
224 #################################
225 self.connnect.commit()
226 self.cursor.close() # closed curser
227 self.connnect.close() # closes database connection
228 print("[+] New user was added to the database")
229
230
231
232 except Exception as ex:
233 print(f"[!] Could not add user to the database: {ex}")
234
235 def search(self):
236 # id is used as unique identifier to search for each user in the database
237 # other methods of search can also be implemented such as
238 # show all users with names john brown etc
239 # this can be implemented with views or where statements
240 # self.args = args
241 # if self.args == 1:
242 # search function needs development
243 print("[+] you have selected the search option ")
244 # add logic to search by ex. search by firstname or date of entry etc
245 id_num = input("Enter the id to search: ")
246 self.cursor.execute("SELECT * FROM user WHERE id_num=?", (id_num,))
247 results = self.cursor.fetchone() # returnes values from database quary
248
249 if results:
250 print("[+] User found") # evaluate this line to return names
251 results_list = []
252 for i in range(len(results)): # this range is dependent on how much data is to be returned
253 results_list.append(results[i])
254
255 show_user(results_list, args=3) # show user 3 returns first name and id only
256 # add logic to return to homescreen
257 else:
258 print("[!] User not found")
259 self.cursor.close() # closes cursor if user not found
260 self.connnect.close() # closes database connection if user not found
261 # add logic to return to homescreen
262
263 def delete_user(self):
264 # this is the delete user function
265 print("[+] you have selected the Delete option ")
266 # add logic to search by ex. search by firstname or date of entry etc
267 id_num = input("Enter the id: ")
268 self.cursor.execute("SELECT * FROM user WHERE id_num=?", (id_num,))
269 results = self.cursor.fetchone() # returnes values from database quary
270
271 if results:
272 # evaluate this line to return names
273 print("[+] User found!")
274 results_list = []
275 for i in range(len(results)): # this range is dependent on how much data is to be returned
276 results_list.append(results[i])
277
278 show_user(results_list, args=3) # this returnes data of the user which was found
279 # add logic to return to homescreen
280
281 d = input("[*] would you like to delete this user? y or n: ")
282 try: # try catch needs to be evaluated
283 if d == "y" or "yes":
284 # execute the delete user quary
285 self.cursor.execute("DELETE FROM user WHERE id_num=?", (id_num,))
286 print("[*] User Removed!")
287 self.connnect.commit()
288 self.cursor.close() # closed curser
289 self.connnect.close()
290 #################################
291 # possible add functionality to add tablenames to a flat file before
292 # they are sent to the database i.e firstname wille be appended to the file
293 # because the user has to add something to firstname
294
295 # add logic to return to homescreen i.e call the usage function again
296 elif d == "n" or "no":
297 self.cursor.close()
298 self.connnect.close()
299 # add logic to return to homescreen
300 except:
301 print("[!] incorrect input") #### needs evaluation
302
303 else:
304 print("[!] User not found")
305 self.cursor.close() # closes cursor if user not found
306 self.connnect.close()
307 # closes database connection if user not found
308 # add logic to return to homescreen
309
310 def edit_user(self, args, ident):
311 # this is the edit user function or rather the update user function
312 # these functions need different versions to enforce acces levels in the progran
313 # each version of the function is implemented using args which are numbers passed
314 # to each version which initializes it
315 # this function will have an append verion where it is able to append data to the database
316 self.args = args
317 self.ident = ident
318 #################################
319 # functionality to update
320 # firstname,lastname,precondition,violator_status,covid_status
321 #
322 # add logic to search by ex. search by firstname or date of entry etc
323 if args == 1:
324 t = database_s()
325 t.add_user(args=1, ident=ident) # this edits everythong about an existing user
326
327
328 elif args == 2:
329
330 id_num = input("Enter the id: ")
331 self.cursor.execute("SELECT * FROM user WHERE id_num=?", (id_num,))
332 result = self.cursor.fetchone() # returnes values from database quary
333 if result:
334 print("[*] User found")
335 results_list = []
336 for i in range(len(result)): # this range is dependent on how much data is to be returned
337 results_list.append(result[i])
338 show_user(list=results_list, args=4) # returnes the users information
339
340 opt = input("Would you like to update this users data? y or n")
341 if opt == "y" or "yes":
342 firstname = input("Enter the firstname: ")
343 lastname = input("Enter the lastname: ")
344 precondition = input("Enter the precondition: ")
345 violator_status = input("Enter the violator status: ")
346 covid_status = input("Enter the covid status: ")
347 update_qry = """UPDATE user SET firstname=?,lastname=?,precondition=?,violator_status=?,covid_status=? WHERE id_num=? """
348 data = (firstname, lastname, precondition, violator_status, covid_status, id_num)
349 self.cursor.execute(update_qry, data)
350 self.connnect.commit()
351 self.cursor.close() # closed curser
352 self.connnect.close() # closes database connection
353 print("[+] user updated")
354
355 elif opt == "n" or "no":
356 pass
357
358
359 else:
360 print("[-] User not found")
361
362
363 elif args == 3:
364 pass
365
366 return
367 # rec handling was here
368
369
370def records_handling(args, ident): # possible add functionality to pass list with total deaths and visitors
371 # if not develop logic to add them
372 if args == 1:
373 print("add log ")
374 logsList = []
375 # usage will alwsys be equal to one however it will be used to add up total usage count
376 logsList.append(ident)
377 logsList.append(current_time)
378 ####
379 log_qry = f"LOG,ID,{logsList[0]},TIME,{logsList[1]}\nendfill"
380 f = files_s() # this is the files class
381 f.write_logs(log_qry) # this is the write logs function from the logs class
382 elif args == 2:
383 print("add record")
384 recList = [] # this list should deal with all the data
385 # strt = "record1,1000,time"
386 id_num = str(ident)
387 version = 1 # might remove
388 total_deaths = 134 # should have functionality
389 total_visitors = 8000 # should have functionality
390 cppList = []
391 dpp = []
392 parish = ["Kingston", "St.Andrew", "St.Catherine", "Clarendon", "Manchester", "St.Elizabeth", "Westmoreland",
393 "Hanover", "St.James", "Trelawny", "St.Ann", "St.Mary", "Portland", "St.Thomas"]
394 print("Enter the number of cases per parish: ")
395 for i in range(len(parish)):
396 d = int(input(f" {parish[i]} "))
397 dpp.append(d)
398 cppList.append(parish[i] + ":" + str(d))
399
400 total_cases = sum(dpp)
401 recList.append(id_num)
402 recList.append(version)
403 recList.append(current_time)
404 recList.append(total_cases)
405 recList.append(total_deaths)
406 recList.append(total_visitors)
407 # identity
408 ##RECORD#1000#1#TIME#8,000#124#12,000#
409 recordQry = f"RECORD#{recList[1]}#{recList[2]}#{recList[3]}#{recList[4]}#{recList[5]}#{recList[6]}"
410 # records quary which should come after the beginfill
411 f = files_s()
412 f.write_records(recordQry=recordQry, cppList=cppList)
413
414
415# this would be where the program runs
416# develop a login function to initiate this
417
418def usage(args, ident):
419 # usage function need multiple versions for different levels of access and
420 # usage args 1 would be for administrator level access i.e has all the options available
421 # usage args 2 would be semi=administrator level access i.e has 2 or at least 3 options available
422 # usage args 3 would be low privalaged user level access i.e has only the search user option etc
423 # this is version 1
424 if args == 1:
425
426 database_s()
427 print("=" * 20)
428 print("Select (1) to add user Select (2) to search for user (3) to delete user ///(4) to edit user")
429 selected = int(input(":"))
430 if selected == 1:
431 t = database_s()
432 t.add_user(args=1, ident=ident) # this will call the function if the user already exists
433 # logic to call add user function should be developed
434 # add user version 2 is admin level
435 elif selected == 2:
436 t = database_s()
437 t.search()
438 elif selected == 3:
439 t = database_s()
440 t.delete_user()
441 elif selected == 4:
442 t = database_s()
443 t.edit_user(args=1, ident=ident) # edit user needs ident for version 1
444
445 # add logic to save all instances or usages of the program
446 # this file should save id used to enter and return the date and time the user logged on,
447 # this wold increment by an id of all logs i.e (logs) = logs + 1 "after use"
448
449 # add else clause for exit functionality
450
451
452def show_user(list, args):
453 if args == 1:
454 # show user 1 would return all data of the user
455 # 0,1,2,3,4,5,6,7,8,9,10,11
456 """
457 0 id
458 1 firstname
459 2 lastname
460 3 date of birth
461 4 address
462 5 parish
463 6 gender
464 7 date of arrival
465 8 length of stay
466 9 precondition
467 10 covid status
468 11 date of last labtest
469 12 violator status
470 """
471 id_num = 0
472 firstname, lastname, date_of_birth, address, parish, gender, date_of_arrival, length_of_stay, precondition, covid_status, date_of_last_labtest, violator_status = ""
473
474 id_num = str(list[0])
475 firstname = str(list[1])
476 lastname = str(list[2])
477 date_of_birth = str(list[3])
478 address = str(list[4])
479 parish = str(list[5])
480 gender = str(list[6])
481 date_of_arrival = str(list[7])
482 length_of_stay = str(list[8])
483 precondition = str(list[9])
484 covid_status = str(list[10])
485 date_of_last_labtest = str(list[11])
486 violator_status = str(list[12])
487
488 print("=" * 10)
489 print(f"I.D: {id_num}")
490 print(f"Firstname: {firstname}")
491 print(f"Lastname: {lastname}")
492 print(f"Date of birth: {date_of_birth}")
493 print(f"Address: {address}")
494 print(f"Parish: {parish}")
495 print(f"Gender: {gender}")
496 print(f"Date of Arrival: {date_of_arrival}")
497 print(f"Length of stay: {length_of_stay}")
498 print(f"Precondition: {precondition}")
499 print(f"Covid status: {covid_status}")
500 print(f"Date of recent labtest: {date_of_last_labtest}")
501 print(f"Violator status: {violator_status}")
502 print("=" * 10)
503 # incomplete i.e to add further aspects of the user ex lastname,date of birth etc
504 elif args == 2:
505 # show user 2 would return the first name only as a single line variable
506 firstname = ""
507 firstname = str(list[1])
508 # print(f"Firstname: {firstname}")
509 # this could return the last name as well
510 return firstname
511 elif args == 3:
512 # show user 3 would only return the first name and id
513 id_num = 0
514 firstname = ""
515 id_num = str(list[0])
516 firstname = str(list[1])
517 print("=" * 10)
518 print(f"I.D: {id_num}")
519 print(f"Firstname: {firstname}")
520 print("=" * 10)
521 elif args == 4: ##incomplete
522 id_num = 0
523 firstname, lastname, precondition, violator_status, covid_status = ""
524 """
525 0 id
526 1 firstname
527 2 lastname
528 3 date of birth
529 4 address
530 5 parish
531 6 gender
532 7 date of arrival
533 8 length of stay
534 9 precondition
535 10 covid status
536 11 date of last labtest
537 12 violator status
538 """
539 id_num = str(list[0])
540 firstname = str(list[1])
541 lastname = str(list[2])
542 precondition = str(list[9])
543 violator_status = str(list[12])
544 covid_status = str(list[10])
545 ##########
546 print("=" * 10)
547 print(f"I.D: {id_num}")
548 print(f"Firstname: {firstname}")
549 print(f"Lastname: {lastname}")
550 print(f"Precondition: {precondition}")
551 print(f"Violator status:{violator_status}")
552 print(f"Covid status: {covid_status}")
553 print("=" * 10)
554
555
556def menu():
557 # this is the main menu of the program
558 database_s() # this initializes the database once the program starts
559 select = int(input("(1)T.R.N (2) V.E.N "))
560 # this code ensures the user selects 1 or 2 to get started
561 # if 3 is entered, the program exits #this is the case for testing
562 # add update to logs file as trn user true for example
563 try:
564 if select == 1:
565 dbcon = sqlite3.connect("CoIMaDS.db")
566 cursor = dbcon.cursor()
567 trn = input("Enter t.r.n number: ")
568 try:
569 cursor.execute("SELECT * FROM user WHERE id_num=?", (trn,))
570 results = cursor.fetchone() # returnes values from database quary
571
572 if results:
573 records_handling(args=1,
574 ident=trn) # facilitate ident as a list which tells if the user is a trn user
575 results_list = []
576 for i in range(len(results)): # this range is dependent on how much data is to be returned
577 results_list.append(results[i])
578
579 print(f"[+] Welcome back " + show_user(results_list, args=2)) # evaluate this line to return names
580 dbcon.commit()
581 usage(args=1, ident=trn)
582
583 else:
584 # print("[!] User not found")
585 cursor.execute("""INSERT INTO user ( id_num) VALUES (?)
586 """, (trn,)) # quary not complete to add values ?
587 dbcon.commit()
588 print("You will be asked to use this trn as an id to search,edit,and add user to the system")
589 usage(args=1, ident=trn)
590
591 except Exception as ex:
592 print(ex) # needs to be evaluated
593 # cursor.close()
594 if ex:
595 usage(args=1, ident=trn) # if the exception is a unique id error then continue
596 records_handling(args=1,
597 ident=trn) # facilitate ident as a list which tells if the user is a trn user
598 # continue the code
599 elif select == 2:
600 dbcon = sqlite3.connect("CoIMaDS.db")
601 cursor = dbcon.cursor()
602 ven = input("Enter v.e.n number: ")
603 try:
604 cursor.execute("SELECT * FROM user WHERE id_num=?", (ven,))
605 results = cursor.fetchone() # returnes values from database quary
606
607 if results:
608 records_handling(args=1,
609 ident=trn) # facilitate ident as a list which tells if the user is a trn user
610 results_list = []
611 for i in range(len(results)): # this range is dependent on how much data is to be returned
612 results_list.append(results[i])
613
614 print(f"[+] Welcome back " + show_user(results_list, args=2)) # evaluate this line to return names
615 dbcon.commit()
616 usage(args=1, ident=ven)
617
618 else:
619 # print("[!] User not found")
620 cursor.execute("""INSERT INTO user ( id_num) VALUES (?)
621 """, (ven,)) # quary not complete to add values ?
622 dbcon.commit()
623 print("You will be asked to use this trn as an id to search,edit,and add user to the system")
624 usage(args=1, ident=ven)
625
626 except Exception as ex:
627 print(ex) # needs to be evaluated
628 # cursor.close()
629 if ex:
630 usage(args=1, ident=ven) # if the exception is a unique id error then continue
631 records_handling(args=1,
632 ident=ven) # facilitate ident as a list which tells if the user is a trn user
633 # continue the code
634
635 except: # user entered exit
636 sys.exit(1) # exit function assuming user entered something else
637
638
639############80% complete
640menu() # lol