Files
itflow/agent/js/ticket_time_tracking.js

297 lines
12 KiB
JavaScript

/*
* A ticket's timer, on its page (agent/ticket.php), kept in this browser's localStorage so it
* runs on while you're elsewhere (the top bar's timers, js/ticket_timers.js, read the same keys).
* With Start the timer on opening a ticket on, it starts by itself when you open the ticket.
* Sending a reply or note puts the time on it and stops the timer: the page comes back with it
* stopped, and stays so - reloading, or anything else done on the ticket - until you press play or
* come to the ticket again from elsewhere, which starts a new one. Choosing On Hold, Resolved or
* Closed for after the reply pauses it.
*/
(function() {
document.addEventListener("DOMContentLoaded", function() {
var timerInterval = null;
var ticketID = getCurrentTicketID();
var elapsedSecs = getElapsedSeconds();
function getCurrentTicketID() {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get('ticket_id');
}
function getLocalStorageKey(suffix) {
return ticketID + "-" + suffix;
}
function getElapsedSeconds() {
let storedStartTime = parseInt(localStorage.getItem(getLocalStorageKey("startTime")) || "0");
let pausedTime = parseInt(localStorage.getItem(getLocalStorageKey("pausedTime")) || "0");
if (!storedStartTime) return pausedTime;
let timeSinceStart = Math.floor((Date.now() - storedStartTime) / 1000);
return pausedTime + timeSinceStart;
}
function pad(val) {
return val < 10 ? "0" + val : val;
}
function displayTime() {
// Show hrs, mins, sec input placeholders if auto-start is off
if (elapsedSecs === 0) {
document.getElementById("hours").value = "";
document.getElementById("minutes").value = "";
document.getElementById("seconds").value = "";
return;
}
let totalSeconds = elapsedSecs;
let hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
let minutes = Math.floor(totalSeconds / 60);
let seconds = totalSeconds % 60;
let hoursEl = document.getElementById("hours");
let minutesEl = document.getElementById("minutes");
let secondsEl = document.getElementById("seconds");
if (hoursEl && minutesEl && secondsEl) {
hoursEl.value = pad(hours);
minutesEl.value = pad(minutes);
secondsEl.value = pad(seconds);
} else {
console.warn("Timer input elements not found");
}
}
function countTime() {
elapsedSecs = getElapsedSeconds();
displayTime();
}
// Sent a reply or note here - the timer stays stopped while the page comes back from this ticket
function repliedKey() {
return "ticket-timer-replied-" + ticketID;
}
function forgetReplied() {
try {
sessionStorage.removeItem(repliedKey());
} catch (e) {}
let hint = document.querySelector("[data-timer-replied]");
if (hint) hint.hidden = true;
}
/*
* Whether this page is the ticket coming back after your reply - from its own form, a reload,
* or another change made on it. Arriving from anywhere else forgets the reply, so the timer
* starts again as it does on opening a ticket.
*/
function cameBackAfterReply() {
let at = 0;
try {
at = parseInt(sessionStorage.getItem(repliedKey()) || "0", 10);
} catch (e) {
return false;
}
if (!at) {
return false;
}
let fromHere = false;
try {
let from = new URL(document.referrer);
fromHere = from.origin === window.location.origin && from.pathname === window.location.pathname && from.searchParams.get("ticket_id") === String(ticketID);
} catch (e) {}
if (!fromHere) {
forgetReplied();
}
return fromHere;
}
function startTimer() {
forgetReplied();
if (!localStorage.getItem(getLocalStorageKey("startTime"))) {
localStorage.setItem(getLocalStorageKey("startTime"), Date.now().toString());
}
timerInterval = setInterval(countTime, 1000);
let btn = document.getElementById("startStopTimer");
if (btn) btn.innerHTML = "<i class='fas fa-pause'></i>";
localStorage.setItem("ticket-timer-running-" + ticketID, "true");
}
function pauseTimer() {
if (timerInterval) {
clearInterval(timerInterval);
timerInterval = null;
}
let currentElapsed = getElapsedSeconds();
localStorage.setItem(getLocalStorageKey("pausedTime"), currentElapsed.toString());
localStorage.removeItem(getLocalStorageKey("startTime"));
let btn = document.getElementById("startStopTimer");
if (btn) btn.innerHTML = "<i class='fas fa-play'></i>";
localStorage.setItem("ticket-timer-running-" + ticketID, "false");
}
function clearTimeStorage() {
localStorage.removeItem(getLocalStorageKey("startTime"));
localStorage.removeItem(getLocalStorageKey("pausedTime"));
localStorage.removeItem("ticket-timer-running-" + ticketID);
}
function resetTimer() {
itflowConfirm({ title: 'Reset the timer?', text: 'The time on it goes back to zero.', button: 'Reset', danger: true }).then(function (confirmed) {
if (!confirmed) {
return;
}
clearInterval(timerInterval);
timerInterval = null;
elapsedSecs = 0;
clearTimeStorage();
displayTime();
let btn = document.getElementById("startStopTimer");
if (btn) btn.innerHTML = "<i class='fas fa-play'></i>";
localStorage.setItem("ticket-timer-running-" + ticketID, "false");
});
}
function forceResetTimer() {
clearInterval(timerInterval);
timerInterval = null;
elapsedSecs = 0;
clearTimeStorage();
displayTime();
let btn = document.getElementById("startStopTimer");
if (btn) btn.innerHTML = "<i class='fas fa-play'></i>";
}
function handleInputFocus() {
pauseTimer();
let hint = document.querySelector("[data-timer-replied]");
if (hint) hint.hidden = true;
}
function updateTimeFromInput() {
const hours = parseInt(document.getElementById("hours")?.value, 10) || 0;
const minutes = parseInt(document.getElementById("minutes")?.value, 10) || 0;
const seconds = parseInt(document.getElementById("seconds")?.value, 10) || 0;
elapsedSecs = (hours * 3600) + (minutes * 60) + seconds;
if (!timerInterval) {
localStorage.setItem(getLocalStorageKey("pausedTime"), elapsedSecs.toString());
} else {
const newStartTime = Date.now() - (elapsedSecs * 1000);
localStorage.setItem(getLocalStorageKey("startTime"), newStartTime.toString());
localStorage.removeItem(getLocalStorageKey("pausedTime"));
}
}
// On Hold, Resolved or Closed chosen for after the reply - the work is done, so it stops counting.
// The select's values are status ids; data-timer-pause lists those that pause it.
function checkStatusAndPauseTimer() {
var statusEl = document.querySelector('select[name="status"]');
if (statusEl && timerInterval) {
var pausing = (statusEl.getAttribute("data-timer-pause") || "").split(",");
if (pausing.indexOf(String(statusEl.value)) !== -1) {
pauseTimer();
}
}
}
// Update on tab visibility change to handle background sleep
document.addEventListener('visibilitychange', function() {
if (!document.hidden) {
elapsedSecs = getElapsedSeconds();
displayTime();
}
});
// Attach input listeners with null checks
const hoursEl = document.getElementById("hours");
if (hoursEl) {
hoursEl.addEventListener('change', updateTimeFromInput);
hoursEl.addEventListener('focus', handleInputFocus);
}
const minutesEl = document.getElementById("minutes");
if (minutesEl) {
minutesEl.addEventListener('change', updateTimeFromInput);
minutesEl.addEventListener('focus', handleInputFocus);
}
const secondsEl = document.getElementById("seconds");
if (secondsEl) {
secondsEl.addEventListener('change', updateTimeFromInput);
secondsEl.addEventListener('focus', handleInputFocus);
}
const statusEl = document.querySelector('select[name="status"]');
if (statusEl) {
statusEl.addEventListener('change', checkStatusAndPauseTimer);
}
const startStopBtn = document.getElementById("startStopTimer");
if (startStopBtn) {
startStopBtn.addEventListener('click', function() {
if (timerInterval === null) {
startTimer();
} else {
pauseTimer();
}
});
}
const resetBtn = document.getElementById("resetTimer");
if (resetBtn) {
resetBtn.addEventListener('click', function() {
resetTimer();
});
}
// Reset once the reply actually goes - not on a click of Send that is held back (the
// composer shut, or a canned response's [word] still to fill in), which lost the time
const addReplyBtn = document.getElementById("ticket_add_reply");
if (addReplyBtn && addReplyBtn.form) {
addReplyBtn.form.addEventListener('submit', function(e) {
setTimeout(function() {
if (!e.defaultPrevented) {
forceResetTimer();
// ... and it stays stopped when the page comes back, rather than starting again
try {
sessionStorage.setItem(repliedKey(), Date.now().toString());
} catch (err) {}
}
}, 0);
});
}
const closeBtn = document.getElementById("ticket_close");
if (closeBtn) {
closeBtn.addEventListener('click', function() {
setTimeout(clearTimeStorage, 100);
});
}
// Final initialization logic
try {
displayTime();
// No time on it - a pausedTime of 0 left by an older version counts as none
if (!localStorage.getItem(getLocalStorageKey("startTime")) && !(parseInt(localStorage.getItem(getLocalStorageKey("pausedTime")) || "0", 10) > 0)) {
let autoStart = typeof ticketAutoStart !== "undefined" && ticketAutoStart === 1;
if (autoStart && cameBackAfterReply()) {
// Stopped with the reply just sent - press play to time more
let hint = document.querySelector("[data-timer-replied]");
if (hint) hint.hidden = false;
} else if (autoStart) {
startTimer();
}
localStorage.removeItem(getLocalStorageKey("pausedTime"));
} else if (localStorage.getItem(getLocalStorageKey("startTime"))) {
startTimer();
}
} catch (error) {
console.error("There was an issue initializing the timer:", error);
}
});
})();