18 Commits

Author SHA1 Message Date
aa2c08838e fix version number in dev branch 2021-06-29 06:23:43 +02:00
d06ab9d6f0 add function report_by_date for specific date to interactive menu 2021-06-29 05:34:39 +02:00
f553f75462 add delete_user and add to usermanagment 2021-06-15 18:26:34 +02:00
106d93074d add set user part in usermanagement 2021-06-15 17:52:34 +02:00
e49d0c3ab5 replace old db connections 2021-06-15 17:27:47 +02:00
c9ac507ab5 config file extended by categories, clients, references 2021-06-15 17:27:07 +02:00
33dd249601 optimizied text fomating at report_by_day 2021-06-12 20:07:54 +02:00
53d0f8d83f create inital interactive usermanagment 2021-06-10 21:48:59 +02:00
57bbfc77dc preparation database for breaketime 2021-06-10 21:29:21 +02:00
7fbad1ee4a change all userinputs to new function 2021-06-09 23:10:22 +02:00
c081f519dd add function userchoise and print time entries by daly report 2021-06-08 23:48:44 +02:00
0765f45704 add interactive mode & daly report 2021-06-08 00:36:38 +02:00
51709da8fc build database function to get active events and time entries 2021-06-07 20:03:31 +02:00
58d0e6191c optimized screen clear 2021-06-06 14:21:57 +02:00
3d9d1a1d5f db handling optimized 2021-06-05 11:39:28 +02:00
a5cde65967 fix sheebang (Issue#2) 2021-06-04 18:38:40 +02:00
6834469b62 Menu navigation optimized (Issue#1) 2021-06-04 18:07:25 +02:00
28bc3b319e set to v.2.0.0 aplha 2021-06-04 11:22:58 +02:00

View File

@@ -1,9 +1,9 @@
#!/bin/python3 #!/usr/bin/env python3
######################### #########################
# #
# timeTrack.py # timeTrack.py
# by 4nima # by 4nima
# v.0.5.0 # v.2.2.0a
# #
######################### #########################
# simple time tracking with database # simple time tracking with database
@@ -23,6 +23,9 @@ class TimeTrack:
self.USERID = 0 self.USERID = 0
self.USERNAME = '' self.USERNAME = ''
self.OLDEVENT = 2 self.OLDEVENT = 2
self.CLIENTS = False
self.CATEGORIES = False
self.REFERENCES = False
self.LOGFILE = 'timetrack.log' self.LOGFILE = 'timetrack.log'
logging.basicConfig( logging.basicConfig(
filename=self.LOGFILE, filename=self.LOGFILE,
@@ -30,18 +33,61 @@ class TimeTrack:
format='%(asctime)s - %(process)d-%(levelname)s: %(message)s', format='%(asctime)s - %(process)d-%(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S' datefmt='%Y-%m-%d %H:%M:%S'
) )
if os.name == 'posix':
logging.debug('Unix/Linux system detected')
self.LINUX = True
else:
logging.debug('Winwos System detected')
self.db_setup() self.db_setup()
self.load_config() self.load_config()
## Prepartation ## Prepartation
#==============
### Check OS and clear screen ### Check OS and clear screen
def clear_screen(self): def clear_screen(self):
if os.name == 'posix': if self.LINUX:
logging.debug('Unix/Linux system detected')
_ = os.system('clear') _ = os.system('clear')
else: else:
logging.debug('Winwos System detected')
_ = os.system('cls') _ = 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['userid']
self.OLDEVENT = data['oldevent']
self.CLIENTS = data['clients']
self.CATEGORIES = data['categories']
self.REFERENCES = data['references']
logging.debug('UserID {} was used'.format(data['userid']))
self.set_user()
else:
logging.warning('Config file not found')
config = {
'default' : 'interactive',
'userid' : 1,
'oldevent' : 2,
'clients' : False,
'categories' : False,
'references' : False
}
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 ### Creates a database if none is found
def db_setup(self): def db_setup(self):
@@ -56,9 +102,11 @@ class TimeTrack:
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
starttime TIMESTAMP NOT NULL, starttime TIMESTAMP NOT NULL,
endtime TIMESTAMP NOT NULL, endtime TIMESTAMP NOT NULL,
breaktime1 TIMESTAMP,
user_id INTEGER NOT NULL, user_id INTEGER NOT NULL,
activity TEXT, activity TEXT,
catrgory_id INTEGER, reference TEXT,
category_id INTEGER,
client_id INTEGER, client_id INTEGER,
lock BOOLEAN lock BOOLEAN
) )
@@ -68,6 +116,7 @@ class TimeTrack:
CREATE TABLE IF NOT EXISTS active_events ( CREATE TABLE IF NOT EXISTS active_events (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
starttime TIMESTAMP NOT NULL, starttime TIMESTAMP NOT NULL,
breaktime TIMESTAMP,
user_id INT NOT NULL user_id INT NOT NULL
) )
""") """)
@@ -95,56 +144,136 @@ class TimeTrack:
) )
""") """)
connect = sqlite3.connect(self.DATABASE)
cursor = connect.cursor()
logging.debug('Create initial database tables') logging.debug('Create initial database tables')
for SQL in sql: try:
try: with sqlite3.connect(self.DATABASE, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) as con:
cursor.execute(SQL) for SQL in sql:
except: con.execute(SQL)
logging.error('Table could not be created') except sqlite3.Error as err:
logging.debug(SQL) logging.error('Table could not be created')
print('TimeTrack wird beendet: Fehler bei Datanbank Setup') logging.debug(sql)
quit() logging.error('SQLError: {}'.format(err))
else: print('TimeTrack wird beendet: Fehler bei Datanbank Setup')
logging.debug('Table was created successfully or already exists') quit()
connect.commit()
connect.close()
### 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: else:
logging.warning('Config file not found') logging.debug('Table was created successfully or already exists')
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 ? ### Get an active event based on a user or event ID
self.load_config() 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:
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]
### Get time entries based on various criteria
def get_time_entry(self, USERID='', TIMEID='', CATEGORYID='', CLIENTID='', REFERENCE='', STARTTIME='', ENDTIME='', DAY=''):
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()
if DAY:
logging.debug('Search time entries by date: {}'.format(DAY))
tmp = []
for entry in timedata:
if entry[1].date() == DAY:
tmp.append(entry)
timedata = tmp[:]
else:
tmp = []
if STARTTIME:
logging.debug('Search time entries by starttime: {}'.format(STARTTIME))
for entry in timedata:
if entry[1] > STARTTIME:
tmp.append(entry)
timedata = tmp[:]
pass
tmp = []
if ENDTIME:
logging.debug('Search time entrie by endtime: {}'.format(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
## user handling ## user handling
#===============
### Creates a user who does not yet exist ### Creates a user who does not yet exist
def create_user(self, USER=''): def create_user(self, USER=''):
if USER == '': if USER == '':
@@ -160,21 +289,17 @@ class TimeTrack:
logging.debug('Accepted username: {}'.format(username)) logging.debug('Accepted username: {}'.format(username))
connect = sqlite3.connect(self.DATABASE)
cursor = connect.cursor()
sql = "INSERT INTO users ( name ) values ( ? )" sql = "INSERT INTO users ( name ) values ( ? )"
try: try:
cursor.execute(sql, [username]) with sqlite3.connect(self.DATABASE, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) as con:
except: con.execute(sql, [username])
except sqlite3.Error as err:
logging.error('User could not be saved in database') logging.error('User could not be saved in database')
logging.debug(sql) logging.debug(sql)
logging.error('SQLError: {}'.format(err))
else: else:
logging.info('User was saved successfully') logging.info('User was saved successfully')
connect.commit()
connect.close()
### Outputs existing users from the DB ### Outputs existing users from the DB
def get_users(self, UID=0, NAME=''): def get_users(self, UID=0, NAME=''):
@@ -191,25 +316,23 @@ class TimeTrack:
data = '' data = ''
sql = "SELECT * FROM users" sql = "SELECT * FROM users"
connect = sqlite3.connect(self.DATABASE)
cursor = connect.cursor()
try: try:
if data: with sqlite3.connect(self.DATABASE, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) as con:
cursor.execute(sql, [data]) cur = con.cursor()
else: if data:
cursor.execute(sql) cur.execute(sql, [data])
except: else:
cur.execute(sql)
data = cur.fetchall()
except sqlite3.Error as err:
logging.error('Could not get user') logging.error('Could not get user')
logging.debug(sql) logging.debug(sql)
logging.error('SQLError: {}'.format(err))
print('Fehler beim Zugriff auf die Benutzer Datenbank') print('Fehler beim Zugriff auf die Benutzer Datenbank')
return 1 return 1
else: else:
logging.debug('User database read out successfully') logging.debug('User database read out successfully')
connect.commit()
data = cursor.fetchall()
connect.close()
return data return data
### Defines a user for the session ### Defines a user for the session
@@ -226,28 +349,45 @@ class TimeTrack:
else: else:
self.USERNAME = data[0][1] self.USERNAME = data[0][1]
## Time handling def delete_user(self, UID=False):
### Creates an active event if none exists for the user if not UID:
def save_event(self, TIME=datetime.datetime.now()): logging.error('no userid passed for deletion')
if not self.get_event(USERID=self.USERID): else:
logging.debug('No active events found for the user: {}'.format(self.USERID)) logging.debug('Userid {} will be delete'.format(UID))
connect = sqlite3.connect(self.DATABASE) sql = "DELETE FROM users WHERE id = ?"
cursor = connect.cursor()
sql = "INSERT INTO active_events ( starttime, user_id ) VALUES ( ?, ? )"
try: try:
cursor.execute(sql, [TIME, self.USERID]) with sqlite3.connect(self.DATABASE, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) as con:
except: con.execute(sql, [UID])
except sqlite3.Error as err:
logging.error('User could not be delete from database')
logging.debug(sql)
logging.error('SQLError: {}'.format(err))
else:
logging.info('User was delete successfully')
## Time handling
#===============
### Creates an active event if none exists for the user
def save_event(self, TIME=datetime.datetime.now()):
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 ( ?, ? )"
try:
with sqlite3.connect(self.DATABASE, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) as con:
con.execute(sql, [TIME, self.USERID])
except sqlite3.Error as err:
logging.error('Event could not be created') logging.error('Event could not be created')
logging.debug(sql) logging.debug(sql)
logging.error('SQLError: {}'.format(err))
print('Event konnte nicht gespeichert werden.') print('Event konnte nicht gespeichert werden.')
return False return False
else: else:
logging.info('Event was created successfully') logging.info('Event was created successfully')
connect.commit()
connect.close()
return True return True
else: else:
logging.warning('Active events found for the user, new event could not be created') logging.warning('Active events found for the user, new event could not be created')
return False return False
@@ -267,59 +407,18 @@ class TimeTrack:
print('Keine angabe was gelöscht werden soll') print('Keine angabe was gelöscht werden soll')
return 0 return 0
connect = sqlite3.connect(self.DATABASE, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
cursor = connect.cursor()
try: try:
cursor.execute(sql, [data]) with sqlite3.connect(self.DATABASE, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) as con:
except: con.execute(sql, [data])
except sqlite3.Error as err:
logging.error('Event could not be deleted') logging.error('Event could not be deleted')
logging.debug(sql) logging.debug(sql)
logging.error('SQLError: {}'.format(err))
print('Fehler beim löschen des Events.') print('Fehler beim löschen des Events.')
else: else:
logging.debug('Event was successfully deleted') logging.debug('Event was successfully deleted')
connect.commit()
connect.close()
### 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 = ''
connect = sqlite3.connect(self.DATABASE, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
cursor = connect.cursor()
try:
if data:
logging.debug('Search event')
cursor.execute(sql, [data])
else:
logging.debug('Get all Events')
cursor.execute(sql)
except:
logging.error('Events could not be read')
logging.debug(sql)
print('Fehler beim auslesen der aktiven Events')
else:
logging.debug('Events could be read out successfully')
data = cursor.fetchall()
connect.close()
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): def time_start(self, AUTOFORWARD=True):
self.clear_screen() self.clear_screen()
starttime = datetime.datetime.now() starttime = datetime.datetime.now()
@@ -329,7 +428,7 @@ class TimeTrack:
if AUTOFORWARD: if AUTOFORWARD:
self.time_stop() self.time_stop()
else: else:
data = self.get_event(USERID=self.USERID) data = self.get_active_event(USERID=self.USERID)
print('Es existiert bereits ein aktives Event.') print('Es existiert bereits ein aktives Event.')
if (data[1] + datetime.timedelta(hours=self.OLDEVENT)) <= datetime.datetime.now(): if (data[1] + datetime.timedelta(hours=self.OLDEVENT)) <= datetime.datetime.now():
logging.info('Event exceeds allowed duration') logging.info('Event exceeds allowed duration')
@@ -347,57 +446,45 @@ class TimeTrack:
else: else:
logging.debug('Event younger than 1 day') logging.debug('Event younger than 1 day')
print('Vergangene Zeit: >{} Stunden'.format(int(elapsed.seconds/3600))) print('Vergangene Zeit: >{} Stunden'.format(int(elapsed.seconds/3600)))
printtext = [
'Wie soll mit dem Event verfahren werden?',
'[1] fortsetzen',
'[2] löschen',
'[0] abbrechen'
]
userinput = self.userchoise(printtext, 3)
self.clear_screen()
userinput = '' if userinput == 1:
while True:
if userinput == "F" or userinput == "f" or userinput == "1" \
or userinput == "L" or userinput == "l" or userinput == "2" \
or userinput == "A" or userinput == "a" or userinput == "3":
break
print('Soll das Event fortgesetzt oder gelöscht werden?')
print('[1/F/f] für fortsetzen')
print('[2/L/l] für löschen')
print('[3/A/a] für abbrechen')
userinput = input('Aktion: ')
logging.debug('User input: {}'.format(userinput))
self.clear_screen()
if userinput == "F" or userinput == "f" or userinput == "1":
logging.debug('Event should be continued') logging.debug('Event should be continued')
self.time_stop() self.time_stop()
elif userinput == "L" or userinput == "l" or userinput == "2": elif userinput == 2:
logging.info('Event should be deleted (eventid: {})'.format(data[0])) logging.info('Event should be deleted (eventid: {})'.format(data[0]))
self.delete_event(data[0]) self.delete_event(data[0])
self.time_start() self.time_start()
else:
logging.debug('Terminated by the user')
exit()
else: else:
logging.debug('Event continues (eventid{})'.format(data[0])) logging.debug('Event continues (eventid{})'.format(data[0]))
print('Event von {} Uhr geladen'.format(data[1].strftime("%H:%M"))) print('Event von {} Uhr geladen'.format(data[1].strftime("%H:%M")))
self.time_stop() self.time_stop()
### Stops existing time entries
def time_stop(self): 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') logging.debug('Event stop progess is started')
if data: if data:
self.clear_screen() self.clear_screen()
userinput = '' printtext = [
while True: 'Event von {} Uhr beenden?'.format(data[1].strftime("%H:%M")),
if userinput == "B" or userinput == "b" or userinput == "1" \ '[1] für beenden',
or userinput == "L" or userinput == "l" or userinput == "2" \ '[2] für löschen',
or userinput == "A" or userinput == "a" or userinput == "3": '[0] für abbrechen'
break ]
print('Event von {} Uhr beenden?'.format(data[1].strftime("%H:%M"))) userinput = self.userchoise(printtext, 3)
print('[1/B/b] für beenden') self.clear_screen()
print('[2/L/l] für löschen')
print('[3/A/a] für abbrechen')
userinput = input('Aktion: ')
logging.debug('User input: {}'.format(userinput))
self.clear_screen()
if userinput == "B" or userinput == "b" or userinput == "1": if userinput == 1:
logging.debug('Event is ended') logging.debug('Event is ended')
print('Eingabe beenden mittels doppelter Leerzeile.') print('Eingabe beenden mittels doppelter Leerzeile.')
print('Durchgeführte Tätigkeiten:') print('Durchgeführte Tätigkeiten:')
@@ -421,53 +508,189 @@ class TimeTrack:
endtime = datetime.datetime.now() endtime = datetime.datetime.now()
logging.debug('Event end process start at {}'.format(endtime)) logging.debug('Event end process start at {}'.format(endtime))
connect = sqlite3.connect(self.DATABASE)
cursor = connect.cursor()
sql = "INSERT INTO time_entries ( starttime, endtime, user_id, activity ) VALUES ( ?, ?, ?, ? )"
sql = "INSERT INTO time_entries ( starttime, endtime, user_id, activity ) VALUES ( ?, ?, ?, ? )"
try: try:
cursor.execute(sql, [data[1], endtime, self.USERID, action]) with sqlite3.connect(self.DATABASE, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) as con:
except: con.execute(sql, [data[1], endtime, self.USERID, action])
except sqlite3.Error as err:
logging.error('Time entry could not be created') logging.error('Time entry could not be created')
logging.debug(sql) logging.debug(sql)
logging.error('SQLError: {}'.format(err))
print('Zeiteintrag konnte nicht gespeichert werden.') print('Zeiteintrag konnte nicht gespeichert werden.')
return False return False
else: else:
logging.info('Time entry was created successfully') logging.info('Time entry was created successfully')
connect.commit()
self.delete_event(data[0])
self.print_time_entry(STARTTIME=data[1], ENDTIME=endtime, ACTIVITY=action)
print('Zeiteintrag wurde gespeichert.')
while True:
if userinput == "J" or userinput == "j" or userinput == "1" \
or userinput == "N" or userinput == "n" or userinput == "2":
break
print('Nächsten Zeiteintrag begrinnen ?')
print('[1/J/j] Ja')
print('[2/N/n] Nein')
userinput = input('Aktion: ')
logging.debug('User input: {}'.format(userinput))
self.clear_screen()
if userinput == "J" or userinput == "j" or userinput == "1":
self.time_start()
else:
logging.debug('Terminated by the user')
exit()
connect.close() self.delete_event(data[0])
self.clear_screen()
self.print_time_entry(STARTTIME=data[1], ENDTIME=endtime, ACTIVITY=action)
print('Zeiteintrag wurde gespeichert.')
printtext = [
'Nächsten Zeiteintrag beginnen ?',
'[1] Ja',
'[0] Nein'
]
userinput = self.userchoise(printtext)
self.clear_screen()
elif userinput == "L" or userinput == "l" or userinput == "2": if userinput == 1:
self.time_start()
elif userinput == 2:
logging.info('Event should be deleted (eventid: {})'.format(data[0])) logging.info('Event should be deleted (eventid: {})'.format(data[0]))
self.delete_event(data[0]) self.delete_event(data[0])
else:
logging.debug('Terminated by the user')
exit()
def get_time(self): ## Interactive mode
pass #==================
### Main menu of the interactive menu
def start_interactive_mode(self):
self.clear_screen()
printtext = [
'=> Hauptmenü - Angemeldet als {}'.format(self.USERNAME),
'Was willst du tun?',
'[1] Zeiterfassung starten',
'[2] heutiger Report',
'[3] Reports',
'[4] Benutzerverwaltung',
'[0] Programm verlassen'
]
userinput = self.userchoise(printtext, 4)
if userinput == 1:
logging.debug('Start TimeTrack')
self.time_start()
elif userinput == 2:
logging.info('Print todays report')
self.report_by_day(DETAIL=True)
input()
elif userinput == 3:
self.interactive_reports()
elif userinput == 4:
self.interactive_usermanagment()
else:
exit()
self.start_interactive_mode()
### Reports menu
def interactive_reports(self):
self.clear_screen()
printtext = [
'==> Reports für {}'.format(self.USERNAME),
'Welcher Report soll angezeigt werden?',
'[1] Tages Report von [Datum]',
'[0] abbrechen'
]
userinput = self.userchoise(printtext, 2)
if userinput == 1:
valid = False
while not valid:
self.clear_screen()
print('Report für welches Datum soll angezeigt werden?')
print('[0] für abbruch')
userdate = input("Datum: [yyyy-mm-dd]:")
if userdate == 0:
break
else:
try:
date = datetime.datetime.strptime(userdate, "%Y-%m-%d")
valid = True
except:
pass
self.report_by_day(date.date())
### Usermanagment menu
def interactive_usermanagment(self):
self.clear_screen()
printtext = [
'==> Benutzerverwaltung - Angemeldet als {}'.format(self.USERNAME),
'Was willst du tun?',
'[1] Benutzer anlegen',
'[2] Benutzer wechseln',
'[3] Benutzer löschen',
'[0] abbrechen'
]
userinput = self.userchoise(printtext, 4)
if userinput == 1:
self.create_user()
elif userinput == 2:
users = self.get_users()
printtext = ['Wähle deinen User:']
count = 1
for user in users:
printtext.append('[{}] {}'.format(count, user[1]))
count += 1
printtext.append('[0] abbrechen')
userid = self.userchoise(printtext, count)
self.USERID = users[userid - 1][0]
self.set_user()
elif userinput == 3:
users = self.get_users()
printtext = ['Welcher User soll gelöscht werden?:']
count = 1
for user in users:
printtext.append('[{}] {}'.format(count, user[1]))
count += 1
printtext.append('[0] abbrechen')
userid = self.userchoise(printtext, count)
self.delete_user(users[userid - 1][0])
## Reports
#=========
### One day report, optionally with time entries
def report_by_day(self, DATE=datetime.date.today(), USER='', DETAIL=''):
if not USER:
USER = self.USERID
timedata = self.get_time_entry(DAY=DATE, USERID=USER)
if timedata == 0:
print("Es wurden keine Zeiteinträge für den angegeben Tag gefunden")
logging.debug('No time entries for date: '.format(DATE))
input()
return 1
STARTTIMES = []
ENDTIMES = []
DURATIONS = []
for entry in timedata:
STARTTIMES.append(entry[1])
ENDTIMES.append(entry[2])
DURATIONS.append(entry[2] - entry[1])
if timedata:
FIRSTSTARTTIME = min(STARTTIMES)
LASTENDTIME = max(ENDTIMES)
TRACKEDTIMESPAN = (LASTENDTIME - FIRSTSTARTTIME)
TRACKEDTIME = sum(DURATIONS, datetime.timedelta())
NONTRACKEDTIME = (TRACKEDTIMESPAN - TRACKEDTIME)
ENTRIECOUNT = len(timedata)
self.clear_screen()
text = "{:40} {}"
print(text.format("Beginn des ersten Zeiteintrags:", FIRSTSTARTTIME.strftime('%d.%m.%Y %H:%M')))
print(text.format("Ende des letzen Zeiteintrags:", LASTENDTIME.strftime('%d.%m.%Y %H:%M')))
print(text.format("Maximal erfassbare Zeit:", self.timedela_to_string(TRACKEDTIMESPAN)))
print(text.format("Nicht erfasste Zeit:", self.timedela_to_string(NONTRACKEDTIME)))
print(text.format("Erfasste Zeit:", self.timedela_to_string(TRACKEDTIME)))
print(text.format("Zeiteinträge:", ENTRIECOUNT))
printtext = [
'Zeiteinträge anzeigen?',
'[1] Ja',
'[0] Nein'
]
userinput = self.userchoise(printtext)
if userinput == 1:
for entry in timedata:
self.print_time_entry(entry[1], entry[2], entry[4])
## Outputs
#=========
### Shows a time entry
def print_time_entry(self, STARTTIME='', ENDTIME='', ACTIVITY=''): def print_time_entry(self, STARTTIME='', ENDTIME='', ACTIVITY=''):
s = (ENDTIME - STARTTIME).seconds s = (ENDTIME - STARTTIME).seconds
hours, remainder = divmod(s, 3600) hours, remainder = divmod(s, 3600)
@@ -482,8 +705,33 @@ class TimeTrack:
print(ACTIVITY) print(ACTIVITY)
print(50*"-") print(50*"-")
## Miscellaneous
#===============
### User selection
def userchoise(self, TEXT='', MAX=2):
userinput = -1
while not -1 < int(userinput) < MAX:
for text in TEXT:
print(text)
userinput = input('Aktion: ')
logging.debug('User input: {}'.format(userinput))
try:
int(userinput)
except ValueError:
userinput = -1
else:
self.clear_screen()
return int(userinput)
### Conversion to string of Timedelta typ
def timedela_to_string(self, TIME):
s = TIME.seconds
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
output = '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))
return output
if __name__ == "__main__":
test = TimeTrack() test = TimeTrack()
test.time_start() test.start_interactive_mode()