let selectedAccounts = getOrInitSessionArray('selectedAccounts');
let selectedAccountLabels = getOrInitSessionArray('selectedAccountLabels');
let userAccountDetailsArray = [];
let isOrderGridLoading = false;
let debounceTimer;
let uniqueAccounts = [];
let bulkUpdating = false;
// $(document).ready(function () {
// var idleTime = 0;
// var idleLimit = 15 * 60 * 1000; // 15 minutes
// var idleTimer;
// function resetTimer() {
// clearTimeout(idleTimer);
// idleTimer = setTimeout(logoutUser, idleLimit);
// }
// function logoutUser() {
// // alert("You have been logged out due to inactivity.");
// // Example logout action:
// location.href = "/Account/Login/LogOff";
// }
// // List of user activity events to listen for
// $(document).on("mousemove keydown click scroll", function () {
// resetTimer();
// });
// // Start the timer on load
// resetTimer();
// });
function getOrInitSessionArray(key) {
const stored = sessionStorage.getItem(key);
if (stored) {
return JSON.parse(stored);
} else {
const emptyArray = [];
sessionStorage.setItem(key, JSON.stringify(emptyArray));
return emptyArray;
}
}
function populateAccountDropdown() {
let locationDropdownItems = "";
//condition to exclude home page
if (window.location.pathname != "/" && window.location.pathname != "") {
// showLoader();
//get account details of the current user
apiService
.getItems(
"ricnt_contactaccountmappings?$select=ricnt_contactaccountmappingid,ricnt_Account,ricnt_Contact&$expand=ricnt_Account($select=accountnumber,name,address2_composite),ricnt_Contact($select=contactid)&$filter=ricnt_Contact/contactid eq '" +
$("#contact-id").val() +
"'"
)
.then((data) => {
locationDropdownItems += `
`;
if (data.value.length > 0) {
data.value.forEach((element) => {
userAccountDetailsArray.push({
customerName: element.ricnt_Account.name,
custometNumber: element.ricnt_Account.accountnumber,
});
locationDropdownItems += `
`;
});
}
//populate items in location dropdown
$("#location-items").empty();
$("#location-items").append(locationDropdownItems);
const $allCheckboxes = $("#location-items input[type='checkbox']");
const $accountCheckboxes = $allCheckboxes.not("#selectAllLocations"); // Exclude 'Select All'
if ($accountCheckboxes.length === 1) {
uniqueAccounts = [];
$accountCheckboxes.prop("checked", true).trigger("change");
}
// var $items = $("#location-items li");
// select the location if only one location exists
// if ($items.length === 1) {
// const $checkbox = $items.find("input[type='checkbox']");
// $checkbox.prop("checked", true).trigger("change"); // ✅ triggers your change handler
// }
//select dropdown if a new account is added
selectedAccountLabels.forEach(element => {
let checkbox = Array.from(document.querySelectorAll("label.dropdown-item"))
.find(label => label.textContent.includes(element))
?.querySelector("input[type='checkbox']");
$(checkbox).prop("checked", true).trigger("change");
});
// hideLoader();
})
.catch((error) => {
hideLoader();
showErrorToast("Failed to get account details");
console.error("Failed to get account details", error);
});
}
}
function updateLocationDropdownButton() {
const $btn = $("#selectLocationDropdown");
const count = selectedAccountLabels.length;
if (count === 0) {
$btn.text("Select Location")
.attr("title", "Select Location")
.removeClass("multi-options");
} else if (count === 1) {
$btn.text(selectedAccountLabels[0])
.attr("title", selectedAccountLabels[0])
.removeClass("multi-options");
} else {
const display = `${selectedAccountLabels[0]} `;
$btn.html(display)
.attr("title", selectedAccountLabels.join(", "))
.addClass("multi-options");
}
}
function showLoader() {
$("#loader").addClass("active");
}
function hideLoader() {
$("#loader").removeClass("active");
}
function showErrorToast(content) {
$("#error-toast-text").text(content);
$("#error-toast").show();
setTimeout(() => {
$("#error-toast").hide();
}, 4000);
}
function showSuccessToast(content) {
$("#success-toast-text").text(content);
$("#success-toast").show();
setTimeout(() => {
$("#success-toast").hide();
}, 3000);
}
// checkbox change handling
// $(document).on(
// "change",
// '#location-items input[type="checkbox"]',
// async function () {
// const value = $(this).val();
// // only take name + accountnumber for display
// const rawText = $(this).closest("label").text().trim();
// const parts = rawText.split("-");
// //***********do not change label and selectedAccountLables logic, this is used in many places*****
// const label = parts[0].trim() + " - " + parts[1].trim();
// //***********do not change label and selectedAccountLables logic, this is used in many places*****
// if (this.checked) {
// if (!selectedAccounts.includes(value)) selectedAccounts.push(value);
// if (!selectedAccountLabels.includes(label))
// selectedAccountLabels.push(label);
// } else {
// selectedAccounts = selectedAccounts.filter((v) => v !== value);
// selectedAccountLabels = selectedAccountLabels.filter((l) => l !== label);
// }
// updateLocationDropdownButton();
// populateCustomOrderSummary();
// await initOrderGrid();
// if (selectedAccounts.length > 0) {
// await initCarousel();
// fetchAndRenderCases();
// await initInvoiceGrid();
// } else {
// setCarousel();
// }
// }
// );
$(document).on(
"change",
'#location-items input[type="checkbox"]',
async function () {
const value = $(this).val();
if (
value !== "all" &&
uniqueAccounts.includes(value) &&
selectedAccounts.includes(value) &&
this.checked
) {
return;
}
if (value === "all") {
const isChecked = this.checked;
bulkUpdating = true;
// Check/uncheck all child checkboxes silently
$('#location-items input[type="checkbox"]').not(this).prop("checked", isChecked);
// ✅ rebuild arrays/labels in bulk
selectedAccounts = [];
selectedAccountLabels = [];
uniqueAccounts = [];
if (isChecked) {
$('#location-items input[type="checkbox"]').not(this).each(function () {
const rawText = $(this).closest("label").text().trim();
const lastHyphenIndex = rawText.lastIndexOf("-");
let label = rawText;
if (lastHyphenIndex !== -1) {
const namePart = rawText.substring(0, lastHyphenIndex).trim();
const accountNumberPart = rawText.substring(lastHyphenIndex + 1).trim();
label = `${namePart} - ${accountNumberPart}`;
}
const val = $(this).val();
selectedAccounts.push(val);
selectedAccountLabels.push(label);
uniqueAccounts.push(val);
});
}
sessionStorage.setItem("selectedAccounts", JSON.stringify(selectedAccounts));
sessionStorage.setItem("selectedAccountLabels", JSON.stringify(selectedAccountLabels));
bulkUpdating = false;
// ✅ run updates once
runUpdates();
return;
}
if (bulkUpdating) return;
// -------------------
// Extract label (do not change this logic)
// -------------------
const rawText = $(this).closest("label").text().trim();
const lastHyphenIndex = rawText.lastIndexOf("-");
let label = rawText;
if (lastHyphenIndex !== -1) {
const namePart = rawText.substring(0, lastHyphenIndex).trim();
const accountNumberPart = rawText.substring(lastHyphenIndex + 1).trim();
label = `${namePart} - ${accountNumberPart}`;
}
// -------------------
// Maintain selected accounts/labels
// -------------------
if (this.checked) {
if (!selectedAccounts.includes(value)) selectedAccounts.push(value);
if (!selectedAccountLabels.includes(label))
selectedAccountLabels.push(label);
if (value !== "all") uniqueAccounts.push(value);
} else {
selectedAccounts = selectedAccounts.filter((v) => v !== value);
selectedAccountLabels = selectedAccountLabels.filter((l) => l !== label);
uniqueAccounts = selectedAccounts.filter((v) => v !== value);
// Uncheck "Select all" if any item is unchecked
$("#selectAllLocations").prop("checked", false);
}
sessionStorage.setItem("selectedAccounts", JSON.stringify(selectedAccounts));
sessionStorage.setItem("selectedAccountLabels", JSON.stringify(selectedAccountLabels));
// Auto-check "Select all" if all are selected
const totalCheckboxes = $('#location-items input[type="checkbox"]').not("#selectAllLocations").length;
const checkedCheckboxes = $('#location-items input[type="checkbox"]:checked')
.not("#selectAllLocations").length;
if (checkedCheckboxes === totalCheckboxes) {
$("#selectAllLocations").prop("checked", true);
}
runUpdates();
}
);
let updateTimer;
function runUpdates() {
clearTimeout(updateTimer);
updateTimer = setTimeout(async () => {
try {
// showLoader(); // Unified loader at the start
// updateLocationDropdownButton();
await loaderRun();
populateCustomOrderSummary();
// setEquipmentCard();
await initOrderGrid();
fetchAndRenderCases();
await initInvoiceGrid();
// if (selectedAccounts.length > 0) {
// await initCarousel();
// // fetchAndRenderCases();
// // await initInvoiceGrid();
// } else {
// setCarousel();
// }
} catch (error) {
console.error('Error during runUpdates:', error);
} finally {
// hideLoader(); // Hide once all operations are done
}
}, 0);
}
async function loaderRun(){
try {
showLoader(); // Unified loader at the start
updateLocationDropdownButton();
setEquipmentCard();
if (selectedAccounts.length > 0) {
await initCarousel();
// fetchAndRenderCases();
// await initInvoiceGrid();
} else {
setCarousel();
}
} catch (error) {
console.error('Error during loaderRun:', error);
} finally {
hideLoader(); // Hide once all operations are done
}
}
// function runUpdates() {
// clearTimeout(updateTimer);
// updateTimer = setTimeout(async () => {
// updateLocationDropdownButton();
// populateCustomOrderSummary();
// setEquipmentCard();
// await initOrderGrid();
// if (selectedAccounts.length > 0) {
// await initCarousel();
// fetchAndRenderCases();
// await initInvoiceGrid();
// } else {
// setCarousel();
// }
// }, 0);
// }
// prevent closing dropdown when clicking labels
$(document).on("click", ".dropdown-menu label.dropdown-item", function (e) {
e.stopPropagation();
});
//hide modal based on id
function hideModalById(modalId) {
const modalElement = document.getElementById(modalId);
if (!modalElement) return;
// Get existing instance or create one
const modal =
bootstrap.Modal.getInstance(modalElement) ||
new bootstrap.Modal(modalElement);
modal.hide();
}
//clean up modal backdrops
function cleanupStrayBackdrops() {
// Remove all backdrops
document.querySelectorAll(".modal-backdrop").forEach((el) => el.remove());
// Remove modal-open class from body
document.body.classList.remove("modal-open");
// Reset body padding Bootstrap might have added
document.body.style.removeProperty("padding-right");
if (document.body.style.overflow === "hidden") {
document.body.style.removeProperty("overflow");
}
}
function getProductNames(){
let productName ="";
$(".imgandtxt").each(function() {
productName = $(this).find("p").text();
console.log("Product:", productName);
});
}
// trigger product inquiry power automate
function sendProductInquiry(isQucikOrder) {
showLoader();
const endpoint =
"/_api/cloudflow/v1.0/trigger/5f97494d-1ba1-f011-bbd3-6045bd088d91";
/*var data = {};
data["CustomerName"] = selectedAccountLabels.join(",");
data["UserID"] = $("#user-id").text();
data["CustomerID"]= selectedAccounts.join(",");*/
let allProductNames = "";
$(".imgandtxt").each(function() {
let productName = $(this).find("p").text();
allProductNames += productName + ",";
});
// Optionally remove trailing comma and space
allProductNames = allProductNames.replace(/, $/, "");
const data = {
CustomerName: selectedAccountLabels.join(","),
UserID: $("#user-id").text(),
CustomerID: selectedAccounts.join(","),
ProductNames: allProductNames
};
let payload = {};
payload.eventData = JSON.stringify(data);
console.log("Payload type:", typeof payload);
console.log("Flow Endpoint:", endpoint);
shell
.ajaxSafePost({
type: "POST",
url: endpoint,
contentType: "application/json",
data: JSON.stringify(payload),
processData: false,
global: false,
})
.done(function (response) {
hideLoader();
if (isQucikOrder) {
hideModalById("iceOrderDetails");
}
const inquirySuccessModal = new bootstrap.Modal(
document.getElementById("findproduts")
);
inquirySuccessModal.show();
})
.fail(function (xhr, status, error) {
hideLoader();
console.error("Error triggering flow:", {
status: status,
error: error,
responseText: xhr.responseText,
});
showErrorToast("Failed to send inquiry");
});
}
//convert time from UTC to local
function convertUTCToLocal(utcDateString) {
let date = new Date(utcDateString);
let month = date.getMonth() + 1; // 0-based
let day = date.getDate();
let year = date.getFullYear();
// Format MM/DD/YYYY
return `${month}/${day}/${year}`;
}
// common function to show a popup
function showModalById(modalId) {
const modalElement = document.getElementById(modalId);
if (modalElement) {
const modalInstance = new bootstrap.Modal(modalElement);
modalInstance.show();
} else {
console.warn(`Modal with ID '${modalId}' not found`);
}
}
function formatDateToMDYHM(dateInput) {
if (!dateInput) return null;
const date = new Date(dateInput);
let month = date.getMonth() + 1; // Months are 0-indexed
let day = date.getDate();
let year = date.getFullYear();
let hours = date.getHours();
let minutes = date.getMinutes();
let ampm = hours >= 12 ? "PM" : "AM";
hours = hours % 12;
hours = hours ? hours : 12; // 0 becomes 12
minutes = minutes < 10 ? "0" + minutes : minutes;
return `${month}/${day}/${year} ${hours}:${minutes} ${ampm}`;
}
//hide add/remove location in all pages except customer dashboard
// $(document).ready(function () {
// if (window.location.pathname !== "/CP-Customer-Dashboard/") {
// $("#account-box").children().hide();
// }
// else {
// $("#account-box").parents(".header-top").addClass("customer-dashboard-account-box")
// }
// });