-
Notifications
You must be signed in to change notification settings - Fork 0
/
chargeNumberTracker.py
executable file
·803 lines (685 loc) · 29.9 KB
/
chargeNumberTracker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
#!/usr/bin/env python3
###############################################################################
# Charge Number Timecard
# Copyright (C) 2020 Nathan Hui
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
#
# DATE Name Description
# -----------------------------------------------------------------------------
# 02/20/20 NH Added logging facility
# 02/16/20 NH Added time editing
# 01/27/20 NH Fixed backup, arrive, timeEdit
# 01/21/20 NH Fixed start from empty, Added wraparound, added backups
# 01/07/20 NH Fixed log hours launcher, Added settings editor, Enabling
# string based charge numbers, Removed implementation of old
# toDict to remove forward comptability, Added project
# sorting
# 01/04/20 NH Added auto save
# 01/02/20 NH Added custom record add, rounding to earliest time off,
# recording path
# 12/22/19 NH Fixed earliest release time
# 12/12/19 NH Initialized arrival charge number, added try catch to remove
# old data, removed extraneous print, added shortcuts
# 12/11/19 NH Fixed addProject bug, added error to notify failure to
# record start time, added initialization failure catch
# 12/10/19 NH Fixed on start bug
# 12/09/19 NH Initial Commit
#
###############################################################################
import tkinter as tk
import numpy as np
import datetime as dt
import json
import platform
import os
import tkcalendar as tkc
from tkinter import messagebox as tkMessageBox
import operator
import dataStore
import subprocess
import shlex
from tkinter import filedialog as tkf
import traceback
import glob
import logging
import sys
test = True
class Project():
def __init__(self, name, chargeNumber, isBillable, sortIdx=-1):
self.__log = logging.getLogger(
"chargeNumberTracker.Project(%s)" % (chargeNumber))
self.__log.info("Created")
self.name = name
self.chargeNumber = chargeNumber
self.hours = {}
self.isBillable = isBillable
if sortIdx == -1:
self.sortIdx = 999
else:
self.sortIdx = sortIdx
def addHours(self, hours, date):
assert(isinstance(hours, float) or isinstance(hours, dt.timedelta))
self.__log.info("Adding hours")
if date not in self.hours:
self.hours[date] = 0
if isinstance(hours, float):
self.hours[date] += hours
elif isinstance(hours, dt.timedelta):
self.hours[date] += hours.total_seconds() / 60.0 / 60.0
def setHours(self, hours, date):
assert(isinstance(hours, float) or isinstance(hours, dt.timedelta))
self.__log.info("Setting total hours")
if isinstance(hours, float):
self.hours[date] = hours
elif isinstance(hours, dt.timedelta):
self.hours[date] = hours.total_seconds() / 60.0 / 60.0
def getBillableHours(self, date):
self.__log.info("Retrieving total hours")
if not self.isBillable:
return 0
if date in self.hours:
return np.round(self.hours[date] * 4) / 4
else:
return 0
def __str__(self):
return "{%s(%s): %s}" % (self.name, self.chargeNumber, self.hours)
class HourTracker():
NUM_BACKUPS = 4
def __init__(self, path):
self.__log = logging.getLogger("chargeNumberTracker.HourTracker")
self.__log.info("Created")
self.path = os.path.join(path, 'data.json')
self.start = None
self.prevTime = dt.datetime.fromtimestamp(0)
self.arriveProject = None
self.addProjectCallback = []
self.addHoursCallback = []
self.dailyHours = 0
def open(self):
self.__log.debug("Open")
self.__enter__()
def close(self):
self.__log.debug("Close")
self.__exit__(None, None, None)
def __enter__(self):
self.__log.info("Initializing resources")
if os.path.isfile(self.path):
with open(self.path, 'r') as file:
data = json.load(file)
else:
self.__log.info("New data store")
data = {}
data = dataStore.fromDict(data)
self.dailyHours = data['dailyHours']
self.projects = data['projects']
self.timeRecord = data['timeRecord']
self.prevTime = data['prevTime']
self.arriveProject = data['arriveProject']
self.recordHoursPath = data['recordHoursPath']
def __exit__(self, exc_type, exc_value, tbk):
self.__log.info("Closing resources")
self.flush()
def flush(self):
self.__log.info("Flushing data")
data = dataStore.toDict(dailyHours=self.dailyHours,
projects=self.projects, timeRecord=self.timeRecord,
recordHoursPath=self.recordHoursPath)
existingBackups = glob.glob("%s.*" % (self.path))
existingBackupNums = [(backup, int(os.path.basename(
backup).split('.json.')[1])) for backup in existingBackups]
if len(existingBackups) >= self.NUM_BACKUPS:
os.remove(existingBackupNums[-1][0])
existingBackupNums = existingBackupNums[0:-1]
for backup, number in sorted(existingBackupNums, reverse=True, key=lambda x: x[1]):
os.rename(backup, "%s.%d" % (self.path, number + 1))
if os.path.isfile(self.path):
os.rename(self.path, "%s.%d" % (self.path, 0))
with open(self.path, 'w') as file:
json.dump(data, file, indent=4, sort_keys=True)
def registerAddProjectCallback(self, func):
self.__log.debug("Adding AddProject callback")
self.addProjectCallback.append(func)
def registerAddHoursCallback(self, func):
self.__log.debug("Adding AddHours Callback")
self.addHoursCallback.append(func)
def getProjectNames(self, includeArrival=False):
self.__log.debug("Getting project names")
if includeArrival:
return {project.name: project for project in self.projects}
else:
return {project.name: project for project in self.projects
if project.chargeNumber != "0"}
def addProject(self, project):
self.__log.debug("Adding project")
self.projects.append(project)
for func in self.addProjectCallback:
func(project)
def __today(self):
self.__log.debug("Getting today's records")
return self.timeRecord[dt.datetime.today().date()]
def recordArrive(self, time=dt.datetime.now()):
self.__log.info("Recording arrival")
self.start = time
self.prevTime = self.start
self.timeRecord[dt.datetime.today().date()] = {}
self.__today()[self.start] = self.arriveProject
for func in self.addHoursCallback:
func(self.arriveProject)
self.flush()
def addRecord(self, time, project):
self.__log.info("Recording timestamp")
self.timeRecord[time.date()][time] = project
# Update project hours
timeRef = {}
startTime = sorted(self.timeRecord[time.date()].keys())[0]
for endTime in sorted(self.timeRecord[time.date()].keys())[1:]:
if self.timeRecord[time.date()][endTime] not in timeRef:
timeRef[self.timeRecord[time.date()][endTime]] = endTime - \
startTime
else:
timeRef[self.timeRecord[time.date()][endTime]] += endTime - \
startTime
startTime = endTime
for proj, tDelta in timeRef.items():
proj.setHours(tDelta, time.date())
if time > self.prevTime:
self.prevTime = time
for func in self.addHoursCallback:
func(project)
self.flush()
def recordHours(self, project):
self.__log.info("Recording hours")
time = dt.datetime.now()
self.__today()[time] = project
project.addHours(time - self.prevTime, time.date())
self.prevTime = time
for func in self.addHoursCallback:
func(project)
self.flush()
def getTodayTotalHours(self):
self.__log.info("Retrieving today's hours")
date = dt.datetime.now().date()
totalHours = 0
projectHours = self.getHours(date)
for chargeNumber, hours in projectHours.items():
totalHours += hours
return totalHours
def getTodayRemainingHours(self):
return self.dailyHours - self.getTodayTotalHours()
def getEarliestReleaseTime(self):
if self.prevTime.date() != dt.datetime.now().date():
return dt.datetime.now() + \
dt.timedelta(hours=self.getTodayRemainingHours()) - \
dt.timedelta(minutes=7.5)
return self.prevTime + \
dt.timedelta(hours=self.getTodayRemainingHours()) - \
dt.timedelta(minutes=7.5)
def getHours(self, date):
retval = {}
for project in self.projects:
retval[project.chargeNumber] = project.getBillableHours(date)
return retval
class HourTrackerViewer(tk.Frame):
def __init__(self, master, hourTracker):
self.hourTracker = hourTracker
self.innerFrame = None
self.nameMap = None
self.projectNameIdx = 0
self._displayedProjects = {}
self.timeRecord = hourTracker.timeRecord
super().__init__(master)
self.__createWidget()
self.hourTracker.registerAddProjectCallback(self.updateProject)
def __createWidget(self):
if self.innerFrame is not None:
self.innerFrame.destroy()
self.innerFrame = tk.Frame(self)
self.dateSelector = tk.StringVar()
dateEntry = tkc.DateEntry(self.innerFrame,
textvariable=self.dateSelector, maxdate=dt.datetime.today())
dateEntry.grid(row=0, column=0, columnspan=2)
dateEntry.bind('<<DateEntrySelected>>', self.setDate)
self.recordFrame = None
self.setDate()
self.projectSelector = tk.StringVar()
self.nameMap = self.hourTracker.getProjectNames()
self.projectNames = [project.name for project
in sorted(self.nameMap.values(),
key=operator.attrgetter('sortIdx'))]
if len(self.nameMap) > 0:
self.projectSelector.set(self.projectNames[self.projectNameIdx])
tk.OptionMenu(self.innerFrame, self.projectSelector,
*tuple(self.projectNames)).grid(row=2, column=0)
button = tk.Button(self.innerFrame, text='Record',
command=self.recordActivity)
button.grid(row=2, column=1)
button.bind("<Up>", self.__changeProjectUp)
button.bind("<Down>", self.__changeProjectDown)
self.innerFrame.grid(row=0, column=0)
def __changeProjectUp(self, *args):
self.projectNameIdx -= 1
if self.projectNameIdx < 0:
self.projectNameIdx = 0
self.projectSelector.set(self.projectNames[self.projectNameIdx])
def __changeProjectDown(self, *args):
self.projectNameIdx += 1
if self.projectNameIdx >= len(self.projectNames):
self.projectNameIdx = len(self.projectNames) - 1
self.projectSelector.set(self.projectNames[self.projectNameIdx])
def updateProject(self, project):
self.__createWidget()
def update(self):
self.__createWidget()
def recordActivity(self):
projectName = self.projectSelector.get()
project = self.nameMap[projectName]
try:
self.hourTracker.recordHours(project)
except KeyError:
tkMessageBox.showerror(
'Entry Error', 'Error: Start time not found!')
return
self.projectSelector.set(self.projectNames[0])
self.innerFrame.destroy()
self.innerFrame = tk.Frame(self)
self.__createWidget()
def setDate(self, *args):
if self.recordFrame is not None:
self.recordFrame.destroy()
self._displayedProjects = {}
self.recordFrame = tk.Frame(self.innerFrame)
date = dt.datetime.strptime(self.dateSelector.get(), '%m/%d/%y').date()
if date in self.hourTracker.timeRecord:
row = 0
for record in sorted(self.hourTracker.timeRecord[date].items()):
timeLabel = tk.Label(self.recordFrame, text=record[0].strftime(
'%H:%M'))
timeLabel.grid(row=row, column=0)
projectLabel = tk.Label(self.recordFrame, text=record[1].name)
projectLabel.grid(row=row, column=1)
projectLabel.bind('<Double-Button-1>',
self.__editChargeNumberHandler)
self._displayedProjects[projectLabel] = [
record[0], timeLabel, record[1], self.hourTracker.timeRecord[date]]
row += 1
self.recordFrame.grid(row=1, column=0, columnspan=2)
def __editChargeNumberHandler(self, event: tk.Event):
timestamp, timeLabel, project, projectTree = self._displayedProjects[event.widget]
d = TimeEditor(self, self.hourTracker.getProjectNames(includeArrival=True), title='Edit Time',
time=self._displayedProjects[event.widget][0], project=project)
if d.result:
if d.result[1] != project and d.result[0] == timestamp:
# Just need to update the charge number
projectTree[timestamp] = d.result[1]
elif d.result[0] != timestamp and d.result[1] == project:
# Adjusting the time
projectTree.pop(timestamp, None)
projectTree[d.result[0]] = project
else:
# Adjusting time and charge number
projectTree.pop(timestamp, None)
projectTree[d.result[0]] = d.result[1]
self.update()
class ProjectList(tk.Frame):
def __init__(self, master, hourTracker):
super().__init__(master)
self.hourTracker = hourTracker
self.hourTracker.registerAddHoursCallback(self.updateHours)
self.innerFrame = None
self.createWidget()
def updateHours(self, project):
self.createWidget()
def createWidget(self):
if self.innerFrame is not None:
self.innerFrame.destroy()
self.innerFrame = tk.Frame(self)
row = 0
today = dt.datetime.today().date()
for project in sorted(self.hourTracker.projects, key=operator.attrgetter('sortIdx')):
if project.chargeNumber != "0":
tk.Label(self.innerFrame, text=project.name,
anchor=tk.NW).grid(row=row, column=0)
tk.Label(self.innerFrame, text='%s' % (
project.chargeNumber), anchor=tk.NW).grid(row=row, column=1)
billableHours = project.getBillableHours(today)
if billableHours > 0:
tk.Label(self.innerFrame, text='%.2f hrs' % (
billableHours), anchor=tk.NW).grid(row=row, column=2)
else:
tk.Label(self.innerFrame, text="").grid(row=row, column=2)
row += 1
self.projectEntry = tk.StringVar()
self.chargeNumberEntry = tk.StringVar()
tk.Entry(self.innerFrame, textvariable=self.projectEntry).grid(
row=row, column=0)
entry = tk.Entry(self.innerFrame, textvariable=self.chargeNumberEntry)
entry.grid(row=row, column=1)
entry.bind('<Return>', self.addProject)
entry.bind('<KP_Enter>', self.addProject)
button = tk.Button(self.innerFrame, text='Add Project',
command=self.addProject)
button.grid(row=row, column=2)
button.bind('<Return>', self.addProject)
button.bind('<KP_Enter>', self.addProject)
tk.Label(self.innerFrame, text="Total Hours: %.2f" % (
self.hourTracker.getTodayTotalHours()), anchor=tk.NW).grid(row=0, column=3)
earliestReleaseTime = self.hourTracker.getEarliestReleaseTime()
tk.Label(self.innerFrame, text="Earliest Off Time: %s" % (self.hourTracker.getEarliestReleaseTime(
).time().strftime('%H:%M')), anchor=tk.NW).grid(row=1, column=3)
self.innerFrame.grid(row=0, column=0)
def addProject(self, *args):
self.hourTracker.addProject(
Project(self.projectEntry.get(), self.chargeNumberEntry.get(), True))
self.projectEntry.set("")
self.chargeNumberEntry.set('')
self.createWidget()
class SettingsDialog(tk.Toplevel):
def __init__(self, parent, hour_tracker):
tk.Toplevel.__init__(self, parent)
self.transient(parent)
self.title("Settings")
self.parent = parent
self.hour_tracker = hour_tracker
self.recordHoursPath = tk.StringVar()
self.recordHoursPath.set(self.hour_tracker.recordHoursPath)
self.bodyFrame = None
self.initial_focus = self.createBody()
self.acceptFrame = None
self.createAcceptFrame()
self.grab_set()
if not self.initial_focus:
self.initial_focus = self
self.protocol("WM_DELETE_WINDOW", self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx() + 50,
parent.winfo_rooty() + 50))
self.initial_focus.focus_set()
self.wait_window(self)
def createBody(self):
if self.bodyFrame is not None:
self.bodyFrame.destroy()
self.bodyFrame = tk.Frame(self)
tk.Label(self.bodyFrame, text="Hour Log App:").grid(row=0, column=0)
entry = tk.Entry(self.bodyFrame, textvariable=self.recordHoursPath).grid(
row=0, column=1)
tk.Button(self.bodyFrame, text='...',
command=self.getRecordHoursPath).grid(row=0, column=2)
self.bodyFrame.grid(row=0, column=0)
def getRecordHoursPath(self):
if self.recordHoursPath.get() is "":
if platform.system() == "Linux":
init_path = "/usr/local/bin"
else:
init_path = "C:\\Program Files"
else:
init_path = os.path.dirname(self.recordHoursPath.get())
newPath = tkf.askopenfilename(initialdir=init_path, parent=self)
self.recordHoursPath.set(newPath)
def createAcceptFrame(self):
if self.acceptFrame is not None:
self.acceptFrame.destroy()
self.acceptFrame = tk.Frame(self)
tk.Button(self.acceptFrame, text="OK",
command=self.ok).grid(row=0, column=0)
tk.Button(self.acceptFrame, text='Cancel',
command=self.cancel).grid(row=0, column=1)
self.acceptFrame.grid(row=1, column=0)
def cancel(self, event=None):
self.parent.focus_set()
self.destroy()
def validate(self):
try:
assert(os.path.isfile(self.recordHoursPath.get()))
return True
except:
return False
def ok(self, event=None):
if not self.validate():
return
self.withdraw()
self.update_idletasks()
# apply changes
self.hour_tracker.recordHoursPath = self.recordHoursPath.get()
self.cancel()
class TimeEditor(tk.Toplevel):
def __init__(self, parent, projects, title=None, time=dt.datetime.now(), project=None):
tk.Toplevel.__init__(self, parent)
self.transient(parent)
if title:
self.title(title)
else:
self.title("Custom Time")
self.parent = parent
self.result = None
self.projects = projects
self.time = time
body = tk.Frame(self)
self.dateSelector = tk.StringVar()
self.hrSelector = tk.StringVar()
self.hrSelector.set(time.hour)
self.minSelector = tk.StringVar()
self.minSelector.set(time.minute)
self.projectSelector = tk.StringVar()
self.projectNames = [project.name for project
in sorted(self.projects.values(),
key=operator.attrgetter('chargeNumber'))]
if project is None:
self.projectNameIdx = 0
else:
self.projectNameIdx = self.projectNames.index(project.name)
self.initial_focus = self.create(body)
body.grid(row=0, column=0, padx=5, pady=5)
buttonbox = tk.Frame(self)
submitButton = tk.Button(buttonbox, text='Submit', width=10,
command=self.ok)
submitButton.grid(row=0, column=0, padx=5, pady=5)
cancelButton = tk.Button(buttonbox, text='Cancel', width=10,
command=self.cancel)
cancelButton.grid(row=0, column=1, padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
buttonbox.grid(row=1, column=0)
if not self.initial_focus:
self.initial_focus = self
self.protocol("WM_DELETE_WINDOW", self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx() + 50,
parent.winfo_rooty() + 50))
self.initial_focus.focus_set()
self.grab_set()
self.wait_window(self)
def create(self, parent):
self.dateEntry = tkc.DateEntry(parent, textvariable=self.dateSelector,
maxdate=self.time)
self.dateEntry.grid(row=0, column=0, columnspan=2)
hr = tk.Spinbox(parent, from_=-1, to=24, textvariable=self.hrSelector,
width=5)
hr.grid(row=1, column=0)
min_ = tk.Spinbox(parent, from_=-1, to=60, textvariable=self.minSelector,
width=5, command=self.rotateMin)
min_.grid(row=1, column=1)
if len(self.projects) > 0:
self.projectSelector.set(self.projectNames[self.projectNameIdx])
tk.OptionMenu(parent, self.projectSelector, *tuple(self.projectNames))\
.grid(row=2, column=0, columnspan=2)
def rotateMin(self):
if self.minSelector.get() == "-1":
self.minSelector.set("59")
hr = int(self.hrSelector.get()) - 1
if hr == -1:
hr = 23
date = dt.datetime.strptime(
self.dateSelector.get(), '%m/%d/%y')
date = date.replace(day=date.day - 1)
self.dateSelector.set(date.strftime('%m/%d/%y'))
self.hrSelector.set(str(hr))
elif self.minSelector.get() == "60":
self.minSelector.set('0')
hr = int(self.hrSelector.get()) + 1
self.hrSelector.set(str(hr))
if hr == 24:
hr = 0
date = dt.datetime.strptime(
self.dateSelector.get(), '%m/%d/%y')
date = date.replace(day=date.day + 1)
self.dateSelector.set(date.strftime('%m/%d/%y'))
self.hrSelector.set(str(hr))
def ok(self, event=None):
self.withdraw()
self.update_idletasks()
self.apply()
self.cancel()
def cancel(self, event=None):
# put focus back to the parent window
self.parent.focus_set()
self.destroy()
def apply(self):
date = dt.datetime.strptime(self.dateSelector.get(), '%m/%d/%y')
hr = int(self.hrSelector.get())
min_ = int(self.minSelector.get())
date = date.replace(hour=hr)
date = date.replace(minute=min_)
self.result = date, self.projects[self.projectSelector.get()]
class ChargeNumberTrackerApp:
def __init__(self):
self.__log = logging.getLogger("chargeNumberTracker.App")
self.platform = platform.system()
if test:
self.dataPath = os.path.join('.', 'chargeNumber')
self.__log.info("Test mode")
elif self.platform == 'Linux':
self.dataPath = os.path.expanduser(
os.path.join('~', '.chargeNumber'))
self.__log.debug("Detected Linux")
elif self.platform == 'Darwin':
self.dataPath = os.path.expanduser(
os.path.join('~', '.chargeNumber'))
self.__log.debug("Detected MacOS")
elif self.platform == 'Windows':
self.dataPath = os.path.expanduser(os.path.join('~', 'Appdata',
'Roaming', 'chargeNumber'))
self.__log.debug("Detected Windows")
else:
self.__log.warning("Unknown platform")
raise RuntimeError("Unknown Platform!")
if not os.path.isdir(self.dataPath):
os.mkdir(self.dataPath)
self.tracker = HourTracker(self.dataPath)
try:
self.tracker.open()
except Exception as e:
print(traceback.print_last())
self.__log.info("Failed to load data")
if tkMessageBox.askyesno("Charge Number Hour Tracker", "Failed to "
"load data - would you like to delete the old data?"):
try:
self.__log.info("Deleting old data")
os.remove(self.tracker.path)
self.__log.info("Opening clean")
self.tracker.open()
except:
tkMessageBox.askokcancel(
"Charge Number Hour Tracker", "Fatal Error - Exiting")
sys.exit()
else:
self.__log.info("User declined to clean bad data")
return
self.__log.debug("Creating GUI")
self.master = tk.Tk()
self.master.protocol("WM_DELETE_WINDOW", self.destroy)
self.master.title('Charge Number Hour Tracker')
self.menubar = None
self.createMenu()
self.__log.debug("Creating Hour Tracker Viewer")
self.htViewer = HourTrackerViewer(self.master, self.tracker)
self.htViewer.grid(row=0, column=0, sticky=tk.NW)
self.__log.debug("Creating Project List Viewer")
ProjectList(self.master, self.tracker).grid(
row=0, column=1, sticky=tk.NW)
self.__log.debug("Assigning global hotkey")
self.master.bind('<Control-Shift-S>', self.arrive)
self.__log.debug("Starting main loop")
self.master.mainloop()
def createMenu(self):
self.__log.info("Creating menu")
if self.menubar:
self.__log.debug("Refreshing menu")
self.menubar.destroy()
self.menubar = tk.Menu(self.master)
filemenu = tk.Menu(self.menubar, tearoff=0)
filemenu.add_command(label='Arrive', command=self.arrive)
filemenu.add_command(label='Get Hours', command=self.getHours)
filemenu.add_command(label='Record Custom...',
command=self.recordCustom)
filemenu.add_separator()
filemenu.add_command(label='Preferences', command=self.setPrefs)
filemenu.add_separator()
filemenu.add_command(label='Log Hours', command=self.logHours,
state=("disabled" if self.tracker.recordHoursPath is "" else "normal"))
filemenu.add_separator()
filemenu.add_command(label='Exit', command=self.destroy)
self.menubar.add_cascade(label="File", menu=filemenu)
self.master.config(menu=self.menubar)
def logHours(self):
self.__log.info("Logging Hours")
excPath = self.tracker.recordHoursPath
if excPath is not "":
if platform.system() == 'Linux':
subprocess.Popen(shlex.split(excPath))
elif platform.system() == 'Windows':
subprocess.Popen(shlex.split(excPath, posix=False), shell=True)
def arrive(self, *args):
self.__log.info("Recording arrive")
self.tracker.recordArrive()
self.htViewer.update()
def destroy(self):
self.__log.info("Exiting")
self.tracker.close()
self.master.destroy()
def getHours(self):
self.__log.info("Retrieving hours")
print(self.tracker.getHours(dt.datetime.today().date()))
def recordCustom(self):
self.__log.info("Custom Time")
d = TimeEditor(
self.master, self.tracker.getProjectNames(includeArrival=True))
if d.result:
self.__log.info("Received result")
if d.result[1] == self.tracker.arriveProject:
self.__log.info("Custom arrival")
self.tracker.recordArrive(d.result[0])
else:
self.__log.info("Custom project")
self.tracker.addRecord(*d.result)
self.htViewer.update()
def setPrefs(self):
self.__log.info("Opening settings")
d = SettingsDialog(self.master, self.tracker)
self.createMenu()
if __name__ == '__main__':
logName = 'log.log'
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
consoleOutput = logging.StreamHandler(sys.stdout)
consoleOutput.setLevel(logging.WARNING)
formatter = logging.Formatter(
'%(asctime)s.%(msecs)03d: %(levelname)s:%(name)s: %(message)s', datefmt='%Y-%M-%d %H:%m:%S')
consoleOutput.setFormatter(formatter)
logger.addHandler(consoleOutput)
fileOutput = logging.FileHandler(logName)
fileOutput.setLevel(logging.INFO)
fileOutput.setFormatter(formatter)
logger.addHandler(fileOutput)
root = ChargeNumberTrackerApp()