-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
533 lines (453 loc) · 19.6 KB
/
script.js
File metadata and controls
533 lines (453 loc) · 19.6 KB
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
// ==UserScript==
// @name Tempo Worklog Highlighter
// @namespace Violentmonkey Scripts
// @version 1.3.2
// @description Highlights working logs based on billable seconds and internal or customer
// @author Armin Schneider
// @match *://timetoactgroup.atlassian.net/*
// @match https://app.eu.tempo.io/*
// @run-at document-start
// @grant unsafeWindow
// ==/UserScript==
(function () {
// region "Variables & Constants"
// Detect dark mode
const isDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches;
// Set highlighting colors (light and dark theme variants)
const COLOR_BILLABLE_WITH_BILLABLE_SECONDS = isDarkMode
? "#2e5e2e"
: "#efffddff"; // Green background for billable worklogs with billable seconds
const COLOR_BILLABLE_NO_BILLABLE_SECONDS = isDarkMode
? "#705a2e"
: "#fff4ddff"; // Orange/Yellow background for billable worklogs without billable seconds
const COLOR_INTERNAL = isDarkMode ? "#703232" : "#FFDDDD"; // "Lighter" Red background for internal worklogs (not billable)
const COLOR_TAT_TEMP = isDarkMode ? "#444488" : "#ddddffff"; // Purple background for TAT_TEMP worklogs
const COLOR_ERROR = isDarkMode ? "#b33a3a" : "#ff0000ff"; // Red background for error worklogs
const COLOR_LS = isDarkMode ? "#336b8a" : "#d6efff"; // Light Blue background for LS worklogs
// Configure description suggestion feature
const IS_DESCRIPTION_SUGGESTION_ENABLED = true;
const DESCRIPTION_SUGGESTION_STORAGE_DAYS = 14;
// Check if we're in the Tempo iframe
const IS_TEMPORAL_IFRAME = window.location.href.includes("app.eu.tempo.io");
// Create global variable to store Tempo worklog data
window.tempoWorklogData = [];
// endregion "Variables & Constants"
// region "DOM and Navigation Monitoring"
const _push = history.pushState;
const _replace = history.replaceState;
history.pushState = function () {
_push.apply(this, arguments);
window.dispatchEvent(new Event("locationchange"));
};
history.replaceState = function () {
_replace.apply(this, arguments);
window.dispatchEvent(new Event("locationchange"));
};
// --- Listen to all relevant navigation events ---
window.addEventListener("popstate", () =>
window.dispatchEvent(new Event("locationchange"))
);
window.addEventListener("hashchange", () =>
window.dispatchEvent(new Event("locationchange"))
);
// region "Time Entry Comment Caching"
if (IS_DESCRIPTION_SUGGESTION_ENABLED && IS_TEMPORAL_IFRAME) {
const PAGE_KEY = "tempo_comment_cache";
const MAX_AGE_MS =
DESCRIPTION_SUGGESTION_STORAGE_DAYS * 24 * 60 * 60 * 1000; // 30 days
function safeParse(raw) {
try {
return raw ? JSON.parse(raw) : [];
} catch (e) {
console.warn("[tempo-cache] failed to parse cache, resetting:", e);
return [];
}
}
function loadCache() {
try {
const raw = localStorage.getItem(PAGE_KEY);
return safeParse(raw);
} catch (e) {
console.warn("[tempo-cache] load failed:", e);
return [];
}
}
function saveCache(entries) {
try {
localStorage.setItem(PAGE_KEY, JSON.stringify(entries));
} catch (e) {
console.warn("[tempo-cache] save failed:", e);
}
}
function clearCache() {
try {
localStorage.setItem(PAGE_KEY, JSON.stringify([]));
} catch (e) {
console.warn("[tempo-cache] clear failed:", e);
return false;
}
return true;
}
// Attach to the API and create a console-friendly alias
window.clearTempoCommentCache = clearCache;
function purgeOldEntries(entries) {
const cutoff = Date.now() - MAX_AGE_MS;
const filtered = entries.filter((e) => {
// Use lastUsed if present
const t = e.lastUsed || 0;
return t >= cutoff;
});
if (filtered.length !== entries.length) {
saveCache(filtered);
}
return filtered;
}
// Convenience method: add a comment (increment count if exists)
function addTimeEntryComment(comment, projectNumber) {
if (!comment || typeof comment !== "string") return null;
const normalized = comment.trim();
if (normalized.length === 0) return null;
const now = Date.now();
const entries = loadCache();
const idx = entries.findIndex((e) => e.comment === normalized);
let entry;
if (idx !== -1) {
entry = entries[idx];
entry.count = (entry.count || 0) + 1;
entry.lastUsed = now;
entries[idx] = entry;
} else {
entry = {
comment: normalized,
count: 1,
lastUsed: now,
projectNumber: projectNumber,
};
entries.push(entry);
}
saveCache(entries);
return entry;
}
// Convenience method: list all comments ordered by count (desc)
function listTimeEntryComments() {
const entries = loadCache();
// return a shallow copy sorted by count desc then lastUsed desc
return entries.slice().sort((a, b) => {
const countA = a.count || 0;
const countB = b.count || 0;
if (countB !== countA) return countB - countA;
return (b.lastUsed || 0) - (a.lastUsed || 0);
});
}
// Purge on load
saveCache(purgeOldEntries(loadCache()));
function addCommentEntrySelect(issueInputField) {
if (!issueInputField) {
console.error("[tempo-addCommentEntrySelect] no input field found");
return;
}
// Create new select element for current project
if (document.getElementById("tempoCommentSelect")) {
document.getElementById("tempoCommentSelect").remove();
}
const worklogCommentField = document.getElementById("commentField");
const issueInput = issueInputField.value.trim();
const projectNumber = issueInput.substring(0, issueInput.indexOf(" "));
if (worklogCommentField && projectNumber) {
worklogCommentField.parentElement.style.flexDirection = "column";
const commentSelect = document.createElement("select");
commentSelect.id = "tempoCommentSelect";
commentSelect.style.display = "block";
commentSelect.style.marginBottom = "6px";
commentSelect.style.padding = "8px";
commentSelect.style.width = "100%";
commentSelect.style.maxWidth = "500px";
commentSelect.style.textOverflow = "ellipsis";
const placeholder = document.createElement("option");
placeholder.value = "";
placeholder.textContent = "Select recent comment";
placeholder.disabled = true;
placeholder.selected = true;
commentSelect.appendChild(placeholder);
listTimeEntryComments()
.filter((entry) => {
return entry.projectNumber.startsWith(projectNumber);
})
.forEach((e) => {
const opt = document.createElement("option");
opt.value = e.comment;
opt.textContent = `${e.comment} (${e.count || 0})`;
commentSelect.appendChild(opt);
});
if (worklogCommentField.parentElement) {
worklogCommentField.parentElement.insertBefore(
commentSelect,
worklogCommentField
);
}
commentSelect.addEventListener("change", () => {
// Shenanigans to properly set the value and trigger any listeners for React
const setter = Object.getOwnPropertyDescriptor(
window.HTMLTextAreaElement.prototype,
"value"
).set;
setter.call(worklogCommentField, commentSelect.value);
worklogCommentField.dispatchEvent(
new Event("input", {bubbles: true, cancelable: true})
);
});
// time log get's updated
document.getElementById("logTimeBtn").addEventListener("click", () => {
if (
issueInputField &&
worklogCommentField &&
worklogCommentField.value.trim()
) {
addTimeEntryComment(
worklogCommentField.value.trim(),
projectNumber
);
setupModalObserver();
}
});
}
}
function callOnValueChanged(elementId, callback) {
const checkContent = () => {
const el = document.getElementById(elementId);
if (el && el.value && el.value.trim().length > 0) {
const value = el.value.trim();
if (!el.__last_value) {
callback(el);
} else if (value !== el.__last_value) {
callback(el);
}
el.__last_value = value;
}
};
setInterval(checkContent, 50);
}
function setupModalObserver() {
waitForElement(
"#form-issue-input",
(elements) => {
if (elements && elements.length) {
// We need to do a poll approach, as no listener seems to work reliably here
// This might be to the reason that there is always a new input field created
callOnValueChanged("form-issue-input", () => {
addCommentEntrySelect(
document.getElementById("form-issue-input")
);
});
}
},
Number.MAX_VALUE
);
}
setupModalObserver();
}
// endregion "Time Entry Comment Caching"
// Only listen for location changes in the Tempo iframe
if (IS_TEMPORAL_IFRAME) {
window.addEventListener("locationchange", onWeekChangedInIframe);
// Set up MutationObserver to watch for DOM changes
const setupObserver = () => {
if (!document.body) {
setTimeout(setupObserver, 100);
return;
}
const observer = new MutationObserver((mutations) => {
// Check if any worklog elements were added
for (const mutation of mutations) {
if (mutation.addedNodes.length > 0) {
for (const node of mutation.addedNodes) {
if (node.nodeType === 1) {
// Element node
// Check if the node or its descendants contain worklog elements
if (node.id && node.id.startsWith("WORKLOG-")) {
onWeekChangedInIframe();
return;
}
if (
node.querySelector &&
node.querySelector('div[id^="WORKLOG-"]')
) {
onWeekChangedInIframe();
return;
}
if (
node.querySelector &&
node.querySelector(
'a[href^="https://timetoactgroup.atlassian.net/browse/"]'
)
) {
changeWorklogInformation();
return;
}
}
}
}
}
});
// Start observing the document with the configured parameters
observer.observe(document.body, {
childList: true,
subtree: true,
});
};
setupObserver();
}
// endregion "DOM and Navigation Monitoring"
// region "Worklog Processing and Highlighting"
// This runs every time the page changes inside the Tempo iframe
function onWeekChangedInIframe() {
waitForElement('div[id^="WORKLOG-"]', (elements) => {
elements.forEach((el) => {
const worklogId = el.id.replace("WORKLOG-", "");
const worklogData =
window.tempoWorklogData &&
window.tempoWorklogData.find(
(wl) => wl.originId.toString() === worklogId
);
if (!worklogData) return;
if (
worklogData.attributes._Account_.value.endsWith("SAP_C") &&
worklogData.billableSeconds > 0
) {
el.style.backgroundColor = COLOR_BILLABLE_WITH_BILLABLE_SECONDS;
} else if (
worklogData.attributes._Account_.value.endsWith("SAP_C") &&
worklogData.billableSeconds === 0
) {
el.style.backgroundColor = COLOR_BILLABLE_NO_BILLABLE_SECONDS;
} else if (worklogData.attributes._Account_.value === "ERRORACCOUNT") {
el.style.backgroundColor = COLOR_ERROR;
} else if (worklogData.attributes._Account_.value === "TATTEMP") {
el.style.backgroundColor = COLOR_TAT_TEMP;
} else if (
//Will break sooner or later
worklogData.attributes._Account_.value.includes("TATINT.1.2")
) {
el.style.backgroundColor = COLOR_LS;
} else {
el.style.backgroundColor = COLOR_INTERNAL;
}
});
changeWorklogInformation(elements);
});
}
function changeWorklogInformation(elements) {
elements.forEach((el) => {
const worklogId = el.id.replace("WORKLOG-", "");
const worklogData =
window.tempoWorklogData &&
window.tempoWorklogData.find(
(wl) => wl.originId.toString() === worklogId
);
const header = el.querySelector("div[title]");
if (header && header.title.trim() === header.textContent.trim()) {
Object.assign(header.style, {
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
display: "block",
});
}
const existingCommentSpan = el.querySelector(
'div[name="tempoCardComment"]'
);
if (!existingCommentSpan) {
// Select the <a> element inside the div
var link = el.querySelector(
'div a[href^="https://timetoactgroup.atlassian.net/browse/"]'
);
if (link) {
// Create a new <span> element
const span = document.createElement("span");
span.textContent = worklogData.comment;
span.id = "customCommentSpan" + worklogId;
span.title = link.href;
// Replace the <a> element with the <span>
link.replaceWith(span);
}
} else {
existingCommentSpan.style.opacity = "1.0";
const comment = document.getElementById(
"customCommentSpan" + worklogId
);
if (comment) {
const commentParent = comment.parentElement;
const link = document.createElement("a");
link.href = comment.title + commentParent.title;
link.textContent = commentParent.title;
link.target = "_blank";
// Replace the <a> element with the <span>
comment.replaceWith(link);
}
}
});
}
// Helper function to wait for elements to appear in the DOM
function waitForElement(selector, callback, timeout = 5000) {
const startTime = Date.now();
const checkElement = () => {
const elements = document.querySelectorAll(selector);
if (elements.length > 0) {
callback(elements);
} else if (Date.now() - startTime < timeout) {
setTimeout(checkElement, 50);
} else {
callback([]);
}
};
checkElement();
}
// endregion "Worklog Processing and Highlighting"
// region "Retrieve Tempo worklog data via XHR interception"
function upsertWorklogs(data) {
// Ensure data is always an array
const worklogs = Array.isArray(data) ? data : [data];
for (const wl of worklogs) {
const index = window.tempoWorklogData.findIndex(
(existing) => existing.tempoWorklogId === wl.tempoWorklogId
);
if (index !== -1) {
// Update existing worklog
window.tempoWorklogData[index] = wl;
} else {
// Add new worklog
window.tempoWorklogData.push(wl);
}
}
onWeekChangedInIframe();
}
// Only set up XHR interception in the Tempo iframe
if (IS_TEMPORAL_IFRAME) {
// Intercept XMLHttpRequest
const origOpen = XMLHttpRequest.prototype.open;
const origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function (method, url, ...rest) {
this._logUrl = url;
this._logMethod = method;
return origOpen.apply(this, [method, url, ...rest]);
};
XMLHttpRequest.prototype.send = function (...args) {
// Check if this is the Tempo worklog request
if (
this._logUrl &&
this._logUrl.includes("/rest/tempo-timesheets/4/worklogs")
) {
this.addEventListener("load", function () {
try {
const data = JSON.parse(this.responseText);
upsertWorklogs(data);
} catch (e) {
console.error("[TEMPO] Failed to parse response:", e);
}
});
}
return origSend.apply(this, args);
};
}
// endregion "Retrieve Tempo worklog data via XHR interception"
})();