-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathworklogger.user.js
1801 lines (1620 loc) · 67.7 KB
/
worklogger.user.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
// ==UserScript==
// @name p4u-worklogger
// @description JIRA work log in UU
// @version 2.10.1
// @namespace https://uuos9.plus4u.net/
// @homepage https://github.com/bubblefoil/p4u-worklogger
// @author bubblefoil
// @license MIT
// @require https://code.jquery.com/jquery-3.2.1.min.js
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_addStyle
// @connect jira.unicorn.com
// @match https://uuos9.plus4u.net/uu-specialistwtmg01-main/*
// @match https://uuapp.plus4u.net/uu-specialistwtm-maing01/*
// @run-at document-idle
// ==/UserScript==
//Test issue - FBLI-7870
const jiraComUrl = 'https://jira.unicorn.com';
const jiraRestApiPath = 'rest/api/2';
const jiraIssueKeyPattern = /([A-Z]+-\d+)/;
const jiraIssueProjectPattern = /([A-Z]+)-\d+/;
class PageCheck {
static isWorkLogFormPage() {
//Check that the work log page is loaded by querying for some expected elements
if (document.title !== 'Working Time Management') {
console.log("Judging by the page title, this does not seem to be the Working Time Management app. Exiting extension script.");
return false;
}
return true;
}
}
if (!PageCheck.isWorkLogFormPage()) {
// noinspection JSAnnotator
return;
} else {
// language=CSS
// noinspection JSUnresolvedFunction
GM_addStyle(`
/* Widen the month selection button envelope by overriding its fixed width. */
.uu-specialistwtm-worker-monthly-detail-top-change-month-dropdown {
min-width: 330px;
}
/* Copied from .uu-specialistwtm-worker-monthly-detail-top-back-icon without its padding */
.wtm-month-switch-button-icon {
color: #616161;
font-size: 20px;
height: fit-content;
}
`);
// Polyfill some syntactic sugar
Promise.of = Promise.resolve;
}
const jiraIssueLoaderAnimation = `
<style>
.progress-spinner {
width: 16px;
height: 16px;
-webkit-animation: spin 2s linear infinite; /* Safari */
animation: spin 1.5s linear infinite;
}
/* Safari */
@-webkit-keyframes spin {
0% {
-webkit-transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
}
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
<svg class="progress-spinner" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 75.76 75.76">
<defs>
<style>.cls-2 { fill: #2684ff; } .cls-3 { fill: url(#linear-gradient); } .cls-4 { fill: url(#linear-gradient-2); }</style>
<linearGradient id="linear-gradient" x1="34.64" y1="15.35" x2="19" y2="30.99" gradientUnits="userSpaceOnUse"><stop offset="0.18" stop-color="#0052cc"/><stop offset="1" stop-color="#2684ff"/></linearGradient>
<linearGradient id="linear-gradient-2" x1="38.78" y1="60.28" x2="54.39" y2="44.67" xlink:href="#linear-gradient"/>
</defs>
<title>Connecting to Jira...</title>
<g id="Layer_2">
<g id="Blue">
<path class="cls-2" d="M72.4,35.76,39.8,3.16,36.64,0h0L12.1,24.54h0L.88,35.76A3,3,0,0,0,.88,40L23.3,62.42,36.64,75.76,61.18,51.22l.38-.38L72.4,40A3,3,0,0,0,72.4,35.76ZM36.64,49.08l-11.2-11.2,11.2-11.2,11.2,11.2Z"/>
<path class="cls-3" d="M36.64,26.68A18.86,18.86,0,0,1,36.56.09L12.05,24.59,25.39,37.93,36.64,26.68Z"/>
<path class="cls-4" d="M47.87,37.85,36.64,49.08a18.86,18.86,0,0,1,0,26.68h0L61.21,51.19Z"/>
</g>
</g>
</svg>
`;
/**
* Branches off the flow into a supplied function, typically to perform side-effects.
* Returns the input value.
*
* @param {function(*): *} f The dead-end functions, may be impure.
* @return {function(*): (Promise<*> | Promise<void>)} Resolved Promise of the original input
*/
const tee = (f) => (x) => {
f(x);
return Promise.of(x);
};
/**
* Returns wrapped fn which, when called, delegates the call to fn
* if and only if pred returns true at the time of invocation.
* Wrapping function passes args to Both pred and fn.
*
* @param pred {Function} predicate
* @param fn {Function} function to be called conditionally if pred(...args) == true
* @return {Function}
*/
function when(pred, fn) {
return function conditionalFn(...args) {
if (pred(...args)) {
return fn(...args);
}
}
}
/**
* Returns a function that dispatches calls to one of given functions, based on the first matching predicate.
* Takes pairs of predicate, function (alternating), tests predicates one by one
* and when a predicate returns true (strict match), calls following function and returns its result.
* Each predicate and fn gets arguments passed to the returned dispatching function.
*
* Basically a functional if-else.
*
* @param pred {Function} Predicate
* @param fn {Function} Function to call if pred matches.
* @param more More pred/fn pairs.
* @return {function(...[*]=)} Dispatching function
*/
function condp(pred, fn, ...more) {
if (more.length % 2 !== 0) {
throw new Error('Invalid number of functions. Expected even number of functions, predicate/function pairs.')
}
const nonFn = [pred, fn, ...more].find(f => typeof f !== "function");
if (nonFn) {
throw new TypeError('Invalid argument. Expected even number of functions, predicate/function pairs, but got this: ' + nonFn);
}
return function predMatchingFn(...args) {
const fns = [pred, fn, ...more];
for (let i = 0; i < fns.length; i += 2) {
if (fns[i](...args)) {
return fns[i + 1](...args);
}
}
};
}
/**
* Returns pred giving negated result.
*/
function not(pred) {
return function notPred(...args) {
return !pred(...args);
}
}
/**
* Returns pred giving positive result if all given preds return true.
*/
function and(...preds) {
return function everyPred(...args) {
return preds.every(p => {
if (typeof p !== "function") {
throw new TypeError('All arguments of function [and] must be functions, not this thing:' + p);
}
return p(...args);
});
};
}
/**
* Pure form of attribute assignment.
* Adds an attribute to an object and returns the updated object.
*
* @param o Target object
* @param k Attribute name
* @param v Attribute value
* @return {Object} o with o.k = v
*/
const assoc = (o, k, v) => {
o[k] = v;
return o;
};
/**
* Enhances the work log table.
*/
class LogTableDecorator {
/**
* Finds the JIRA issue references in the work descriptions in the work log table
* and replaces them with links.
*/
static findAndLinkifyJiraIssues() {
const logTableNodes = document.querySelectorAll('#table-tsitems td.htsItemStyle div.hts_object');
const hasTextNodes = (p) => Array.from(p.childNodes).find(n => n.nodeType === 3);
Array.from(logTableNodes)
.filter(hasTextNodes)
.forEach(node => this.replaceIssueByLink(node));
}
static replaceIssueByLink(element) {
const issueKeyPatternGlobal = new RegExp(jiraIssueKeyPattern, "g");
element.innerHTML = element.innerHTML
.replace(issueKeyPatternGlobal, `<a href="${jiraComUrl + '/browse'}/$1" target="_blank">$1</a>`);
}
}
const wtmMessage = {
cs: {
'wtm.table.day-range.label': 'ČAS MEZI DNY:',
'wtm.month.prev.title': 'Předchozí měsíc',
'wtm.month.next.title': 'Následující měsíc',
},
en: {
'wtm.table.day-range.label': 'TIME BETWEEN DAYS:',
'wtm.month.prev.title': 'Previous month',
'wtm.month.next.title': 'Next month',
}
};
const _t = function (messageCode) {
if (!messageCode) {
console.warn('Invalid I18N message code: ', messageCode);
return '?';
}
const getBundle = function () {
const language = WtmWorktableModel.language();
if (wtmMessage.hasOwnProperty(language)) {
return wtmMessage[language];
}
return wtmMessage.cs
};
const bundle = getBundle();
if (!bundle.hasOwnProperty(messageCode)) {
console.warn(`)I18N message "${messageCode}" is not defined for "${WtmWorktableModel.language()}`);
return messageCode;
}
return bundle[messageCode];
};
class WtmDateTime {
/**
* Returns parsed date as an array of fields: [day, month, year]. Months are counted from 1.
* @param {string} selectedDate
* @return {number[]}
*/
static parseDate(selectedDate) {
const dateParts = selectedDate.split(/[.\/]/);
const dateFields = dateParts.length === 3 && dateParts.map(Number) || [NaN, NaN, NaN];
if (WtmWorktableModel.language() === 'cs') {
return dateFields;
} else {
const [month, day, year] = dateFields;
return [day, month, year];
}
}
static parseDateTime(selectedDate, selectedTime) {
const [day, month, year] = this.parseDate(selectedDate);
const [hour, minute] = selectedTime.split(':').map(Number);
return new Date(year, month - 1, day, hour, minute, 0, 0);
}
static padToDoubleDigit(num) {
const norm = Math.floor(Math.abs(num));
return (norm < 10 ? '0' : '') + norm;
}
static addHours(d, h) {
return this.addMinutes(d, h * 60);
}
static addMinutes(d, m) {
return new Date(d.getTime() + (m * 60 * 1000))
}
}
/**
* Access methods to the WTM time table view.
*/
class WtmWorktableModel {
static language() {
return document.getElementsByClassName("uu5-bricks-language-selector-code-text")[0].textContent;
}
static newItemButton() {
return document.querySelector('button.uu-specialistwtm-create-timesheet-item-button');
}
static monthlyDetailTopTimeColumn() {
return document.querySelector('.uu5-common-div .uu-specialistwtm-worker-monthly-detail-top-time-column');
}
static timeTable() {
return document.querySelector('table.uu5-bricks-table-table');
}
/**
* Reads the day of month from a time table row.
* @param {HTMLTableRowElement} tableRow
* @return {number|NaN} Day of month, 0 - 31, or NaN.
*/
static getDay(tableRow) {
const dateCellText = tableRow.cells[1].innerText;
const dateFields = WtmDateTime.parseDate(dateCellText);
return dateFields[0];
}
static isModalDialogOpened() {
const modal = document.querySelector('div.uu5-bricks-page-modal');
const modalStyle = modal && window.getComputedStyle(modal);
return modalStyle && modalStyle.visibility === 'visible';
}
/**
* Reads logged working time in minutes from a time table row.
* @param {HTMLTableRowElement} tableRow
* @return {number|NaN} Minutes of work, or NaN.
*/
static getTimeInMinutes(tableRow) {
const dateCellText = tableRow.cells[2].innerText;
const match = dateCellText.match(/(\d\d)[:](\d\d)/);
return match && 60 * Number(match[1]) + Number(match[2]) || NaN;
}
/**
* Filters table rows by given range of days of month.
* @param {number} dayFrom
* @param {number} dayTo
* @return {Promise<HTMLTableRowElement[]>}
*/
static rowsBetweenDays(dayFrom, dayTo) {
return new Promise(resolve => {
const timeTable = WtmWorktableModel.timeTable();
const firstDay = Math.min(dayFrom, dayTo);
const lastDay = Math.max(dayFrom, dayTo);
const rowsInRange = [].filter.call(timeTable.rows, (row, idx) => {
return idx > 0 && firstDay <= WtmWorktableModel.getDay(row) && WtmWorktableModel.getDay(row) <= lastDay;
});
resolve(rowsInRange);
})
}
/**
*
* @param dayFrom
* @param dayTo
* @return {Promise<number>} Sum of time in selected day range in minutes.
*/
static minutesBetween(dayFrom, dayTo) {
return this
.rowsBetweenDays(dayFrom, dayTo)
.then((rows) => new Promise(resolve => {
const minutesTotal = rows
.map((row) => WtmWorktableModel.getTimeInMinutes(row))
.reduce((acc, minutes) => acc + minutes, 0);
resolve(minutesTotal);
}));
}
}
/**
* Takes care of Time table extension view.
*/
class WtmWorktableView {
constructor() {
}
static worktableSumViewShow() {
if (document.getElementById('wtt-time-range-form')) {
console.log('WTM Extension: Work table already enhanced.');
WtmWorktableView.updateSum();
return;
}
console.log('WTM Extension: enhancing work table');
const today = new Date();
const dayOfWeek = (today.getDay() + 6) % 7;
const lastMonday = Math.max(today.getDate() - dayOfWeek, 1);
const nextSunday = Math.min(lastMonday + 6, 31);
WtmWorktableModel.monthlyDetailTopTimeColumn()
.insertAdjacentHTML(
'beforeend',
`
<div id="wtt-time-range-form" class="uu-specialistwtm-worker-monthly-detail-top-time-column" style="z-index: 10">
<!--Move the span to front, because this div is covered by some uu component's width % and the content is hard to select by mouse-->
<span class="uu5-bricks-span uu5-bricks-lsi-item uu5-bricks-lsi uu-specialistwtm-worker-monthly-detail-top-total-time-label" style="width: max-content; min-width: 8em;">${_t('wtm.table.day-range.label')}</span>
<input class="uu5-bricks-text uu5-common-text uu-specialistwtm-worker-monthly-detail-table-form-date" type="number" id="wtt-day-from" value="${lastMonday}" min="1" max="31" style="width: 4em; margin: 0.25em">
<input class="uu5-bricks-text uu5-common-text uu-specialistwtm-worker-monthly-detail-table-form-date" type="number" id="wtt-day-to" value="${nextSunday}" min="1" max="31" style="width: 4em; margin: 0.25em">
<span id="wtt-time-in-range-sum" class="uu5-bricks-span uu-specialistwtm-worker-monthly-detail-top-total-time">${WtmWorktableView.formatToHours(0)}</span>
</div>`
);
WtmWorktableView.getDayFromInput().onchange = () => WtmWorktableView.updateSum();
WtmWorktableView.getDayFromInput().onclick = () => WtmWorktableView.updateSum();
WtmWorktableView.getDayToInput().onchange = () => WtmWorktableView.updateSum();
WtmWorktableView.getDayToInput().onclick = () => WtmWorktableView.updateSum();
WtmWorktableView.updateSum().catch((e) => console.warn(e));
}
static getDayToInput() {
return document.getElementById('wtt-day-to');
}
static getDayFromInput() {
return document.getElementById('wtt-day-from');
}
static async updateSum() {
const dFrom = Number(WtmWorktableView.getDayFromInput().value);
const dTo = Number(WtmWorktableView.getDayToInput().value);
document.getElementById('wtt-time-in-range-sum').innerText = '-h';
const minutesInRange = await WtmWorktableModel.minutesBetween(dFrom, dTo);
document.getElementById('wtt-time-in-range-sum').innerText = WtmWorktableView.formatToHours(minutesInRange);
}
static formatToHours(minutes) {
return ` ${Number(Math.round(minutes / 60 * 100) / 100).toLocaleString(WtmWorktableModel.language())}h`;
}
}
class WtmDialog {
static descArea() {
return document.getElementsByTagName("textarea")[0];
}
static _getNamedInput(elementName) {
return document.getElementsByName(elementName)[0]
.lastChild
.firstChild
.firstChild;
}
static datePicker() {
return WtmDialog._getNamedInput("date")
}
static timeFrom() {
return WtmDialog._getNamedInput("timeFrom");
}
static timeTo() {
return WtmDialog._getNamedInput("timeTo");
}
static artifactField() {
return WtmDialog._getNamedInput("subject");
}
static categoryField() {
return WtmDialog._getNamedInput("category");
}
static dateFrom() {
return WtmDateTime.parseDateTime(this.datePicker().value, this.timeFrom().value);
}
static dateTo() {
return WtmDateTime.parseDateTime(this.datePicker().value, this.timeTo().value);
}
static getDurationSeconds() {
const dateFrom = WtmDialog.dateFrom();
const dateTo = WtmDialog.dateTo();
if (isNaN(dateFrom.getTime()) || isNaN(dateTo.getTime())) {
return 0;
}
const durationMillis = dateTo - dateFrom;
return durationMillis > 0 ? durationMillis / 1000 : 0;
}
/** Returns the OK button. It is an <a> element containing a structure of spans. */
static buttonNextItem() {
return WtmDialog.highRateNode().parentElement
.lastChild
.firstChild
.firstChild
.firstChild;
}
/** Returns the 'Next item' button. It is an <a> element containing a structure of spans, or null in case of work log update. */
static buttonOk() {
return WtmDialog.highRateNode().parentElement
.lastChild
.lastChild
.firstChild
.firstChild;
}
static addKeyboardShortcutMnemonics() {
WtmDialog.buttonOk().title = "Ctrl + Enter";
WtmDialog.buttonNextItem().title = "Ctrl + Shift + Enter";
}
/**
*
* @param {HTMLElement} element
* @param {string} key
*/
static addMnemonic(element, key) {
if (element && key && key.length === 1 && element.innerText.indexOf(key) > 0) {
element.innerHTML = element.innerText.replace(key, `<u>${key}</u>`);
element.accessKey = key;
}
}
static highRateNode() {
return document.getElementsByName("highRate")[0];
}
}
/**
* Wrap log functions to make them more functional.
* Cannot be wrapped in a class because FF does not support fields and standard function syntax is horribly bloated.
*/
const log = tee(console.log);
const error = tee(console.error);
const warn = tee(console.warn);
const info = tee(console.info);
const debug = tee(console.debug);
const trace = tee(console.trace);
/**
* Removes leading and trailing slash '/' character.
* @param s
* @return {string}
*/
const stripSlashes = (s) => s
.replace(/^\//, '')
.replace(/\/?$/, '');
const addRequestParameter = (parameter) => (value) => (url) => {
const separator = url.includes('?') ? '&' : '?';
return `${url}${separator}${parameter}=${value}`;
};
/**
* @param {...string|string[]} resource path
* @return {function(*=): Promise<string | Error>}
*/
const getResourceUrl = (...resource) => (domain) => new Promise((resolve, reject) => {
if (domain && typeof domain === 'string') {
resolve(`${stripSlashes(domain)}/${resource.flat().map(stripSlashes).join('/')}`);
} else {
reject(new TypeError('Invalid url domain :' + domain));
}
}
);
/**
* @param {...string} resourcePath path
* @return {function(*=): Promise<string | Error>}
*/
const jiraRestApiResource = (...resourcePath) =>
getResourceUrl([jiraRestApiPath].concat(resourcePath).flat(2));
/**
* @param {...string} issue JIRA issue key
* @return {function(string): Promise<string|Error>} Resource url provider which takes domain as the argument.
*/
const jiraRestApiIssueUrl = (issue) => jiraRestApiResource('issue', issue);
/**
* @param {...string} issue JIRA issue key
* @return {function(string): Promise<string|Error>} Resource url provider which takes domain as the argument.
*/
const jiraBrowseIssueUrl = (issue) => getResourceUrl('browse', issue);
class InvalidResponse {
/**
* @param {HttpResponse} response
*/
constructor(response) {
this._url = response.finalUrl;
this._response = response;
}
get response() {
return this._response;
}
get url() {
return this._url;
}
}
class InvalidProjectError {
constructor(projectKey) {
this._projectKey = projectKey;
}
get projectKey() {
return this._projectKey;
}
}
class ProjectLoadingError {
constructor(projectKey) {
this._projectKey = projectKey;
}
get projectKey() {
return this._projectKey;
}
}
/**
* Constructs a base of an HTTP request for json data and GET method.
*
* @param {string} url
* @return {Request} Pre-filled request object for GM_xmlhttpRequest
*/
const getJsonRequest = (url) => ({
method: 'GET',
headers: {'Accept': 'application/json'},
url: url,
onreadystatechange: function (res) {
console.debug(`Processing request: [${url}], state: ${res.readyState}`);
}
});
/**
* JIRA API connector and utils.
*/
class Jira4U {
constructor() {
}
static tryParseIssue(desc) {
console.log(`Parsing description: ${desc}`);
if (typeof desc !== "string") {
return new WorkDescription();
}
return WorkDescription.parse(desc);
}
/**
* @param {string} issueKey
* @return {Promise<string|TypeError>}
*/
static getProjectCode(issueKey) {
if (typeof issueKey !== 'string' || !jiraIssueProjectPattern.test(issueKey)) {
return Promise.reject(new TypeError(`Invalid argument issueKey: "${issueKey}", expected an issue key`));
}
return Promise.of(issueKey.match(jiraIssueProjectPattern)[1]);
}
/**
* @param {Function} onprogress
* @return {function(Object): Object}
*/
static setOnProgressCallback(onprogress) {
return (request) => Object.assign(request, {onreadystatechange: onprogress});
}
/**
* Triggers the actual http request.
*
* @typedef HttpResponse
* @property {number} status
* @property {string} responseText
* @property {string} responseHeaders
* @property {string} finalUrl
*
* @param {Request} requestParams
* @return {Promise<HttpResponse>} A Promise which resolves with the http response.
*/
static request(requestParams) {
return new Promise((resolve, reject) => {
// noinspection JSUnresolvedFunction
GM_xmlhttpRequest(
Object.assign(requestParams, {
onload: resolve,
onerror: reject
}))
});
}
/**
* Checks whether http response status is OK (200).
*
* @param {HttpResponse} response Http response
* @return {Promise<HttpResponse|InvalidResponse>}
*/
static validateStatusOk(response) {
return (response.status === 200)
? Promise.of(response)
: Promise.reject(new InvalidResponse(response));
}
/**
* @param {HttpResponse} response
* @return {object}
*/
static parseResponse(response) {
return JSON.parse(response.responseText);
}
/**
* Resolve url of the JIRA in which requested project exists.
* If the project is found at both eu and com domains, com is preferred.
*
* @param {string} projectCode Just the project prefix of a JIRA issue.
* @return {Promise<string|InvalidProjectError|ProjectLoadingError>} JIRA url
*/
static async getJiraUrlForProject(projectCode) {
return jiraComUrl;
}
/**
* Fetches raw JIRA issue data.
* @param {string} key JIRA issue key string
* @param {?Function} onprogress Optional loading progress callback
* @return {Promise<HttpResponse|InvalidResponse>}
*/
static fetchIssue(key, onprogress = () => undefined) {
return Jira4U.getProjectCode(key)
.then(Jira4U.getJiraUrlForProject)
.then(tee(url => debug('project code url: ' + url)))
.then(jiraRestApiIssueUrl(key))
.then(tee(url => log(`Resolved JIRA issue url: [${url}]`)))
.then(getJsonRequest)
.then(Jira4U.setOnProgressCallback(onprogress))
.then(Jira4U.request);
}
/**
* Returns a Promise which loads and parses JIRA issue to an object.
* @param {string} key JIRA issue key string
* @param {?Function} onprogress Optional loading progress callback
* @return {Promise<JiraIssue|InvalidResponse|string|InvalidProjectError|ProjectLoadingError>}
*/
static loadIssue(key, onprogress = () => undefined) {
return Jira4U.fetchIssue(key)
.then(tee(_ => log(`Loading of issue ${key} completed.`)))
//Getting into the onload function does not actually mean the status was OK
.then(Jira4U.validateStatusOk)
.then(tee(_ => log(`Issue ${key} loaded successfully.`)))
.then(Jira4U.parseResponse)
}
/**
* @param {string} workInfo.key JIRA issue key string.
* @param {Date} workInfo.started The date/time the work on the issue started.
* @param {number} workInfo.duration in seconds.
* @param {string} workInfo.comment The work log comment.
* @param {Function} [workInfo.onReadyStateChange] Callback to be invoked when the request state changes.
* @return {Promise}
*/
static logWork(workInfo) {
console.log(`Sending a work log request. Issue=${workInfo.key}, Time spent=${workInfo.duration}minutes, Comment="${workInfo.comment}"`);
return Jira4U.getProjectCode(workInfo.key)
.then(Jira4U.getJiraUrlForProject)
.then(jiraRestApiResource('issue', workInfo.key, 'worklog'))
.then(url => (
{
method: 'POST',
headers: {
"Content-Type": "application/json",
//Disable the cross-site request check on the JIRA side
"X-Atlassian-Token": "nocheck",
//Previous header does not work for requests from a web browser
"User-Agent": "xx"
},
data: JSON.stringify({
timeSpentSeconds: workInfo.duration,
started: Jira4U._toIsoString(workInfo.started),
comment: workInfo.comment,
}),
url: url,
onreadystatechange: workInfo.onReadyStateChange
})
)
.then(Jira4U.request);
}
/**
* Converts a date to a proper ISO formatted string, which contains milliseconds and the zone offset suffix.
* No other date formats are recognized by JIRA.
* @param {Date} date Valid Date object to be formatted.
* @returns {string}
*/
static _toIsoString(date) {
const offset = -date.getTimezoneOffset();
const offsetSign = offset >= 0 ? '+' : '-';
const pad = WtmDateTime.padToDoubleDigit;
return date.getFullYear()
+ '-' + pad(date.getMonth() + 1)
+ '-' + pad(date.getDate())
+ 'T' + pad(date.getHours())
+ ':' + pad(date.getMinutes())
+ ':' + pad(date.getSeconds())
+ '.' + String(date.getUTCMilliseconds()).padStart(3, "0").substr(0, 3)
+ offsetSign + pad(offset / 60) + pad(offset % 60);
}
}
/**
* JIRA issue visualisation functions.
*
* Most of this object is stateless functions
* with the exception of currently visualised JIRA issue,
* because it is repeatedly accessed when user changes
* the working time to update the worklog bar.
*/
class IssueVisual {
constructor() {
IssueVisual.init();
}
/**
* Install JIRA issue GUI into the worklog dialog.
* Checks whether the GUI has already been added before
* making any DOM changes, so repeated calls have no effect.
*/
static init() {
if (document.getElementById('jira-toolbar-envelope')) {
console.log("JIRA toolbar was already added to form.");
return;
}
IssueVisual.addToForm();
}
/**
* Adds jira issue GUI to the time sheet form.
*/
static addToForm() {
console.log("Adding JIRA toolbar into form");
const transition = "-webkit-transition: width 0.25s; transition-delay: 0.5s;";
const trackerStyle = "width: 100%; border-collapse: collapse; height: 0.75em; margin-top: 0.4em;";
//.uu5-forms-label uu5-forms-input-m
const jiraBarNode = document.createElement('DIV');
jiraBarNode.id = 'jira-toolbar-envelope';
jiraBarNode.innerHTML = (`
<div>
<div>
<span id="parsedJiraIssue" class="uu5-forms-input-m"></span>
</div>
</div>
<div>
<div>
<table id="jiraWorkTrackerOriginal" style="${trackerStyle}">
<tbody>
<tr>
<td class="workTracker wtl" id="jiraOrigEstimate" title="Původní odhad:" style="background-color: #89AFD7; padding: 0; ${transition} width: 0;"></td>
<td class="workTracker wt" style="background-color: #eeeeee; padding: 0; ${transition} width: 100%"></td>
</tr>
</tbody>
</table>
<table id="jiraWorkTrackerLogged" style="${trackerStyle}">
<tbody>
<tr>
<td class="workTracker wtl" id="jiraWorkLogged" title="Vykázáno:" style="background-color: #51a825; padding: 0; ${transition} width: 0;"></td>
<td class="workTracker wtn" id="jiraWorkLogging" title="Nový výkaz" style="background-color: #51A82580; padding: 0; /*${transition}*/ width: 0"></td>
<td class="workTracker wtr" id="jiraRemainEstimate" title="Zbývající odhad:" style="background-color: #ec8e00; padding: 0; ${transition} width: 0;"></td>
<td class="workTracker pad" id="jiraWorkPad" title="Zbývá" style="background-color: #eeeeee; padding: 0; width: 100%"></td>
</tr>
</tbody>
</table>
</div>
<div>
<span id="parsedJiraIssue"></span>
</div>
</div>
<div style="margin-top: 10px">
<button id="jiraLogWorkButton" class="uu5-bricks-button-m uu6-bricks-button-filled" type="button" style="border: none" disabled>
<span class="uu5-bricks-span uu5-bricks-lsi-item uu5-bricks-lsi">Vykázat na <u>J</u>IRA issue</span>
</button>
<span id="jira-issue-work-log-request-progress" style="margin-left: 8px;"></span>
</div>
`);
IssueVisual.insertAfter(jiraBarNode, WtmDialog.highRateNode());
}
static insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
/**
* Display a loaded JIRA issue in the form as a link
* and update the time tracker.
*
* @param {JiraIssue} issue The JIRA issue object as fetched from JIRA rest API
*/
static async showIssue(issue) {
const domain = issue.self.slice(0, issue.self.indexOf(jiraRestApiPath));
const url = await jiraBrowseIssueUrl(issue.key)(domain);
//Some projects use this field for a project code, like NBS or FBLI
const projectCode = P4uWorklogger.mapToHumanJiraIssue(issue).projectCode;
const projectCodeHtml = projectCode && `<div>Project Code: ${projectCode}</div>` || '';
IssueVisual.$showInIssueSummary(IssueVisual.linkHtml(url, `${issue.key} - ${issue.fields.summary}`) + projectCodeHtml);
IssueVisual.trackWorkOf(issue);
return issue;
}
/**
* Displays some fancy animation at the place of the JIRA issue summary.
*/
static showIssueLoadingProgress() {
IssueVisual.$showInIssueSummary(jiraIssueLoaderAnimation);
IssueVisual.resetWorkTracker();
}
/**
* Sets the currently displayed JIRA issue to null and resets all the visualisation.
*/
static resetIssue() {
IssueVisual.resetWorkTracker();
}
/**
* Display a visual work log time tracker of the current JIRA issue in the form.
*/
static updateWorkTracker() {
if (IssueVisual._issue) {
const issue = IssueVisual._issue;
const orig = issue.fields.timetracking.originalEstimateSeconds || 0;
const remain = issue.fields.timetracking.remainingEstimateSeconds || 0;
const logged = issue.fields.timetracking.timeSpentSeconds || 0;
const added = WtmDialog.getDurationSeconds();
const totalMax = Math.max(orig, logged + Math.max(added, remain));
const newRemain = Math.max(remain - added, 0);
const percentOfTotal = (x) => totalMax > 0 ? x / totalMax * 100 : 0;
const setWidth = (id, w) => {
document.getElementById(id).style.width = `${Math.round(w)}%`;
};
const setTitle = (id, t) => {
const e = document.getElementById(id);
e.title = e.title.split(':')[0] + ': ' + t || "0h";
e.alt = e.title;
};
const toHours = (seconds) => (seconds / 3600).toFixed(2) + 'h';
setWidth('jiraOrigEstimate', percentOfTotal(orig));
setTitle('jiraOrigEstimate', issue.fields.timetracking.originalEstimate);
setWidth('jiraWorkLogged', percentOfTotal(logged));
setTitle('jiraWorkLogged', issue.fields.timetracking.timeSpent);
setWidth('jiraWorkLogging', percentOfTotal(added));
setTitle('jiraWorkLogging', toHours(added));
setWidth('jiraRemainEstimate', percentOfTotal(newRemain));
setTitle('jiraRemainEstimate', toHours(newRemain));
const remainCell = document.getElementById('jiraRemainEstimate');
remainCell.style.display = (newRemain === 0) ? "none" : null;//Chrome renders zero width as 1px
}
else
IssueVisual.resetWorkTracker();
}
/**
* Sets currently displayed JIRA issue for the time tracker bar.
* This is the only state held by IssueVisual class.
*
* @typedef JiraIssue
* @property {string} key The key of the JIRA issue, e.g. XYZ-1234
* @property {string} rawJiraIssue.fields.project.key The project key of the JIRA issue, e.g. XYZ
* @property {string} fields.summary The JIRA issue summary, i.e. the title of the ticket.
* @property {string} self JIRA link to this issue.
* @property {?number} fields.timetracking.originalEstimateSeconds
* @property {?number} fields.timetracking.remainingEstimateSeconds
* @property {?number} fields.timetracking.timeSpentSeconds
* @property {?number} fields.timetracking.originalEstimate
* @property {?number} fields.timetracking.remainingEstimate
* @property {?number} fields.timetracking.timeSpent
* @property {string} rawJiraIssue.fields.issuetype.name Type of the issue, e.g. "Bug"
* @property {?string} fields.customfield_13908 NBS Project code
* @property {?string} fields.customfield_10174 FBL Project code
* @property {?string} fields.customfield_12271 FBL System
*
* @param {?JiraIssue} issue
*/
static trackWorkOf(issue = null) {