def add_entry(self): '''Add data to the database''' while True: ssn = retrieve_data.get_ssn() #input work_employee = retrieve_data.verify_employee(ssn) #input time.sleep(1) formatter.clear_screen() task_data = { 'task' : task_functions.store_category(), 'task_date' : task_functions.store_date(), 'time_duration' : task_functions.store_duration(), 'note' : task_functions.store_note(), 'employee' : work_employee } formatter.clear_screen() print("Task Stored...") work_task = Task.create(**task_data) print('Please select from the following:\n[ N ] - Add another entry\n[ B ] - Back to the previous menu') while True: prompt_new_entry = readchar.readkey().upper() # invokes program flow via keystroke if prompt_new_entry not in ['N', 'B']: print("Invalid option. Please enter [N]ew entry; [B]ack to the previous menu:") continue break if prompt_new_entry == 'N': continue else: return (all(isinstance(model[0], model[1]) for model in [(work_employee, Employee), (work_task,Task)]))
def main(filename, time_window, update_interval, alert_window, alert_threshold): if filename != "-": input_file = open(filename, "r") else: input_file = sys.stdin stats = HttpStats(time_window) alert_manager = AlertManager(alert_threshold) last_update = datetime(1, 1, 1) #TODO(Wesley) this is a hack #TODO(Wesley) Should handle SIGWINCH and reset this value. # Another option would be to get this value in the main loop. term_height = shutil.get_terminal_size((80, 20))[1] while True: line_str = input_file.readline() if line_str: logline = HttpLog.from_str(line_str) if logline: stats.add(logline) elif datetime.now() - last_update > timedelta(0, update_interval): alert_manager.update( stats.total_pageviews( datetime.now(tzlocal.get_localzone()) - timedelta(0, alert_window)), datetime.now()) formatter.clear_screen() stats_str = str(str(stats)) print("") print(stats_str) lines_left = term_height - stats_str.count("\n") - 1 print(alert_manager.to_str(lines_left), end="") sys.stdout.flush() last_update = datetime.now()
def store_date(): formatter.clear_screen() date = input( "\nProvide the date for which the task was completed - [yyyy-mm-dd]:\n>>> " ) return formatter.date(date)
def search_dates(self): """Find database entries by date""" formatter.clear_screen() provided_date = formatter.date(input("Provide a base date to begin searching entries\n>>>")) while True: try: day_range = int(input(f"Establish how many days to look before and after {provided_date}:\n>>>")) except (ValueError, TypeError): formatter.clear_screen() print("Could not compute the search...only provide a number for the range.") else: if not day_range: print('A minimum of 1 day must be provided to initiate a date search...') continue break try: search_start = provided_date - datetime.timedelta(days=day_range) except OverflowError: this_year = provided_date.year search_start = datetime.date(year=this_year, month=1, day=1) else: try: search_end = provided_date + datetime.timedelta(days=day_range) except OverflowError: this_year = provided_date.year search_end = datetime.date(year=this_year, month=12, day=31) collect_date_range = Task.select().join(Employee).where(Task.task_date >= search_start, Task.task_date <= search_end).order_by(Task.task_date) return collect_date_range
def store_category(): formatter.clear_screen() while True: category = input("\nSpecify what type of task was conducted:\n>>> " ).strip().upper() if not category: print("Category not entered...") continue return category
def store_note(): formatter.clear_screen() while True: note = input("\nProvide details as to what was completed:\n>>> " ).strip().upper() if not note: print("Note not entered...") continue return note
def delete_entry(self): '''Remove an employee from the database''' record_ssn = retrieve_data.get_ssn() formatter.clear_screen() previous_tasks = Task.select().join(Employee).where(Employee.ssn == record_ssn['ssn']).dicts(as_dict=True) if not previous_tasks: print(f"No entrys are stored under SSN {record_ssn['ssn']}.") time.sleep(2) return False task_ids = [] while True: formatter.clear_screen() header = f"Employe SSN: {record_ssn['ssn']}\n" print(header + '*' * 20) task_choices = '' for t in previous_tasks: task_ids.append(t['id']) task_choices += '\nTask ID: {id}\nTask: {task}\nDate: {task_date}\nNote: {note}\n'.format(**t) task_choices += '\n' print(task_choices) print('*' * 20) print("\nChoose an entry to delete... (or 'Q' to exit)") while True: task_num = readchar.readkey().upper() if task_num == 'Q': print('Deletion Occured: None') time.sleep(2) return else: try: task_num = int(task_num) except ValueError: print("Cannot delete entry. Enter a valid ID") time.sleep(1.5) break else: if task_num not in task_ids: print(f"No match exists under that SSN: Task ID# {task_num}") time.sleep(1.5) break del_task = Task.get_by_id(task_num) print(f'Deleted Task ID# {task_num}') time.sleep(1.5) return del_task.delete_instance()
def search_notes(self): """Find database entries by string matches""" formatter.clear_screen() while True: phrase = input("Search tasks by a given phrase:\n>>>").title().strip() if not phrase: formatter.clear_screen() print("Empty strings cannot be used to search tasks...") continue break tasks_by_phrase = Task.select().where((Task.task.contains(phrase)) | (Task.note.contains(phrase))).order_by(Task.task_date).order_by(Task.task_date) return tasks_by_phrase
def store_duration(): formatter.clear_screen() while True: try: time_duration = abs( int(input("\nProvide time spent on task (in minutes):\n>>> "))) except ValueError: print("Invalid time value...") continue if not time_duration: print("No time entered...") continue stored_time = formatter.timeclock(time_duration) return stored_time
def render_main_menu(self, options): show_menu = ''.join(['[ {key} ] - {option}\n'.format(key=key, option=value.__doc__) # string of `menu_options` for key, value in options.items()]) menu_ids = options.keys() while True: formatter.clear_screen() print(show_menu + "\nSelect from one of the above options") option = readchar.readkey().upper() while option not in menu_ids and option: print(f'Cannot perform selection -> ID entered: [{option}]') option = readchar.readkey().upper() action_taken = options[option]() if action_taken or not action_taken: continue
def search_minutes(self): """Find database entries by time spent""" formatter.clear_screen() while True: try: search_time = abs(int(input("Search tasks by the number of minutes it took to finish:\n>>>"))) except (TypeError, ValueError): formatter.clear_screen() print("Tasks searched by time are only searched by minutes...") else: if not search_time: print("No time was entered to search by...") continue else: search_time = formatter.timeclock(search_time) tasks_by_mins = Task.select().where(Task.time_duration == search_time).order_by(Task.task_date) return tasks_by_mins
def get_employee_data(): formatter.clear_screen() string_matches = re.compile(r'\b\w+') print("Provide the following: first name, last name:") while True: employee_query = input("Employee's name:\n>>> ").title().strip() query_result = re.findall(string_matches, employee_query) # '.' is not included with a name suffix for the purpose of line 192 passing; refer to line 184 if any(not re_string.isalpha() for re_string in query_result) or len(query_result) < 2: formatter.clear_screen() print("Invalid name provided...First and last names required") continue break db_name = formatter.filter_name(employee_query) first_name, last_name = db_name.split() return dict(zip(['first_name', 'last_name'], [first_name, last_name]))
def search_entries(self): '''Search database''' search_options = { '1' : self.search_employee, '2' : self.search_dates, '3' : self.search_minutes, '4' : self.search_notes } while True: formatter.clear_screen() print("Specify how you want to search the database") search_menu_str = ''.join(f'{key} - {value.__doc__}\n' for key, value in search_options.items()) print(search_menu_str) search_input = readchar.readkey() if search_input not in search_options: print("That functionality does not exist. Please select only from the options listed above.") time.sleep(1) continue search_results = search_options[search_input]() if search_results: formatter.display_tasks(search_results) else: formatter.clear_screen() print("No results can be generated.") print("\nWould you like to perform another search...\n[N]ew search\n[M]ain Menu") while True: search = readchar.readkey().upper() if search not in ['N', 'M']: print('Command unknown...please press [N] or [M]') continue break if search == 'N': continue return
def search_employee(self): """Find database entries by employee""" formatter.clear_screen() task_dict = {} stored_employees = Employee.select() employee_menu = '' formatter.clear_screen() for emp in stored_employees: employee_menu_id = f'{emp.id}-{emp.ssn[-4:]}' employee_menu += employee_menu_id + f') {str(emp)}\n' task_dict.setdefault(employee_menu_id, []) task_dict[employee_menu_id].append(emp) while True: formatter.clear_screen() print("Employees in Database:\n" +employee_menu) while True: select_emp = input('Enter an employee id followed by the last four of their SSN# [X-XXXX]:\n>>> ').strip() if select_emp not in task_dict: print("An invalid reference was entered...") time.sleep(1.5) break else: id_pattern = re.compile(r'\d+') real_id = int(id_pattern.match(select_emp).group()) all_emp_tasks = Task.select().where(Task.employee == real_id).order_by(Task.task_date) return all_emp_tasks
def get_ssn(): formatter.clear_screen() ssn_number = input(f'\nEnter social security number:\n>>> '.strip()) ssn = formatter.verify_ssn(ssn_number) return dict(zip(['ssn'], [ssn]))