From 51709da8fcd62c77d51651480f7ca0aac57694c7 Mon Sep 17 00:00:00 2001 From: anima Date: Mon, 7 Jun 2021 20:03:31 +0200 Subject: [PATCH] build database function to get active events and time entries --- timeTrack.py | 225 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 148 insertions(+), 77 deletions(-) diff --git a/timeTrack.py b/timeTrack.py index b362b10..aa9c637 100644 --- a/timeTrack.py +++ b/timeTrack.py @@ -46,6 +46,38 @@ class TimeTrack: else: logging.debug('Winwos System detected') _ = os.system('cls') + + ### Loads or creates a config file + def load_config(self): + if os.path.isfile(self.CONFIG): + logging.info('Config file was found') + try: + with open(self.CONFIG) as config_data: + data = json.load(config_data) + except ValueError: + logging.error('Config file has no valid JSON syntax') + print('TimeTrack wird beendet: Fehler in der JSON-Konfig ({})'.format(self.CONFIG)) + quit() + else: + logging.info('Config file was loaded successfully') + self.USERID = data['user'] + self.OLDEVENT = data['oldevent'] + logging.debug('UserID {} was used'.format(data['user'])) + self.set_user() + + else: + logging.warning('Config file not found') + config = { + 'default' : 'interactive', + 'user' : 1, + 'oldevent' : 2 + } + with open(self.CONFIG, "w") as outfile: + json.dump(config, outfile, indent=4, sort_keys=True) + logging.info('Config file created successfully') + + #> wenn man keine datei erstellen darf/kann, fällt das skript in einen loop ? + self.load_config() ### Creates a database if none is found def db_setup(self): @@ -62,7 +94,8 @@ class TimeTrack: endtime TIMESTAMP NOT NULL, user_id INTEGER NOT NULL, activity TEXT, - catrgory_id INTEGER, + reference TEXT, + category_id INTEGER, client_id INTEGER, lock BOOLEAN ) @@ -113,37 +146,111 @@ class TimeTrack: else: logging.debug('Table was created successfully or already exists') - ### Loads or creates a config file - def load_config(self): - if os.path.isfile(self.CONFIG): - logging.info('Config file was found') - try: - with open(self.CONFIG) as config_data: - data = json.load(config_data) - except ValueError: - logging.error('Config file has no valid JSON syntax') - print('TimeTrack wird beendet: Fehler in der JSON-Konfig ({})'.format(self.CONFIG)) - quit() - else: - logging.info('Config file was loaded successfully') - self.USERID = data['user'] - self.OLDEVENT = data['oldevent'] - logging.debug('UserID {} was used'.format(data['user'])) - self.set_user() - + ### Get an active event based on a user or event ID + def get_active_event(self, USERID='', EVENTID=''): + if USERID: + logging.debug('Search events based on userid: {}'.format(USERID)) + sql = "SELECT * FROM active_events WHERE user_id = ?" + searchdata = [USERID] + elif EVENTID: + logging.debug('Search event based on eventid: {}'.format(EVENTID)) + sql = "SELECT * FROM active_events WHERE id = ?" + searchdata = [EVENTID] else: - logging.warning('Config file not found') - config = { - 'default' : 'interactive', - 'user' : 1, - 'oldevent' : 2 - } - with open(self.CONFIG, "w") as outfile: - json.dump(config, outfile, indent=4, sort_keys=True) - logging.info('Config file created successfully') + sql = "SELECT * FROM active_events" + searchdata = False + + try: + with sqlite3.connect(self.DATABASE, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) as con: + cur = con.cursor() + if searchdata: + logging.debug('Search event') + cur.execute(sql, searchdata) + else: + logging.debug('Get all Events') + cur.execute(sql) + eventdata = cur.fetchall() + except sqlite3.Error as err: + logging.debug(sql) + logging.error('SQLError: {}'.format(err)) + print('Fehler beim auslesen der aktiven Events') + else: + logging.debug('Events could be read out successfully') + + con.close() + if eventdata == []: + logging.debug('No active events found') + return 0 + else: + logging.debug('{} events found'.format(len(eventdata))) + return eventdata[0] - #> wenn man keine datei erstellen darf/kann, fällt das skript in einen loop ? - self.load_config() + ### Get time entries based on various criteria + def get_time_entry(self, USERID='', TIMEID='', CATEGORYID='', CLIENTID='', REFERENCE='', STARTTIME='', ENDTIME=''): + if USERID: + logging.debug('Search time entries based on userid: {}'.format(USERID)) + sql = "SELECT * FROM time_entries WHERE user_id = ?" + searchdata = [USERID] + elif TIMEID: + logging.debug('Search time entrys based on timeid: {}'.format(TIMEID)) + sql = "SELECT * FROM time_entries WHERE id = ?" + searchdata = [TIMEID] + elif CATEGORYID: + logging.debug('Search time entrys based on categoryid: {}'.format(CATEGORYID)) + sql = "SELECT * FROM time_entries WHERE category_id = ?" + searchdata = [CATEGORYID] + elif CLIENTID: + logging.debug('Search time entrys based on clientid: {}'.format(CLIENTID)) + sql = "SELECT * FROM time_entries WHERE client_id = ?" + searchdata = [CLIENTID] + elif REFERENCE: + logging.debug('Search time entrys based on reference: {}'.format(REFERENCE)) + sql = "SELECT * FROM time_entries WHERE reference = ?" + searchdata = [REFERENCE] + else: + sql = "SELECT * FROM time_entries" + searchdata = False + + try: + with sqlite3.connect(self.DATABASE, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) as con: + cur = con.cursor() + if searchdata: + logging.debug('Search time entry') + cur.execute(sql, searchdata) + else: + logging.debug('Get all time entries') + cur.execute(sql) + timedata = cur.fetchall() + except sqlite3.Error as err: + logging.debug(sql) + logging.error('SQLError: {}'.format(err)) + print('Fehler beim auslesen der Zeiteinträge') + else: + logging.debug('Time entries could be read out successfully') + + con.close() + + tmp = [] + if STARTTIME: + for entry in timedata: + if entry[1] > STARTTIME: + tmp.append(entry) + timedata = tmp[:] + pass + tmp = [] + if ENDTIME: + for entry in timedata: + if entry[2] < ENDTIME: + tmp.append(entry) + timedata = tmp[:] + + if timedata == []: + logging.debug('No time entries found') + return 0 + else: + logging.debug('{} time entries found'.format(len(timedata))) + return timedata + pass ## user handling ### Creates a user who does not yet exist @@ -223,7 +330,7 @@ class TimeTrack: ## Time handling ### Creates an active event if none exists for the user def save_event(self, TIME=datetime.datetime.now()): - if not self.get_event(USERID=self.USERID): + if not self.get_active_event(USERID=self.USERID): logging.debug('No active events found for the user: {}'.format(self.USERID)) sql = "INSERT INTO active_events ( starttime, user_id ) VALUES ( ?, ? )" @@ -271,45 +378,7 @@ class TimeTrack: else: logging.debug('Event was successfully deleted') - ### Get an active event based on a user or event ID - def get_event(self, ENTRYID='', USERID=''): - if not ENTRYID == '': - logging.debug('Search event based on eventid: {}'.format(ENTRYID)) - sql = "SELECT * FROM active_events WHERE id = ?" - data = ENTRYID - elif not USERID == '': - logging.debug('Search events based on userid: {}'.format(USERID)) - sql = "SELECT * FROM active_events WHERE user_id = ?" - data = USERID - else: - sql = "SELECT * FROM active_events" - data = '' - - try: - with self.DBCON as con: - cur = con.cursor() - if data: - logging.debug('Search event') - cur.execute(sql, [data]) - else: - logging.debug('Get all Events') - cur.execute(sql) - data = cur.fetchall() - except sqlite3.Error as err: - logging.error('Events could not be read') - logging.debug(sql) - logging.error('SQLError: {}'.format(err)) - print('Fehler beim auslesen der aktiven Events') - else: - logging.debug('Events could be read out successfully') - - if data == []: - logging.debug('No active events found') - return 0 - else: - logging.debug('{} events found'.format(len(data))) - return data[0] - + # Checks for existing time entries and creates a new one if none is available. def time_start(self, AUTOFORWARD=True): self.clear_screen() starttime = datetime.datetime.now() @@ -319,7 +388,7 @@ class TimeTrack: if AUTOFORWARD: self.time_stop() else: - data = self.get_event(USERID=self.USERID) + data = self.get_active_event(USERID=self.USERID) print('Es existiert bereits ein aktives Event.') if (data[1] + datetime.timedelta(hours=self.OLDEVENT)) <= datetime.datetime.now(): logging.info('Event exceeds allowed duration') @@ -368,8 +437,9 @@ class TimeTrack: print('Event von {} Uhr geladen'.format(data[1].strftime("%H:%M"))) self.time_stop() + # Stops existing time entries def time_stop(self): - data = self.get_event(USERID=self.USERID) + data = self.get_active_event(USERID=self.USERID) logging.debug('Event stop progess is started') if data: self.clear_screen() @@ -454,9 +524,7 @@ class TimeTrack: logging.debug('Terminated by the user') exit() - def get_time(self): - pass - + # Shows a time entry def print_time_entry(self, STARTTIME='', ENDTIME='', ACTIVITY=''): self.clear_screen() s = (ENDTIME - STARTTIME).seconds @@ -474,5 +542,8 @@ class TimeTrack: if __name__ == "__main__": test = TimeTrack() - test.time_start() - test.DBCON.close() \ No newline at end of file + #test.time_start() + #test.DBCON.close() + start = datetime.datetime(2021,6,4,18) + end = datetime.datetime(2021,6,5,11,30) + print(test.get_time_entry(STARTTIME=start, ENDTIME=end)) \ No newline at end of file