-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
executable file
·1300 lines (1143 loc) · 44.1 KB
/
main.js
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 node
// the shebang is needed because this is a command line executable
// package.json > bin maps a command to this file
// the os needs the shebang to understand what to do with this file
// require('dotenv').config()
const { authorization } = require('./config/config');
const fetch = require('node-fetch');
const fs = require('fs');
const chalk = require('chalk');
const Table = require('cli-table3');
const time = require('./util/time');
const moment = require('moment');
const highlight = require('cli-highlight').highlight;
const _ = require('lodash');
const argv = require('minimist')(process.argv.slice(2));
const toggl = require('./util/toggl')
// const Conf = require('conf')
// let config = new Conf();
const logger = require('./util/logger')
const config = require('./config/config.json');
async function run() {
// if (Object.keys(argv).length == 1 && argv._ && argv._.length == 0) {
if (argv.h) {
showHelp();
return;
}
const headers = {
"Authorization": authorization
}
let requestOptions = {
method: 'GET',
headers: headers,
};
let reportType = 'details';
if (argv.t) {
switch (argv.t) {
case 'd': //details
reportType = 'details';
break;
case 'w': //weekly
reportType = 'weekly';
break;
case 's': //summary
reportType = 'summary';
}
}
const url = new URL(`${config.reportUrl}${reportType}`)
const params = {
user_agent: '[email protected]',
workspace_id: '1335456' //TODO pass in workspace id
}
let startDate;
let endDate = moment();
if (argv.r) {
let { start, end } = time.convertRange(argv.r)
startDate = start
endDate = end
} else {
if (argv.s) {
startDate = time.convertDate(argv.s)
} else {
startDate = moment().startOf('isoWeek'); //default startDate to monday of current week
}
if (argv.e) {
endDate = time.convertDate(argv.e)
}
}
if (reportType == 'weekly') {
// startDate = moment().startOf('isoWeek');
endDate = startDate.clone().add(6, 'days');
}
params.since = startDate.format('YYYY-MM-DD')
params.until = endDate.format('YYYY-MM-DD');
let workspaceId = '1335456' //default to study
// TODO: interesting te
// HACK: hmm let's do this
// NOTE: athsasan
// FIX: waht si this
// WARNING: hmmm
if (argv.w) {
switch (argv.w) {
case 'c': //candy
workspaceId = 6002441
break;
case 'm': //me
workspaceId = 4858804
break;
case 's': //study
workspaceId = 1335456
break;
default:
workspaceId = 5265641
}
}
params.workspace_id = workspaceId;
let page = 1
params.page = page;
const queryParams = new URLSearchParams(params).toString();
url.search = queryParams;
// console.log('requestOptions', requestOptions)
// console.log('url', url)
const response = await fetch(url, requestOptions)
let data = await response.json();
if (data.error) {
console.log('toggl api error:', data.error)
return;
}
let total_count = data.total_count;
let per_page = data.per_page;
if (total_count > per_page) {
let innerLength = data.data.length;
while (innerLength > 0) {
page++;
params.page = page;
const queryParams = new URLSearchParams(params).toString();
url.search = queryParams;
const response = await fetch(url, requestOptions)
const newdata = await response.json();
innerLength = newdata.data.length;
data.data = data.data.concat(newdata.data);
}
}
if (argv.j) {
let dataString = JSON.stringify(data, null, 4);
console.log(highlight(dataString));
} else {
if (data.data.length == 0) {
let dataString = JSON.stringify(data, null, 4);
console.log(highlight(dataString));
} else {
if (reportType == 'details') {
if (argv.ww) {
data.report = sum(data, startDate, endDate);
data.report = group(data.report, startDate);
} else {
data.clientTotals = getClientTotals(data);
}
}
// console.log('data',data)
let output = await format(data, reportType, startDate, endDate);
console.log(output);
}
}
}
function group(report, startDate) {
// does startDate need to be a global variable?
// add weekly totals to columns
// add weekly percentages to columns
// let dataString = JSON.stringify(data, null, 4);
let grandWeekTotals = report.weekTotals
let grandTotal = report.total
let clientNames = Object.keys(report.clients)
for (let i = 0; i < clientNames.length; i++) {
let clientName = clientNames[i];
let client = report.clients[clientName]
let projectNames = Object.keys(client.projects)
for (let j = 0; j < projectNames.length; j++) {
let projectName = projectNames[j];
let project = client.projects[projectName]
let tagNames = Object.keys(project.tags)
for (let k = 0; k < tagNames.length; k++) {
let tagName = tagNames[k];
let tag = project.tags[tagName]
let { dgt, isDgtGroup } = getDayGroupTotalsAndPercent(startDate, tag.dayTotals, grandWeekTotals, grandTotal);
tag.dayGroupTotals = dgt;
tag.isDayGroupTotalsGroup = isDgtGroup;
}
let { dgt, isDgtGroup } = getDayGroupTotalsAndPercent(startDate, project.dayTotals, grandWeekTotals, grandTotal);
project.dayGroupTotals = dgt;
project.isDayGroupTotalsGroup = isDgtGroup;
}
let { dgt, isDgtGroup } = getDayGroupTotalsAndPercent(startDate, client.dayTotals, grandWeekTotals, grandTotal);
client.dayGroupTotals = dgt;
client.isDayGroupTotalsGroup = isDgtGroup;
}
let { dgt, isDgtGroup } = getDayGroupTotalsAndPercent(startDate, report.dayTotals, grandTotal);
report.dayGroupTotals = dgt;
report.isDayGroupTotalsGroup = isDgtGroup;
logger.verboseLog('report', report);
return report
}
//add a column to sum the results after every column which is a sunday
function getDayGroupTotalsAndPercent(startDate, dayTotals, grandWeekTotals = null, grandTotal = null) {
//isolation - column headers depend on this so if you change this, column headers need to add columns as well zzzz
//start date - start date of report
//grandTotal - the grand grand total - sum of all the time in the report, not just the row total
let dow = startDate.day(); //monday = 1 and so on
let dayGroupTotals = []
let isDayGroupTotalsGroup = [] //true if groupTotal, false if dayTotal
let groupTotal = 0; //set up a runningTotal that resets after every sunday;
let week = 0; //calendar wee
for (let i = 0; i < dayTotals.length - 1; i++) {
let dayTotal = dayTotals[i];
groupTotal += dayTotal;
dayGroupTotals.push(dayTotal)
isDayGroupTotalsGroup.push(false);
if (dow % 7 == 0 || i == dayTotals.length - 2) {
isDayGroupTotalsGroup.push(true);
isDayGroupTotalsGroup.push(null); //todo: code smell null means percentage column ZZZ
let percent = null;
let weekTotal
if (grandWeekTotals) {
weekTotal = grandWeekTotals[week]
percent = weekTotal ? Math.round((groupTotal / weekTotal * 100)) : null
}
dayGroupTotals.push(groupTotal)
dayGroupTotals.push(percent) //add percent column
groupTotal = 0;
week++
}
dow++
}
let weekGrandTotal = dayTotals[dayTotals.length - 1]
dayGroupTotals.push(weekGrandTotal)
let grandPercent = grandTotal ? Math.round((weekGrandTotal / grandTotal * 100)) : null
dayGroupTotals.push(grandPercent)
isDayGroupTotalsGroup.push(true); //todo code smell this total column is different from the other total columns zzz
return {
dgt: dayGroupTotals,
isDgtGroup: isDayGroupTotalsGroup
}
}
function sum(data, startDate, endDate) {
let sortedData = (_.sortBy(data.data, ['client', 'project', 'tags[0]']))
let reportFormat = {
"clients": {
"argus": {
"projects": {
"project1":
{
id: 123,
hex_color: 456,
"tags": {
"tag1": {
"dayTotals": [455, 2, 36, 99999],
"weekTotals": [455, 2, 36, 99999],
"monthTotals": [455, 2, 36, 99999], //kiv may not be used
total: 123
}, //tag total in last column
"tag2": {
"dayTotals": [455, 2, 36, 99999],
"weekTotals": [455, 2, 36, 99999],
"monthTotals": [455, 2, 36, 99999],
total: 123
}, //tag total in last column
},
"dayTotals": [455, 2, 36, 99999],
"weekTotals": [455, 2, 36, 99999],
"monthTotals": [455, 2, 36, 99999],
"total": 123,
},
"project2":
{
id: 123,
hex_color: 456,
"tags": {
"tag1": {
"totals": [455, 2, 36, 99999]
}, //tag total in last column
"tag2": {
"totals": [455, 2, 36, 99999]
}, //tag total in last column
},
"dayTotals": [455, 2, 36, 99999],
"weekTotals": [455, 2, 36, 99999],
"monthTotals": [455, 2, 36, 99999],
"total": 123,
},
},
"dayTotals": [455, 2, 36, 99999],
"weekTotals": [455, 2, 36, 99999],
"monthTotals": [455, 2, 36, 99999],
"total": 123,
},
"calltree": "{...}",
},
"dayTotals": [455, 2, 36, 99999],
"weekTotals": [455, 2, 36, 99999],
"monthTotals": [455, 2, 36, 99999],
"total": 123,
};
//get date range
let start = moment(startDate)
let end = moment(endDate)
let daysInRange = end.diff(start, 'days') + 1
let report
for (i = 0; i < sortedData.length; i++) {
let entry = sortedData[i]
let entryStartDate = entry.start
let client = entry.client ?? null;
let project = entry.project ?? null;
let pid = entry.pid;
let hexColor = entry.project_hex_color;
let tag = entry.tags[0] ?? null;
let dur = entry.dur;
//0 based column number
//need to get col for dayTotal and weekTotal
let col = getColumnNumberOfTimeEntry(entryStartDate, startDate, daysInRange)
//add duration to report
report = addTimeEntryToReport(report, daysInRange, client, project, pid, hexColor, tag, dur, col, startDate);
//add duration to projectTotal
//add duration to clientTotal
}
return report;
}
function addTimeEntryToReport(report, daysInRange, client, project, pid, hexColor, tag, dur, col, startDate) {
//check if client exists
//check if project exists
//check if tag exists
//check if weekTotalsExist
//check
let weeksInRange = Math.ceil(daysInRange / 7); //round up if number if days is eg 10 days
let monthsInRange = Math.ceil(weeksInRange / 4); //assume 1 month = 4 weeks
report = initReportTotals(report, daysInRange, weeksInRange, monthsInRange, client, project, pid, hexColor, tag);
//add to tag
let dayCol = col
let startDayOfWeek = moment(startDate).day();
//eg if first day is saturday, startDayOfWeek is 6
// if col is 0 for saturday, then (col + startDayOfWeek - 1)/7 = 0th element of weekTotal array
//first saturday and sunday belong to the first weektotal
//the following monday ... sunday belong to the second weektotal
let weekCol = Math.floor((col + startDayOfWeek - 1) / 7)
let monthCol = Math.floor(col / 7 / 4) //todo: not useful as well
addTimeEntry(report.clients[client].projects[project].tags[tag], dayCol, weekCol, monthCol, dur);
addTimeEntry(report.clients[client].projects[project], dayCol, weekCol, monthCol, dur);
addTimeEntry(report.clients[client], dayCol, weekCol, monthCol, dur);
addTimeEntry(report, dayCol, weekCol, monthCol, dur);
return report;
}
function addTimeEntry(group, dayCol, weekCol, monthCol, dur) {
// group has the structure
// {
// dayTotals: []
// weekTotals: []
// monthTotals: []
// total
// }
group.dayTotals[dayCol] += dur;
let dayTotals = group.dayTotals
group.dayTotals[dayTotals.length - 1] += dur;
group.weekTotals[weekCol] += dur;
let weekTotals = group.weekTotals
group.weekTotals[weekTotals.length - 1] += dur;
// group.monthTotals[monthCol] += dur;
// let monthTotals = group.monthTotals
// group.monthTotals[monthTotals.length - 1] += dur;
group.total += dur;
}
function initReportTotals(report, daysInRange, weeksInRange, monthsInRange, client, project, pid, hexColor, tag) {
if (!report) {
report = {
clients: {},
dayTotals: Array(daysInRange + 1).fill(0), //add 1 to add the last column which will store the rowTotal
weekTotals: Array(weeksInRange + 1).fill(0), //add 1 to add the last column which will store the rowTotal
monthTotals: Array(monthsInRange + 1).fill(0), //add 1 to add the last column which will store the rowTotal
total: 0,
};
}
//if client not found, initialize the client object
if (!report.clients[client]) {
report.clients[client] = {
projects: {},
dayTotals: Array(daysInRange + 1).fill(0), //add 1 to add the last column which will store the rowTotal
weekTotals: Array(weeksInRange + 1).fill(0), //add 1 to add the last column which will store the rowTotal
monthTotals: Array(monthsInRange + 1).fill(0),//add 1 to add the last column which will store the rowTotal
total: 0,
};
}
//if client project not found, initialize it
if (!report.clients[client].projects[project]) {
report.clients[client].projects[project] = {
id: pid,
hexColor: hexColor,
tags: {},
dayTotals: Array(daysInRange + 1).fill(0), //add 1 to add the last column which will store the rowTotal
weekTotals: Array(weeksInRange + 1).fill(0), //add 1 to add the last column which will store the rowTotal
monthTotals: Array(monthsInRange + 1).fill(0),//add 1 to add the last column which will store the rowTotal
total: 0,
};
}
//if client project tag not found, initialize it
if (!report.clients[client].projects[project].tags[tag]) {
report.clients[client].projects[project].tags[tag] = {
dayTotals: Array(daysInRange + 1).fill(0), //add 1 to add the last column which will store the rowTotal
weekTotals: Array(weeksInRange + 1).fill(0), //add 1 to add the last column which will store the rowTotal
monthTotals: Array(monthsInRange + 1).fill(0), //add 1 to add the last column which will store the rowTotal
total: 0,
}
}
return report
}
function getColumnNumberOfTimeEntry(entryStartDate, startDate, daysInRange) {
let entryStart = moment(entryStartDate).startOf('day'); //remove time portion so that momentjs doesn't round the diff
let col = entryStart.diff(startDate, 'days'); //0 based if entryStart and startDate are the same, return 0
return col;
}
function getClientTotals(data) {
let sortedData = (_.sortBy(data.data, ['client']))
let clientTotals = {};
let clientTotal = 0
let isFirstClientRow;
for (i = 0; i < sortedData.length; i++) {
let row = sortedData[i];
let client = row.client
let dur = row.dur
let previousRow
if (i < sortedData.length - 1) {
nextRow = sortedData[i + 1]
}
if (i == 0) {
isFirstClientRow = true;
clientTotals[client] = dur;
} else {
let previousClient = sortedData[i - 1].client ?? 'Without client'
if (client == previousClient) {
isFirstClientRow = false;
clientTotals[client] += dur;
} else {
isFirstClientRow = true;
clientTotals[client] = dur;
}
}
}
return clientTotals
}
async function format(data, reportType, startDate, endDate) {
switch (reportType) {
case 'details': {
let table
if (argv.dd) { //chronological order
//assume data sorted by date descending
table = new Table({
head: ['day', 'start', 'end', 'client', 'project', 'h', 'm', 'description', 'tags'],
colAligns: ['', 'right', '', '', '', 'right', 'right'],
style: { head: ['green'], 'padding-left': 0, 'padding-right': 0, compact: true }
})
} else if (argv.ww) { //weekly order
} else {
table = new Table({
head: ['client', 'project', 'tag', 'h', 'm', 'CT%', 'GT%'],
colAligns: ['', '', '', 'right', 'right', 'right', 'right'],
style: { head: ['green'], 'padding-left': 0, 'padding-right': 0, compact: true }
})
data.data = (_.sortBy(data.data, ['client', 'project', 'tags[0]']))
}
let table1 = new Table({
// head: ['project', 'task', 'h', 'm'],
chars: {
'top': '', 'top-mid': '', 'top-left': '', 'top-right': ''
, 'bottom': '', 'bottom-mid': '', 'bottom-left': '', 'bottom-right': ''
, 'left': '', 'left-mid': '', 'mid': '', 'mid-mid': ''
, 'right': '', 'right-mid': '', 'middle': ' '
},
style: { 'padding-left': 0, 'padding-right': 0 }
})
let startWeek = startDate.isoWeek()
let endWeek = endDate.isoWeek()
let currentYear = new Date().getFullYear()
if (currentYear !== startDate.year() || currentYear !== endDate.year()) {
startYear = startDate.year()
endYear = endDate.year()
let header = `${startYear}${startYear === endYear ? "" : ' - ' + endYear}`;
table1.push(['year:', header]);
}
table1.push(['week:', `${startWeek}${startWeek === endWeek ? "" : '- ' + endWeek}`]);
table1.push(['date:', `${startDate.format('ddd DD MMM')} - ${endDate.format('ddd DD MMM')}`]);
table1.push([chalk.grey('total count:'), chalk.grey(data.total_count)]);
table1.push([chalk.grey('per page:'), chalk.grey(data.per_page)]);
let hourMin = time.toHourMin(data.total_grand);
table1.push([chalk.grey('total time:'), chalk.bold.red(hourMin.hour + 'h ' + hourMin.min + 'm')]);
if (argv.ww) {
//detailed long format
table = printWeeklyLongReport(data.report, startDate, endDate)
} else {//--dd or normal
let isFirstDayRow = true;
let isLastDayRow = false;
let isFirstHourRow = true; // for --dd report, do not print the hour for the next row if the hour is the same as the previous row
let isFirstClientRow = true;
let isLastClientRow = false;
let isFirstProjectRow = true;
let isLastProjectRow = false;
let isFirstTagRow = true;
let isLastTagRow = false;
let dayTotal, clientTotal, projectTotal, tagTotal = 0;
let grandTotal = data.total_grand;
for (i = 0; i < data.data.length; i++) {
let row = data.data[i];
let nextRow;
if (i < data.data.length - 1) {
nextRow = data.data[i + 1];
}
let client = row.client ?? 'Without client';
let project = row.project ?? 'Without project';
let tag = row.tags[0] ?? null;
let description = row.description;
let tags = row.tags;
let dur = row.dur;
let { hour, min } = time.toHourMin(row.dur);
let date = moment(row.start, "YYYYMMDD");
if (i == 0) {
isFirstDayRow = true; //the first row of a time entry with a different day
isFirstClientRow = true;
isFirstProjectRow = true;
isFirstTagRow = true;
dayTotal = dur;
clientTotal = dur;
projectTotal = dur;
tagTotal = dur;
} else {
//do not repeat projectNames if there are many rows with the same project name
let previousRow = data.data[i - 1];
let previousRowDate = moment(previousRow.start, "YYYYMMDD");
// let currentRowStartHour = moment(row.start,"HH").valueOf();
let currentRowStartHour = moment(row.start).format("HH")
let previousRowStartHour = moment(previousRow.start).format("HH")
if (currentRowStartHour == previousRowStartHour) {
isFirstHourRow = false;
} else {
isFirstHourRow = true;
}
if (date.valueOf() == previousRowDate.valueOf()) {
isFirstDayRow = false;
dayTotal += dur;
} else {
isFirstDayRow = true;
dayTotal = dur;
}
let previousClient = previousRow.client ?? 'Without client'
if (client == previousClient) {
isFirstClientRow = false;
clientTotal += dur;
// let {hour,min} = time.toHourMin(dur)
} else {
isFirstClientRow = true;
clientTotal = dur;
// let {hour,min} = time.toHourMin(dur)
}
let previousProject = previousRow.project ?? 'Without project'
if (project == previousProject) {
isFirstProjectRow = false;
projectTotal += dur;
} else {
isFirstProjectRow = true;
projectTotal = dur;
}
let previousTag = previousRow.tags[0] ?? null;
if (tag == previousTag && project == previousProject) {
isFirstTagRow = false;
tagTotal += dur;
let { hour, min } = time.toHourMin(tagTotal)
} else {
isFirstTagRow = true;
tagTotal = dur;
let { hour, min } = time.toHourMin(tagTotal)
}
}
let nextRowDay, nextRowClient, nextRowProject, nextRowTag;
if (i < data.data.length - 1) {
nextRowDay = moment(nextRow.start, "YYYYMMDD");
nextRowClient = nextRow.client ?? 'Without client'
nextRowProject = nextRow.project ?? 'Without project'
nextRowTag = nextRow.tags[0] ?? null;
isLastDayRow = nextRowDay.valueOf() != date.valueOf() ? true : false;
isLastClientRow = nextRowClient != client ? true : false;
isLastProjectRow = nextRowProject != project ? true : false;
//if next entry is not from the same project
//or if next entry is not from the same client
//or if next entry has a different tag,
//or we are at the last row of data,
// then isLastTagRow is true!
isLastTagRow = (nextRowTag != tag || isLastClientRow || isLastProjectRow) ? true : false;
} else { //if i is == the last row
isLastDayRow = true;
isLastClientRow = true;
isLastProjectRow = true;
isLastTagRow = true;
}
if (argv.dd) {
let end = row.end ? moment(row.end).format('HHmm') : '';
if (isFirstClientRow) {
} else {
client = '';
}
if (isFirstProjectRow) {
} else {
project = '';
}
if (isFirstDayRow) {
date = moment(date).format("ddd DD MMM")
} else {
date = '';
}
let start
if (isFirstHourRow) {
start = moment(row.start).format('HHmm')
} else {
start = moment(row.start).format('mm')
}
let hex_color = row.project_hex_color;
project = chalk.hex(`${hex_color}`)(project);
description = chalk.hex(`${hex_color}`)(description);
let { hour, min } = time.toHourMin(row.dur);
if (hour == 0) {
hour = chalk.hex('#6d6d6d')(hour)
}
if (min < 10) {
min = '0' + min;
}
min = chalk.hex('#6d6d6d')(min);
if (isFirstDayRow) {
table.push([date])
}
table.push(['', start, end, client, project, hour, min, description, tags.toString()])
if (isLastDayRow || i == data.data.length - 1) { //or last row of report
let { hour, min } = time.toHourMin(dayTotal);
table.push(['', '', '', '', chalk.cyan('Day Total:'), chalk.bold.cyan(hour), chalk.cyan(min)])
}
} else {
// if not --dd
if (isFirstClientRow) {
table.push([client])
}
let hex_color = row.project_hex_color;
if (project == 'Without project') {
hex_color = '#ffffff'
}
if (isFirstProjectRow) {
// if (project == 'Without project') {
// //without project is grey and hard to read in the terminal, do not colour it
// } else {
project = chalk.hex(`${hex_color}`)(project);
// }
table.push(['', project,])
}
if (isLastTagRow) {
// head: ['client', 'project', 'tag', 'start', 'end', 'h', 'm', 'description', 'tags'],
let { hour, min } = time.toHourMin(tagTotal);
if (hour == 0) {
hour = chalk.hex('#6d6d6d')(hour)
} else {
hour = chalk.hex(`${hex_color}`)(hour)
}
if (min < 10) {
min = '0' + min;
}
tag = chalk.hex(`${hex_color}`)(tag);
let clientTotal = data.clientTotals[client]
if (client == 'Without client') {
clientTotal = data.clientTotals['null']
}
let tagClientPercent = Math.round((tagTotal / clientTotal) * 100)
tagClientPercent = chalk.grey(tagClientPercent + '%')
let tagGrandTotalPercent = Math.round((tagTotal / grandTotal) * 100)
if (tagGrandTotalPercent < 10) {
tagGrandTotalPercent = chalk.grey(tagGrandTotalPercent + '%')
} else {
tagGrandTotalPercent = chalk.bold.cyan(tagGrandTotalPercent + '%')
}
table.push(['', '', {
hAlign: 'right',
content: tag
}, hour, chalk.grey(min), tagClientPercent, tagGrandTotalPercent])
}
if (isLastClientRow) {
let { hour, min } = time.toHourMin(clientTotal);
if (hour == 0) {
hour = chalk.hex('#6d6d6d')(hour)
}
if (min < 10) {
min = '0' + min;
}
table.push(['', '', chalk.bold('Client Total:'), chalk.bold(hour), chalk.grey(min), chalk.bold(Math.round((clientTotal / grandTotal) * 100) + '%')])
}
}
}
let { hour, min } = time.toHourMin(data.total_grand);
if (argv.dd) {
table.push(['', '', '', '', chalk.bold.cyan('Grand Total:'), chalk.bold.cyan(hour), {
hAlign: 'right',
content: chalk.bold.cyan(min)
}])
} else {
table.push(['', '', chalk.bold.cyan('Grand Total:'), chalk.bold.cyan(hour), {
hAlign: 'right',
content: chalk.bold.cyan(min)
}])
}
}
return table1.toString() + '\n' + table.toString();
}
break
case 'weekly': {
let startWeek = startDate.isoWeek()
let endWeek = endDate.isoWeek()
let headerString = `week: ${startWeek}${startWeek === endWeek ? "" : '- ' + endWeek}` + '\n';
headerString += `${chalk.grey('date:')} ${startDate.format('ddd DDMMM')} - ${endDate.format('ddd DDMMM')}`;
let grandTotal = data.total_grand;
let table = new Table({
// head: ['project', 'task', 'h', 'm'],
colAligns: ['', '', '', '', '', '', '', '', '', 'right', 'right'],
style: { head: ['green'], 'padding-left': 0, 'padding-right': 0, compact: true }
})
let weekStartDay = startDate;
let day1 = weekStartDay.format('ddDD');
let day2 = weekStartDay.add(1, 'day').format('ddDD');
let day3 = weekStartDay.add(1, 'day').format('ddDD');
let day4 = weekStartDay.add(1, 'day').format('ddDD');
let day5 = weekStartDay.add(1, 'day').format('ddDD');
let day6 = weekStartDay.add(1, 'day').format('ddDD');
let day7 = weekStartDay.add(1, 'day').format('ddDD');
let { hour, min } = time.toHourMin(grandTotal);
if (min < 10) {
min = '0' + min;
}
// table.push([chalk.dim('grand total: ') + chalk.bold(`${hour}:${min}`)]);
table.push(['', chalk.grey('title'), chalk.grey(day1), chalk.grey(day2), chalk.grey(day3), chalk.grey(day4), chalk.grey(day5), chalk.grey(day6), chalk.grey(day7), chalk.grey('total'), chalk.grey('%')])
let sortedData = (_.sortBy(data.data, ['title.client', 'title.project']))
let isFirstClientRow = true;
let isLastClientRow;
let clientTotal = Array(8).fill(0);
for (let i = 0; i < sortedData.length; i++) {
let proj = sortedData[i];
let client = proj.title.client ?? 'Without client'
let projectName = proj.title.project ?? 'Without project'
let hex_color = proj.title.hex_color;
if (i == 0) {
isFirstClientRow = true;
} else {
//do not repeat projectNames if there are many rows with the same project name
let previousClient = sortedData[i - 1].title.client ?? 'Without client'
if (client == previousClient) {
isFirstClientRow = false;
} else {
isFirstClientRow = true;
clientTotal = Array(8).fill(0);
}
}
if (i < sortedData.length - 1) {
let nextClient = sortedData[i + 1].title.client ?? 'Without client'
if (nextClient != client) {
isLastClientRow = true;
} else {
isLastClientRow = false;
}
}
let projTotals = proj.totals.slice(); //copy array
for (let i = 0; i < proj.totals.length; i++) {
// let timeTotals = proj.totals.map((ms) => {
let ms = proj.totals[i]
if (ms) {
let { hour, min } = time.toHourMin(ms);
if (hour == 0) {
hour = chalk.hex('#6d6d6d')(hour)
}
if (min < 10) {
min = '0' + min;
}
// min = chalk.hex('#FEF9F8')(min);
min = chalk.hex('#6d6d6d')(min);
projTotals[i] = `${hour}:${min}`
if (isFirstClientRow) {
clientTotal[i] = proj.totals[i]
} else {
clientTotal[i] += proj.totals[i]
}
} else {
projTotals[i] = chalk.grey('-');
}
if (i == proj.totals.length - 1) {
let percent = Math.round(ms / grandTotal * 100)
percent = prettifyPercent(percent, hex_color, true)
projTotals.push(percent)
}
}
if (!hex_color) {
hex_color = '#6d6d6d'
}
if (isFirstClientRow) {
table.push([chalk.hex(`${hex_color}`)(client)])
}
table.push(['', {
hAlign: 'right',
content: chalk.hex(`${hex_color}`)(projectName)
}, projTotals[0], projTotals[1], projTotals[2], projTotals[3], projTotals[4], projTotals[5], projTotals[6], projTotals[7], projTotals[8]])
if (isLastClientRow) {
clientTotalOut = clientTotal.map((ms) => {
if (ms) {
let { hour, min } = time.toHourMin(ms);
if (hour == 0) {
hour = chalk.grey(hour)
} else {
hour = chalk.bold(hour)
}
if (min < 10) {
min = '0' + min;
}
// min = chalk.hex('#FEF9F8')(min);
return `${hour}:${chalk.grey(min)}`
} else {
return chalk.grey('-');
}
})
let clientGrandTotal = clientTotal[7]
let percent = Math.round(clientGrandTotal / grandTotal * 100)
percent = prettifyPercent(percent, '', false, true)
clientTotalOut.push(percent)
table.push(['', chalk.bold('Subtotal:'), clientTotalOut[0], clientTotalOut[1], clientTotalOut[2], clientTotalOut[3], clientTotalOut[4], clientTotalOut[5], clientTotalOut[6], clientTotalOut[7], clientTotalOut[8]])
}
}//for
// )
let timeTotals = data.week_totals.map((total) => {
if (total) {
let { hour, min } = time.toHourMin(total);
if (hour == 0) {
hour = chalk.grey(hour)
} else {
hour = chalk.cyan(hour)
}
if (min < 10) {
min = '0' + min;
} else {
}
min = chalk.hex('#6d6d6d')(min)
return `${hour}:${min}`;
}
return chalk.grey('-');
})
table.push(['', {
hAlign: 'right',
content: chalk.bold.cyan('TOTAL:')
}, timeTotals[0], timeTotals[1], timeTotals[2], timeTotals[3], timeTotals[4], timeTotals[5], timeTotals[6], timeTotals[7]])
return headerString + '\n' + table.toString();
}
break
case 'summary': {
//lolo why am i summing this, i can just post a summary group by clients, sub group by projects ...
let startWeek = startDate.isoWeek()
let endWeek = endDate.isoWeek()
let startYear = startDate.year()
let currentYear = new Date().getFullYear();
let header = "";
if (currentYear !== startDate.year() || currentYear !== endDate.year()) {
startYear = startDate.year()
endYear = endDate.year()
header += `Year: ${startYear}${startYear === endYear ? "" : ' - ' + endYear}\n`;
}
header += `Week: ${startWeek}${startWeek === endWeek ? "" : ' - ' + endWeek}\n`;
header += `${chalk.grey('date:')} ${startDate.format('ddd DD MMM')} - ${endDate.format('ddd DD MMM')}\n`;
let head, colAligns
if (argv.d) {
head = ['client', 'project', 'h', 'm', '%', 'task']
colAligns = ['', 'right', 'right', 'right', 'right']
} else {
head = ['client', 'project', 'h', 'm', '%']
colAligns = ['', 'right', 'right', 'right', '']
}
let table = new Table({
head: head,
colAligns: colAligns,
style: { head: ['green'], 'padding-left': 0, 'padding-right': 0, compact: true }
})
let { hour, min } = time.toHourMin(data.total_grand);
let grandTotal = data.total_grand
let sortedData = (_.sortBy(data.data, ['title.client', 'title.project']))
let clientTotal = 0;//calculate a running total for each client
let isFirstClientRow = true;
let isLastClientRow;
for (i = 0; i < sortedData.length; i++) {
let proj = sortedData[i];
let id = proj.id ?? '-'
let client = proj.title.client ?? 'Without client'
let projectName = proj.title.project ?? 'Without project'
if (i == 0) {
isFirstClientRow = true;
clientTotal += proj.time
} else {
//do not repeat projectNames if there are many rows with the same project name
let previousClient = sortedData[i - 1].title.client ?? 'Without client'
if (client == previousClient) {
isFirstClientRow = false;
clientTotal += proj.time
} else {
isFirstClientRow = true;
clientTotal = proj.time
}
}