-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.py
1843 lines (1475 loc) · 56.8 KB
/
cli.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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
########### SVN repository information ###########
# $Date$
# $Author$
# $Revision$
# $URL$
# $Id$
########### SVN repository information ###########
'''
A CLI (command-line interface) for Kevin's monthly-reporting package
'''
import sys
import os
import readline
import time
import datetime
import string
import textwrap
import os.path
import config
import entry
import log
import mkrep
#!import logging
# Log file is necessary for debugging tab-completion problems
#!LOG_FILENAME = 'completer.log'
#!logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
class ReportCli:
'''
The command-line interface class, which interacts with the log module.
Known problems: groups with strings can only be tab-completed before the first space is typed.
'''
def __init__(self):
# Remove '-' from delim list so entries with dashes tab-complete properly
delims = readline.get_completer_delims()
#!print(",".join(["%x" % ord(x) for x in delims]))
# Allow dashes to be included in tab-completed words. Spaces can't be handled here since they are word separators part of the time.
new_delims = delims.replace("-",'')
readline.set_completer_delims(new_delims)
#!delims2 = readline.get_completer_delims()
#!print(",".join(["%x" % ord(x) for x in delims2]))
self.commands = {
"help": self.displayHelp,
"h": self.displayHelp,
"print": self.displayLog,
"p": self.displayLog,
"add": self.addEntry,
"a": self.addEntry,
"corr": self.correctEntry,
"c": self.correctEntry,
"ch": self.changeTitle,
"chd": self.changeDate,
"cld": self.clearDate,
"lsd": self.showDate,
"day": self.displayDay,
"d": self.displayDay,
"wtab": self.displayWeekTable,
"wt": self.displayWeekTable,
"wsum": self.displayWeekSummary,
"ws": self.displayWeekSummary,
"wrep": self.displayWeekReport,
"wr": self.displayWeekReport,
"wn": self.displayWeekNotes,
"wd": self.displayWeekDayforce,
"dsum": self.displayDaySummary,
"ds": self.displayDaySummary,
"save": self.saveLog,
"s": self.saveLog,
"exit": self.quit,
"quit": self.quit,
"q": self.quit,
"sum": self.displaySummary,
"psum": self.displayPercentSummary,
"rep": self.displayReport,
"prep": self.displayPercentReport,
"list": self.listLabels,
"l": self.listLabels,
"groups": self.listGroups,
"lg": self.listGroups,
"codes": self.listPayCodes,
"pc": self.listPayCodes,
"pcr": self.displayPayCodeReport,
"sc": self.startCapture,
"ec": self.endCapture,
"tpc": self.togglePayCodePrompt,
"xml": self.createReportXml,
"mkrep": self.makePdfReport,
}
self.possibleActivities = config.possible_activities[:]
self.possibleGroups = config.possible_groups[:]
self.possiblePayCodes = config.possible_payCodes[:]
self.defaultPayCode = "RG"
self.promptForPayCode = True
self.logFilename = "work_log.xml"
self.terminalWidth = 132
self.tabSize = 8
self.showCorrectDefaults = False
self.showCorrectDescLen = 40
self.wrDateSort = True
self.showCostCodes = False
self.showWBSCodes = False
self.showPayCodes = False
self.customDate = None
# Override the above definitions
self.definitions()
# Flag to continue prompting for commands
self.run = True
# Dirty flag to indicate unsaved changes
self.dirty = False
#
self.outFile=sys.stdout
# Capture file open flag
self.captureFileHandle = None
# Capture file name
self.captureFile = None
# Run the main loop
self.runMainLoop()
def runMainLoop(self):
# Get log filename
self.filepath, self.directory, self.filename = self._getLogFilename()
if self.run == True:
# Let the user know which file is being used
print("Reading {}".format(self.filepath))
# Read log file into persistent log object
self.logObj = self.createReportLog(self.filepath)
self.logEntryDef = self.logObj.getLogEntryDef()
# Run the main loop
self.main()
def createReportLog(self, filepath):
'''
Method called by __init__ to create the ReportLog instance. Designed to be overriden without having to reimplement __init__.
'''
return log.ReportLog(filepath)
def definitions(self):
'''
Method called by __init__ to define the default work log file name and allow commands to be added. Designed to be overridden without having to reimplement __init__.
'''
pass
def displayHelp(self, *args):
'''
Called when "help" or "h" is typed. Prints a help message.
'''
#!print("displayHelp(", args, ")")
print("""
Commands:
help (h) displays this help
groups (lg) list all available groups
codes (pc) list all available pay codes
tpc Toggle prompt for pay code when adding entries
add (a) adds an entry to the log file
save (s) saves changes to the log file
corr (c) [#] corrects the specified entry (default=last)
chd set a custom date to be used as the default
cld clear the custom date
lsd list the default date
day (d) [#] prints list of entries for a given day (default=today)
dsum (ds) [#] prints summary of entries for a given day (default=today)
wtab (wt) [#] prints a table of hours in green-sheet format
wsum (ws) [#] displays the week summary w/o details (hours)
wrep (wr) [#] displays the week summary w/ details (hours)
wd [#] prints a table in dayforce format
sum [cat] displays the month summary w/o details (hours)
psum [cat] displays the month summary w/o details (percent)
rep [cat] displays the month summary w/ details (hours)
prep [cat] displays the month summary w/ details (percent)
pcr [pc] displays a pay code report w/o details (hours)
print (p) [#] prints info from the log file (default=everything)
list [label ...] list the labels used in the log. Default labels are
activity, group and title.
xml Generates a skeleton xml report in the same directory
as the work log. Categories and keywords in the work log
correspond to titles and subjects in the xml report.
Details must be MANUALLY entered after examining output
of the 'prep' command.
mkrep Converts an xml file into a pdf. Titles are optional
and do not currently appear in the pdf.
ch Bulk title change. Make a BACKUP of your log before using
this feature, since it hasn't been extensively tested yet.
sc Start capturing report output to a text file instead of
printing it to stdout.
ec End capture report output to a text file. Quitting will
automatically close this file.
""")
return True
def changeDate(self, *args):
'''
Set a default date other than today
'''
#!print(args)
if len(args) != 1:
print("Usage: chd DAY\n or: chd YYYY-MM-DD")
else:
# Temporarily assume user always gives a valid date
newDate = args[0]
day = None
# validate the date (code duplicated in entry.py)
try:
if len(newDate) > 2:
# a full date was specified
if newDate.count('/') == 2:
# don't accept slashes
newDate = newDate.replace('/', '-')
# the following line generates an exception if the newDate is not valid
time.strptime(newDate, '%Y-%m-%d')
else:
# a day of the current month was specified
if len(newDate) == 1:
day = "0" + newDate
else:
day = newDate
newDate = time.strftime("%Y-%m-") + day
time.strptime(newDate, '%Y-%m-%d')
except ValueError:
if day == None:
print("{} is not a valid date".format(args[0]))
else:
print("{} is not a valid day of the month".format(args[0]))
else:
self.customDate = newDate
print("{} is the new, default date".format(self.customDate))
return True
def clearDate(self, *args):
'''
Clear the custom date (returns to default: today)
'''
self.customDate = None
return True
def showDate(self, *args):
'''
Display the default date
'''
if (self.customDate != None):
print("Custom date = {}".format(self.customDate))
else:
print("Default date = {}".format(time.strftime("%Y-%m-%d")))
return True
def _removeHistoryEntry(self):
'''
Remove an entry from the readline input history
'''
pos = readline.get_current_history_length()-1
#!print("Removing {} from history, pos={}".format(readline.get_history_item(pos+1), pos+1))
readline.remove_history_item(pos)
def makePdfReport(self, *args):
'''
Convert a report xml file into a pdf.
Calls mkrep.makeReport()
'''
# Interpret empty directory as pwd
if self.directory == '':
directory = "."
else:
directory = self.directory
# Create a list of xml files in the same directory as the work_log
files = os.listdir(directory)
xmlFiles = []
#!print(files)
for f in files:
if f[-4:] == ".xml" and f != self.filename:
xmlFiles.append(f)
# Print xml files in the directory that aren't the work_log
print("Found XML files: {}".format(", ".join(xmlFiles)))
# Prompt user for desired xml file with autocomplete
try:
# Turn on tab complete
readline.parse_and_bind("tab: complete")
completer = _TabCompleter(xmlFiles[:])
readline.set_completer(completer.complete)
# Get xml file
desiredXml = input("XML file to convert: ")
if desiredXml != '':
self._removeHistoryEntry()
else:
#!print("You didn't specify a file, assuming you want dummy.xml")
desiredXml = "dummy.xml"
# Catch KeyboardInterrupt to allow the user to exit the entry process
except (KeyboardInterrupt, EOFError):
print("")
print("Aborting...")
return True
finally:
# Restore main completer
readline.set_completer(self.mainCompleter.complete)
#!print("desiredXml = {}".format(desiredXml))
# Verify that the file exists
fullFilePath = "{}/{}".format(directory, desiredXml)
#!print(fullFilePath)
if os.path.exists(fullFilePath) == False:
print("The desired xml file ({}) doesn't exist.".format(fullFilePath))
return True
# Call mkrep.makeReport()
status = mkrep.makeReport(fullFilePath)
return True
def createReportXml(self, *args):
'''
Method responsible for creating a skeleton xml report based on the work log.
Calls mkrep.makeXml()
'''
#!print("createReportXml(", args, ")")
analysis = self.logObj.getAnalysis()
if analysis == None:
print("! The log is empty.")
return True
# Prompt user for desired filename (Assume just a filename, not a path)
try:
desiredFilename = input("XML report filename: ")
# Remove text entry from history
if desiredFilename != "":
self._removeHistoryEntry()
# Catch Ctrl+c and Ctrl+d to allow the user to exit the entry process
except (KeyboardInterrupt, EOFError):
print("")
print("Aborting...")
return True
# Use a default filename if it was left blank
if desiredFilename == "":
desiredFilename = "skeletonReport.xml"
# Make sure file has xml extension
fparts = desiredFilename.split(".")
if len(fparts) >= 2 and fparts[len(fparts)-1] == "xml":
pass
else:
desiredFilename = desiredFilename + ".xml"
# Abort rather than overwrite an existing file
if os.path.exists("{}/{}".format(self.directory, desiredFilename)):
print("Can't write xml report. {}/{} already exists.".format(self.directory, desiredFilename))
return True
try:
# Prompt user for their name
fullName = input("Your name: ")
# Remove text entry from history
if fullName != "":
self._removeHistoryEntry()
# Catch Ctrl+c and Ctrl+d to allow the user to exit the entry process
except (KeyboardInterrupt, EOFError):
print("")
print("Aborting...")
return True
status = mkrep.makeXml(analysis, self.directory, desiredFilename, fullName)
return True
def _recursiveDisplayLabels(self, struct, level=0):
'''
Display the labels used in the report
'''
#!print("Displaying stuff", struct)
indentStr = " "
if type(struct) is dict:
keys = list(struct.keys())
keys = sorted(keys)
for k in keys:
print(indentStr * level + k)
self._recursiveDisplayLabels(struct[k], level+1)
if type(struct) is list:
for item in struct:
print(indentStr * level + item)
def listLabels(self, *args):
'''
Method to display the heirarchy of labels used for the entries in the log
args is a tuple of the labels that defines the nesting used when displaying the results.
'''
#!print("listLabels(", args, ")")
defaultLabels = ['activity', 'group', 'title']
if args == ():
labels = defaultLabels[:]
else:
# only include valid arguments
labels = []
for label in args:
if label in self.logEntryDef:
labels.append(label)
else:
print("! {} is not a valid label.".format(label))
#!print(labels)
#!print("Listing the following:")
print("")
for i in range(len(labels)):
print(" " * i + labels[i])
if len(labels) != 0:
struct = self.logObj.collectLabels(labels)
print("---" * (len(labels) + 1 ))
self._recursiveDisplayLabels(struct)
print("")
return True
def listGroups(self, *args):
'''
Method to display the complete list of valid groups
args is currently ignored
'''
#!print("listLabels(", args, ")")
print("Possible groups: {}".format(", ".join(config.possible_groups[1:])))
return True
def listPayCodes(self, *args):
'''
Method to display the complete list of valid pay codes
args is currently ignored
'''
#!print("listLabels(", args, ")")
print("Possible pay codes: {}".format(", ".join(sorted(config.possible_payCodes[:]))))
return True
def togglePayCodePrompt(self, *args):
'''
Method to toggle prompt for the pay code when adding entries
args is currently ignored
'''
if self.promptForPayCode == True:
self.promptForPayCode = False
print("Prompt for pay code: Disabled")
else:
self.promptForPayCode = True
print("Prompt for pay code: Enabled")
return True
def displayReport(self, *args):
'''
Method to display the summary with details in hours.
args is an tuple of group strings to display. If no groups are specified, all groups are displayed.
'''
#!print("displayReport(", args, ")")
analysis = self.logObj.getAnalysis()
if analysis != None:
self._displayAnalysis(analysis, verbose=True, percents=False, dateSort=False, desiredGroups=args)
else:
print("! The log is empty.")
return True
def displayPercentReport(self, *args):
'''
Method to display the summary with details in percents.
args is an tuple of group strings to display. If no groups are specified, all groups are displayed.
'''
#!print("displayPercentReport(", args, ")")
analysis = self.logObj.getAnalysis()
if analysis != None:
self._displayAnalysis(analysis, verbose=True, percents=True, dateSort=False, desiredGroups=args)
else:
print("! The log is empty.")
return True
def displaySummary(self, *args):
'''
Method to display the summary in hours.
args is an tuple of group strings to display. If no groups are specified, all groups are displayed.
'''
#!print("displaySummary(", args, ")")
analysis = self.logObj.getAnalysis()
if analysis != None:
self._displayAnalysis(analysis, verbose=False, percents=False, dateSort=False, desiredGroups=args)
else:
print("! The log is empty.")
return True
def displayPercentSummary(self, *args):
'''
Method to display the summary in percents.
args is an tuple of group strings to display. If no groups are specified, all groups are displayed.
'''
#!print("displayPercentSummary(", args, ")")
analysis = self.logObj.getAnalysis()
if analysis != None:
self._displayAnalysis(analysis, verbose=False, percents=True, dateSort=False, desiredGroups=args)
else:
print("! The log is empty.")
return True
def _displayAnalysis(self, analysis, verbose=False, percents=False, dateSort=False, lessInfo=False, desiredGroups=()):
'''
Method that actually displays the analysis
'''
#!print(analysis)
details = analysis[0]
groupTotals = analysis[1]
titleTotals = analysis[2]
recordedTotal = analysis[3]
theoreticalHours = analysis[4]
percent = analysis[5]
groups = list(titleTotals.keys())
groups = sorted(groups)
partialGroupStr = ""
groupsWithSpaces = []
# Make sure desired group(s) exist when allowing group to be specified
for desiredGroup in desiredGroups:
if desiredGroup not in groups:
#!print("! {} is not a valid group.".format(desiredGroup))
# word might be part of a group name with a space in it
if len(partialGroupStr) == 0:
partialGroupStr = desiredGroup
else:
partialGroupStr = partialGroupStr + " " + desiredGroup
# Check to see if the string is now a valid group
if partialGroupStr in groups:
groupsWithSpaces.append(partialGroupStr)
# reset the partialGroup string
partialGroupStr = ""
else:
# When a desiredGroup is valid, reset the partialGroup string
partialGroupStr = ""
# Remove the individual words from the groupsWithSpaces from the list of desiredGroups
desiredGroupList = list(desiredGroups)
for groupWithSpaces in groupsWithSpaces:
wordList = groupWithSpaces.split(" ")
for word in wordList:
desiredGroupList.remove(word)
# Append the words that were just removed as a single string
desiredGroupList.append(groupWithSpaces)
#!print("desiredGroups = {}".format(desiredGroups))
#!print("desiredGroupList = {}".format(desiredGroupList))
#!print("groups = {}".format(groups))
print("", file=self.outFile)
for group in groups:
if desiredGroups == () or group in desiredGroupList:
titles = list(titleTotals[group].keys())
titles = sorted(titles)
# Print group total
if percents == False:
print("{:5.2f} {}".format(groupTotals[group], group), file=self.outFile)
else:
print("{:4.1f}% {}".format(groupTotals[group] / recordedTotal * 100.0, group), file=self.outFile)
# Loop over titles printing totals
for title in titles:
if percents == False:
print("\t{:5.2f} {}".format(titleTotals[group][title], title), file=self.outFile)
else:
print("\t{:4.1f}% {}".format(titleTotals[group][title] / recordedTotal * 100.0, title), file=self.outFile)
if verbose == True:
if lessInfo == False:
# Show date, duration, activity and description by default
lastDate = ""
for e in details[group][title]:
if dateSort == False:
# Use the old, monthly-report approach
line = "\t\t{} ; {} ; {} ; {}".format(e.date, e.duration, e.activity, e.description)
print(textwrap.fill(line, width=(self.terminalWidth-14), subsequent_indent="\t\t"), file=self.outFile)
print("", file=self.outFile)
else:
# Indent based on date
if lastDate != e.date:
print("\t\t{}".format(e.date), file=self.outFile)
lastDate = e.date
# Include index instead of date
line = "\t\t\t{} ; {} ; {} ; {}".format(e.index, e.duration, e.activity, e.description)
print(textwrap.fill(line, width=(self.terminalWidth-21), subsequent_indent="\t\t\t"), file=self.outFile)
print("", file=self.outFile)
else:
# Show only the description
for e in details[group][title]:
#
line = "\t\t* {}".format(e.description)
print(textwrap.fill(line, width=(self.terminalWidth-14), subsequent_indent="\t\t"), file=self.outFile)
print("", file=self.outFile)
print("", file=self.outFile)
if desiredGroups == ():
# Print total hours, theoretical hours, and percent
print("Recorded: {} hrs".format(recordedTotal), file=self.outFile)
print("Possible: {} hrs".format(theoreticalHours), file=self.outFile)
print("Complete: {:0.1f}%".format(percent), file=self.outFile)
print("", file=self.outFile)
def startCapture(self, *args):
'''
Called when "sc" is typed
args is a path to the capture file
'''
#!print("startCapture(", args, ")")
if len(args) != 1:
print("! exactly one capture file is required")
else:
desiredCaptureFile = args[0]
if self.captureFileHandle != None:
print("! {} is already open".format(self.captureFile))
else:
if os.path.isdir(args[0]):
print("! {} is a directory".format(self.captureFile))
else:
self.captureFile = desiredCaptureFile
self.captureFileHandle = open(self.captureFile, "a")
self.outFile = self.captureFileHandle
print("Capturing output in {}".format(self.captureFile))
return True
def endCapture(self, *args):
'''
Called when "ec" is typed
no args required
'''
if self.captureFileHandle != None:
print("Closing {}".format(self.captureFile))
self.captureFileHandle.close()
self.captureFileHandle = None
self.captureFile = None
self.outFile = sys.stdout
return True
def displayLog(self, *args):
'''
Called when "print" or "p" is typed.
args is a tuple of index strings (numbers starting from 1). If no indices are specified, the whole log is displayed.
'''
#!print("displayLog(", args, ")")
if len(args) == 0:
# Display the entire log
self.logObj.printLog()
else:
# Display a specific item or specific items
print("")
for x in args:
try:
index = int(x)
if self.logObj.isValidIndex(index):
tempObj = self.logObj.getEntry(index-1)
tempObj.printEntry()
else:
print("! {} is outside the valid index range.".format(x))
except ValueError:
print("! {} is not a valid index (integer).".format(x))
print("")
continue
print("")
return True
def displayDay(self, *args):
'''
Called when "day" or "d" is typed.
args is a tuple of day strings. If no days are specified, the current day is displayed.
'''
#!print("displayDay(", args, ")")
if len(args) == 0:
if self.customDate == None:
dArgs = (time.strftime("%d"),)
else:
dArgs = (self.customDate[-2:],)
else:
dArgs = args
print("")
for x in dArgs:
try:
day = "{:02d}".format(int(x))
dayArray, dayHours, percentRecorded = self.logObj.getDay(day)
print("selected day: {}".format(x))
print("")
for x in dayArray:
# Should probably use the get() methods, but that adds overhead
if self.showPayCodes == False:
print("{} ; {} ; {} - {} ; {} ; {}".format(x.index, x.duration, x.group, x.title, x.activity, x.description))
else:
print("{} ; {:4s} ; {} ; {} - {} ; {} ; {}".format(x.index, x.payCode, x.duration, x.group, x.title, x.activity, x.description))
print("")
print("Hours: {:.2f}".format(dayHours))
print("Percent: {:.1f}%".format(percentRecorded))
print("")
except ValueError:
print("! {} is not a valid day (integer).".format(x))
print("")
continue
return True
def displayWeekReport(self, *args):
'''
Called when "wr" is typed.
'''
#!print("dayTest(", args, ")")
wArgs = self._handleWeekArgs(args)
if wArgs == -1:
print("Error: Days must be integers")
return True
print()
print("Selected days: {}".format(" ".join(wArgs)))
analysis = self.logObj.getAnalysis(wArgs)
#!print(analysis)
if analysis != None:
if self.wrDateSort == False:
self._displayAnalysis(analysis, verbose=True, percents=False, dateSort=False)
else:
self._displayAnalysis(analysis, verbose=True, percents=False, dateSort=True)
else:
print("! No entries for selected day(s).")
return True
def displayWeekNotes(self, *args):
'''
Called when "wn" is typed.
'''
#!print("dayTest(", args, ")")
wArgs = self._handleWeekArgs(args)
if wArgs == -1:
print("Error: Days must be integers")
return True
print()
print("Selected days: {}".format(" ".join(wArgs)))
analysis = self.logObj.getAnalysis(wArgs)
#!print(analysis)
if analysis != None:
self._displayAnalysis(analysis, verbose=True, percents=False, lessInfo=True)
else:
print("! No entries for selected day(s).")
return True
def displayWeekSummary(self, *args):
'''
Called when "ws" is typed.
'''
#!print("dayTest(", args, ")")
wArgs = self._handleWeekArgs(args)
if wArgs == -1:
print("Error: Days must be integers")
return True
print()
print("Selected days: {}".format(" ".join(wArgs)))
analysis = self.logObj.getAnalysis(wArgs)
#!print(analysis)
if analysis != None:
self._displayAnalysis(analysis, verbose=False, percents=False, dateSort=False)
else:
print("! No entries for selected day(s).")
return True
def displayPayCodeReport(self, *args):
'''
Method to display the pay code report
args is a tuple of pay codes
'''
#!print("displayPayCodeReport(", args, ")")
pcArgs = self._handlePayCodeArgs(args)
#!print(pcArgs)
pcTotals = self.logObj.getPayCodeTotals(pcArgs)
#!print(pcTotals)
print()
for pc in pcTotals.keys():
print("{}: {:.2f}".format(pc, pcTotals[pc]['total']))
print()
for d in pcTotals[pc]['days'].keys():
print(" {}: {:.2f}".format(d, pcTotals[pc]['days'][d]['total']))
print()
return True
def _handlePayCodeArgs(self, args):
'''
Internal routine to handle pay code args for displayPayCode* methods
'''
pcArgs = []
if len(args) > 0:
for arg in args:
if arg in config.possible_payCodes:
pcArgs.append(arg)
else:
print("! {} is not a valid pay code".format(arg))
return pcArgs[:]
def displayDaySummary(self, *args):
'''
Called when "dsum" or "ds" is typed.
args is a tuple of day strings. If no days are specified, the current day is displayed.
'''
#!print("displayDaySummary(", args, ")")
if len(args) == 0:
if self.customDate == None:
dArgs = (time.strftime("%d"),)
else:
dArgs = (self.customDate[-2:],)
else:
dArgs = args
print("")
for x in dArgs:
try:
day = "{:02d}".format(int(x))
groups, totals, entries, dayHours, percentRecorded = self.logObj.getDaySummary(day)
print("selected day: {}".format(x))
for group in groups:
print("")
print("{}: {} hours".format(group, totals[group]))
print("")
for x in entries[group]:
# Should probably use the get() methods, but that adds overhead
if self.showPayCodes == False:
line = " {} ; {} ; {} - {} ; {} ; {}".format(x.index, x.duration, x.group, x.title, x.activity, x.description)
else:
line = " {} ; {:4s} ; {} ; {} - {} ; {} ; {}".format(x.index, x.payCode, x.duration, x.group, x.title, x.activity, x.description)
print(textwrap.fill(line, width=(self.terminalWidth), subsequent_indent=" "))
print("")
print("Hours: {:.2f}".format(dayHours))
print("Percent: {:.1f}%".format(percentRecorded))
print("")
except ValueError:
print("! {} is not a valid day (integer).".format(x))
print("")
continue
return True
def _getWeek(self, num):
'''
Internal function to return current or previous weeks
'''
weekTimeDelta = datetime.timedelta(7)
dayTimeDelta = datetime.timedelta(1)
# Current date is needed to determine past mondays
currentDate = datetime.date.today()
# 0=monday, so week day == days since last monday
daysSinceMonday = currentDate.weekday()
# Calcate date object for last monday
lastMonday = currentDate - datetime.timedelta(daysSinceMonday)
# num is a negative number and weekTimeDelta is positive, which results in subtracting time
desiredMonday = lastMonday + num * weekTimeDelta
# Generate the list of week days
weekDayList = []
for i in range(5):
day = desiredMonday + i * dayTimeDelta