Compare commits
3 Commits
58d0e6191c
...
c081f519dd
| Author | SHA1 | Date | |
|---|---|---|---|
| c081f519dd | |||
| 0765f45704 | |||
| 51709da8fc |
339
timeTrack.py
339
timeTrack.py
@@ -3,7 +3,7 @@
|
|||||||
#
|
#
|
||||||
# timeTrack.py
|
# timeTrack.py
|
||||||
# by 4nima
|
# by 4nima
|
||||||
# v.2.0.4
|
# v.2.1.0
|
||||||
#
|
#
|
||||||
#########################
|
#########################
|
||||||
# simple time tracking with database
|
# simple time tracking with database
|
||||||
@@ -38,6 +38,7 @@ class TimeTrack:
|
|||||||
self.DBCON.close()
|
self.DBCON.close()
|
||||||
|
|
||||||
## 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 os.name == 'posix':
|
||||||
@@ -47,6 +48,38 @@ class TimeTrack:
|
|||||||
logging.debug('Winwos System detected')
|
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['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
|
### Creates a database if none is found
|
||||||
def db_setup(self):
|
def db_setup(self):
|
||||||
if os.path.isfile(self.DATABASE):
|
if os.path.isfile(self.DATABASE):
|
||||||
@@ -62,7 +95,8 @@ class TimeTrack:
|
|||||||
endtime TIMESTAMP NOT NULL,
|
endtime TIMESTAMP NOT NULL,
|
||||||
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
|
||||||
)
|
)
|
||||||
@@ -113,39 +147,122 @@ class TimeTrack:
|
|||||||
else:
|
else:
|
||||||
logging.debug('Table was created successfully or already exists')
|
logging.debug('Table was created successfully or already exists')
|
||||||
|
|
||||||
### Loads or creates a config file
|
### Get an active event based on a user or event ID
|
||||||
def load_config(self):
|
def get_active_event(self, USERID='', EVENTID=''):
|
||||||
if os.path.isfile(self.CONFIG):
|
if USERID:
|
||||||
logging.info('Config file was found')
|
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:
|
try:
|
||||||
with open(self.CONFIG) as config_data:
|
with sqlite3.connect(self.DATABASE, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) as con:
|
||||||
data = json.load(config_data)
|
cur = con.cursor()
|
||||||
except ValueError:
|
if searchdata:
|
||||||
logging.error('Config file has no valid JSON syntax')
|
logging.debug('Search event')
|
||||||
print('TimeTrack wird beendet: Fehler in der JSON-Konfig ({})'.format(self.CONFIG))
|
cur.execute(sql, searchdata)
|
||||||
quit()
|
|
||||||
else:
|
else:
|
||||||
logging.info('Config file was loaded successfully')
|
logging.debug('Get all Events')
|
||||||
self.USERID = data['user']
|
cur.execute(sql)
|
||||||
self.OLDEVENT = data['oldevent']
|
eventdata = cur.fetchall()
|
||||||
logging.debug('UserID {} was used'.format(data['user']))
|
except sqlite3.Error as err:
|
||||||
self.set_user()
|
logging.debug(sql)
|
||||||
|
logging.error('SQLError: {}'.format(err))
|
||||||
|
print('Fehler beim auslesen der aktiven Events')
|
||||||
else:
|
else:
|
||||||
logging.warning('Config file not found')
|
logging.debug('Events could be read out successfully')
|
||||||
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 ?
|
con.close()
|
||||||
self.load_config()
|
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 == '':
|
||||||
@@ -221,9 +338,10 @@ class TimeTrack:
|
|||||||
self.USERNAME = data[0][1]
|
self.USERNAME = data[0][1]
|
||||||
|
|
||||||
## Time handling
|
## Time handling
|
||||||
|
#===============
|
||||||
### Creates an active event if none exists for the user
|
### Creates an active event if none exists for the user
|
||||||
def save_event(self, TIME=datetime.datetime.now()):
|
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))
|
logging.debug('No active events found for the user: {}'.format(self.USERID))
|
||||||
|
|
||||||
sql = "INSERT INTO active_events ( starttime, user_id ) VALUES ( ?, ? )"
|
sql = "INSERT INTO active_events ( starttime, user_id ) VALUES ( ?, ? )"
|
||||||
@@ -271,45 +389,7 @@ class TimeTrack:
|
|||||||
else:
|
else:
|
||||||
logging.debug('Event was successfully deleted')
|
logging.debug('Event was successfully deleted')
|
||||||
|
|
||||||
### Get an active event based on a user or event ID
|
### Checks for existing time entries and creates a new one if none is available.
|
||||||
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]
|
|
||||||
|
|
||||||
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()
|
||||||
@@ -319,7 +399,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')
|
||||||
@@ -368,8 +448,9 @@ class TimeTrack:
|
|||||||
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()
|
||||||
@@ -426,6 +507,7 @@ class TimeTrack:
|
|||||||
logging.info('Time entry was created successfully')
|
logging.info('Time entry was created successfully')
|
||||||
|
|
||||||
self.delete_event(data[0])
|
self.delete_event(data[0])
|
||||||
|
self.clear_screen()
|
||||||
self.print_time_entry(STARTTIME=data[1], ENDTIME=endtime, ACTIVITY=action)
|
self.print_time_entry(STARTTIME=data[1], ENDTIME=endtime, ACTIVITY=action)
|
||||||
print('Zeiteintrag wurde gespeichert.')
|
print('Zeiteintrag wurde gespeichert.')
|
||||||
userinput = 0
|
userinput = 0
|
||||||
@@ -444,8 +526,7 @@ class TimeTrack:
|
|||||||
if userinput == "1":
|
if userinput == "1":
|
||||||
self.time_start()
|
self.time_start()
|
||||||
else:
|
else:
|
||||||
logging.debug('Terminated by the user')
|
self.start_interactive_mode()
|
||||||
exit()
|
|
||||||
|
|
||||||
elif 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]))
|
||||||
@@ -454,11 +535,86 @@ class TimeTrack:
|
|||||||
logging.debug('Terminated by the user')
|
logging.debug('Terminated by the user')
|
||||||
exit()
|
exit()
|
||||||
|
|
||||||
def get_time(self):
|
## Interactive mode
|
||||||
pass
|
#==================
|
||||||
|
### Main menu of the interactive menu
|
||||||
def print_time_entry(self, STARTTIME='', ENDTIME='', ACTIVITY=''):
|
def start_interactive_mode(self):
|
||||||
self.clear_screen()
|
self.clear_screen()
|
||||||
|
printtext = [
|
||||||
|
'Was willst du tun?',
|
||||||
|
'[1] Zeiterfassung starten',
|
||||||
|
'[2] heutiger Report',
|
||||||
|
'[3] Report für Tag x',
|
||||||
|
'[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()
|
||||||
|
self.start_interactive_mode()
|
||||||
|
elif userinput == 3:
|
||||||
|
print('commig soon ...')
|
||||||
|
input()
|
||||||
|
self.start_interactive_mode()
|
||||||
|
elif userinput == 4:
|
||||||
|
print('commig soon ...')
|
||||||
|
input()
|
||||||
|
self.start_interactive_mode()
|
||||||
|
|
||||||
|
## 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)
|
||||||
|
|
||||||
|
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()
|
||||||
|
print('{:40} {}'.format("Beginn des ersten Zeiteintrags:", FIRSTSTARTTIME.strftime('%d.%m.%Y %H:%M')))
|
||||||
|
print('{:40} {}'.format("Ende des letzen Zeiteintrags:", LASTENDTIME.strftime('%d.%m.%Y %H:%M')))
|
||||||
|
print('{:40} {}'.format("Maximal erfassbare Zeit:", self.timedela_to_string(TRACKEDTIMESPAN)))
|
||||||
|
print('{:40} {}'.format("Nicht erfasste Zeit:", self.timedela_to_string(NONTRACKEDTIME)))
|
||||||
|
print('{:40} {}'.format("Erfasste Zeit:", self.timedela_to_string(TRACKEDTIME)))
|
||||||
|
print('{:40} {}'.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])
|
||||||
|
else:
|
||||||
|
self.start_interactive_mode()
|
||||||
|
|
||||||
|
## Outputs
|
||||||
|
#=========
|
||||||
|
### Shows a time entry
|
||||||
|
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)
|
||||||
minutes, seconds = divmod(remainder, 60)
|
minutes, seconds = divmod(remainder, 60)
|
||||||
@@ -472,7 +628,34 @@ 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__":
|
if __name__ == "__main__":
|
||||||
test = TimeTrack()
|
test = TimeTrack()
|
||||||
test.time_start()
|
test.start_interactive_mode()
|
||||||
test.DBCON.close()
|
test.DBCON.close()
|
||||||
Reference in New Issue
Block a user