let selectedAccounts = getOrInitSessionArray('selectedAccounts'); let selectedAccountLabels = getOrInitSessionArray('selectedAccountLabels'); let userAccountDetailsArray = []; let isOrderGridLoading = false; let debounceTimer; let uniqueAccounts = []; let bulkUpdating = false; $(document).ready(function () { if(window.location.pathname.startsWith('/AP-')) { showLoader(); window.location.pathname === "/AP-Admin-Dashboard/" ? checkAdminDashboardAccess(): checkSinglePageAccess(); } if(window.location.pathname === "/CP-Customer-Dashboard/") { showLoader(); CheckUserCaseOrderCreation(); } }) // $(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]} +${count - 1}`; $btn.html(display) .attr("title", selectedAccountLabels.join(", ")) .addClass("multi-options"); } } function showLoader() { $("#loader").addClass("active"); } function hideLoader() { $("#loader").removeClass("active"); } function showErrorToast(content) { const $toastEl = $("#error-toast"); $("#error-toast-text").text(content); // Recreate instance with desired options to ensure autohide settings apply const existing = bootstrap.Toast.getInstance($toastEl[0]); if (existing) existing.dispose(); const toastInstance = new bootstrap.Toast($toastEl[0], { autohide: true, delay: 8000 }); toastInstance.show(); } function showSuccessToast(content) { const $toastEl = $("#success-toast"); $("#success-toast-text").text(content); const existing = bootstrap.Toast.getInstance($toastEl[0]); if (existing) existing.dispose(); const toastInstance = new bootstrap.Toast($toastEl[0], { autohide: true, delay: 8000 }); toastInstance.show(); } // 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 // Update account GUID cache when selectedAccounts changes if (typeof updateAccountGUIDCache === 'function') { await updateAccountGUIDCache(); } // 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"); // Reset body overflow:hidden Bootstrap might have added 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(async function (response) { hideLoader(); if (isQucikOrder) { hideModalById("iceOrderDetails"); } const inquirySuccessModal = new bootstrap.Modal( document.getElementById("findproduts") ); await ShowPopupMessage("CP-Product-Inquiry","#productInquiryModalContent"); 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") // } // }); async function checkSinglePageAccess() { const currentContactId = $('#user-id').text().trim(); const currentPage = $('#current-page-id').val().trim(); await processSinglePageAccess(currentContactId, currentPage); } async function checkAdminDashboardAccess() { const currentContactId = $('#user-id').text().trim(); await setAdminDashboardNavigationAccess(currentContactId); initAdminDashboard(); return; } function getUserFunctions(currentContactId) { showLoader(); return apiService.getItemById("contacts", currentContactId) .then(contact => { if (!contact.emailaddress1) { throw new Error("Contact has no email."); } const filter = `?$filter=internalemailaddress eq '${contact.emailaddress1}'`; return apiService.getItems("systemusers" + filter); }) .then(users => { if (!users.value?.length) { throw new Error("Cannot find related systemuser."); } const user = users.value[0]; const filter = `$filter=cr4e9_admincontactemail eq '${user.internalemailaddress}'`; return apiService.getItems("cr4e9_adminrolecontactses?$select=cr4e9_admincontactemail,_cr4e9_adminrolelookup_value&" + filter); }) .then(admins => { if (!admins.value?.length) { throw new Error("No matching admin contact found."); } const admin = admins.value[0]; const filter = `$filter=cr4e9_businessrolename eq '${admin["_cr4e9_adminrolelookup_value@OData.Community.Display.V1.FormattedValue"]}'`; // Return the admin role data return apiService.getItems("cr4e9_rolemappingconfigurations?$select=cr4e9_businessrolename,cr4e9_functions&" + filter); }) .catch(error => { hideLoader(); console.error("Error fetching user functions:", error); showErrorToast("Failed to validate user."); return null; }); } function processSinglePageAccess(currentContactId, currentPage) { return new Promise((resolve, reject) => { getUserFunctions(currentContactId) .then(adminRoles => { if (!adminRoles || !adminRoles.value?.length) { noPageAccess(); reject(`Access denied`); return; } const role = adminRoles.value[0]; if (!role.cr4e9_functions?.length || !checkCurrentPageAccess(role.cr4e9_functions, currentPage)) { noPageAccess(); reject(`Access denied`); } else { hideLoader(); resolve(true); } }) .catch(error => { console.error("Error in processPageAccess:", error); noPageAccess(); reject(`Access denied`); }); }); } function checkCurrentPageAccess(functionsString, currentPage) { //get Function-to-Page mapping const pageMapping = getPageMapping(); const userFunctions = functionsString.split(',').map(fn => fn.trim()); // Loop through user functions and check if current page URL exists in mapping for (const fn of userFunctions) { const urls = pageMapping[fn]; if (urls && urls.includes(currentPage)) { return true; // Access allowed } } return false; // Access denied } function setAdminDashboardNavigationAccess(currentContactId) { return new Promise((resolve, reject) => { getUserFunctions(currentContactId) .then(adminRoles => { if (!adminRoles || !adminRoles.value?.length) { noPageAccess(); reject(`Access denied`); } const role = adminRoles.value[0]; if (!role.cr4e9_functions?.length) { noPageAccess(); reject(`Access denied`); } else { applyUserAccessRestrictions(role.cr4e9_functions); resolve(true); } }) .catch(error => { console.error("Error in processPageAccess:", error); noPageAccess(); reject(`Error while getting adminRoles: ${error}`); }); }); } function applyUserAccessRestrictions(functionsString) { //get Function-to-Page mapping const pageMapping = getPageMapping(); const userFunctions = functionsString.split(',').map(fn => fn.trim()); const userAllowedPages = userFunctions.flatMap(key => pageMapping[key]); let URLs = document.getElementsByClassName('admin-access-link'); Array.from(URLs).forEach((each) => { let href = each.href.substring(window.location.origin.length); // 1. If href ends with "#", remove it if (href.endsWith("#")) { href = href.slice(0, -1); } // 2. If href ends with "/", leave it else if (href.endsWith("/")) { // do nothing } // 3. If href ends with an alphabet, add "/" else if (/[a-zA-Z]$/.test(href)) { href += "/"; } // Check if href is NOT in user allowed pages if (!userAllowedPages.includes(href)) { // Remove the visibility of the parent element to remove access each.parentElement.style.display = 'none'; // Disable the element visually each.classList.add('disabled'); // Remove the href so it can't be clicked each.removeAttribute('href'); } }); document.getElementById('admin-modules').style.display = 'flex'; hideLoader(); return; } function noPageAccess() { hideLoader(); console.log("Access Denied"); //window.location.href = "/access-denied"; // redirect return; } function getPageMapping() { //Function to Page mapping const pageMapping = { 'Customer User Management': ['/AP-Customer-Management/', '/AP-Inactive-User/', '/AP-Deactivation-Requests/', '/AP-New-User-Invitation/', '/AP-Pop-up-Messages/'], 'Distributor User Management': ['/AP-Distributor-User-Management/'], 'Closing Service/work orders': [], 'Inventory On Arrival': ['/AP-Inventory-On-Arrival/'], 'Production OEE': ['/AP-Production-OEE/'], 'Inventory Counts': ['/AP-Inventory-Counts-History/', '/AP-Inventory-Counts/', '/AP-Inventory-Journal-History/', '/AP-Inventory-Journal/'], 'Inventory Transfer': ['/AP-Inventory-Transfer/', '/AP-Inventory-Adjustment/', '/AP-Inventory-Journal-History/', '/AP-Inventory-Journal/'], 'QuickBooks management': ['/AP-QuickBooks-Management/'], 'Help Hub Management': ['/AP-Help-Hub/', '/AP-Help-Files/'], 'Product Image Management': ['/AP-Product-Image-Management/'], 'Ticket Management': ['/AP-Ticket-Management/', '/AP-Bulk-Ticket/'], 'Notification Management': ['/AP-Notification-Management/'], 'Reports': [], 'Manual Ticket/History': ['/AP-Ticket-Updates-History/'] } return pageMapping; } //Common function for in app alert message async function ShowPopupMessage(popupId, targetPopup, dynamicValues = {}) { try { const data = await apiService.getItems( `cr4e9_inapppopupses?$select=cr4e9_popuptitle,createdon,cr4e9_popuptext,cr4e9_popupvariables,cr4e9_inapppopupsid&$filter=cr4e9_popupid eq '${popupId}'` ); if (!data || data.value.length === 0) { console.warn("No popup data found."); return; } const element = data.value[0]; const popup = { title: element.cr4e9_popuptitle ?? "", content: element.cr4e9_popuptext ?? "", variables: JSON.parse(element.cr4e9_popupvariables || "[]") }; let html = popup.content; const loopStart = "{loopStart}"; const loopEnd = "{loopEnd}"; if (html.includes(loopStart) && html.includes(loopEnd)) { const startIndex = html.indexOf(loopStart); const endIndex = html.indexOf(loopEnd); const loopTemplate = html.substring(startIndex + loopStart.length, endIndex); let loopHtml = ""; // Expect `dynamicValues.loopItems` to hold an array if (Array.isArray(dynamicValues.loopItems)) { dynamicValues.loopItems.forEach(item => { let row = loopTemplate; // Replace all {{vars}} inside the loop Object.keys(item).forEach(key => { const regex = new RegExp(`{{\\s*${key}\\s*}}`, "g"); row = row.replace(regex, item[key] ?? ""); }); loopHtml += row; }); } // Replace the loop block html = html.substring(0, startIndex) + loopHtml + html.substring(endIndex + loopEnd.length); } if (popup.variables.length > 0) { popup.variables.forEach(variableName => { const value = dynamicValues[variableName] || ""; const regex = new RegExp(`{{\\s*${variableName}\\s*}}`, "g"); html = html.replace(regex, value); }); } $(targetPopup).html(`

    ${popup.title}

    ${html}
    `); } catch (error) { console.error("Pop-up data Error:", error); } } $(document).on("click", "#privacy-policy", async function () { const modal = document.getElementById("privacyPolicyInnerModal"); if (modal) { const privacyPolicyModal = new bootstrap.Modal(modal); await ShowPopupMessage("Privacy-Policy", "#privacyPolicyModalContent"); privacyPolicyModal.show(); } }); $('#btn-close-error-toast').on('click', function () { const toast = bootstrap.Toast.getOrCreateInstance($('#error-toast')[0]); toast.hide(); }); $('#btn-close-success-toast').on('click', function () { const toast = bootstrap.Toast.getOrCreateInstance($('#success-toast')[0]); toast.hide(); }); async function CheckUserCaseOrderCreation() { const currentContactId = $('#user-id').text().trim(); try { const contact = await apiService.getItemById("contacts", currentContactId); hideLoader(); if (!contact) { console.error("Contact not found."); return; } if (!contact.cr4e9_ordercreationenabled && contact.cr4e9_ordercreationenabled !== null) { // Quick Ice Order Button const quickOrderBtn = $('#quickIceOrderBtn'); quickOrderBtn.addClass('disabled') .css('pointer-events', 'none') .attr('aria-disabled', 'true') .removeAttr('data-bs-toggle') .removeAttr('href'); // Custom Order Button const customOrderBtn = $('#place-custom-order'); customOrderBtn.addClass('disabled') .css('pointer-events', 'none') .attr('aria-disabled', 'true') .removeAttr('data-bs-toggle') .removeAttr('href'); // Disable card UI $('#orderIceCard').addClass('order-disabled'); } if (!contact.cr4e9_casecreationenabled && contact.cr4e9_casecreationenabled !== null) { const caseBtn = $('#btn-submit-ticket'); caseBtn.addClass('disabled') .css('pointer-events', 'none') .attr('aria-disabled', 'true') .removeAttr('data-bs-toggle') .removeAttr('href'); // Correct selector $('#equipmentMainCard').addClass('equipment-disabled'); } } catch (err) { hideLoader(); console.error("Error in CheckUserCaseOrderCreation:", err); } } // Medallia async function setMedalliaParams() { if (window.KAMPYLE_ONSITE_SDK && typeof window.KAMPYLE_ONSITE_SDK.updatePageView === 'function') { window.KAMPYLE_ONSITE_SDK.updatePageView(); } window.dataLayer = window.dataLayer || []; try { const data = await fetchAccounts(); const accounts = data?.value ?? []; // Build a single aggregated object const combinedParams = { AXCustomerNumber: accounts.map(i => i?.accountnumber ?? "").join(","), ChainCode: accounts.map(i => i?.ri_chaincode ?? "").join(","), CustomerContact_Email: accounts.map(i => i?.ri_email ?? "").join(","), CustomerContact_Phone: accounts.map(i => i?.telephone1 ?? "").join(","), CustomerGroup: accounts.map(i => i?.msdyn_customergroupid?.msdyn_description ?? "").join(","), CustomerName: accounts.map(i => i?.name ?? "").join(","), DeliveryBU: accounts.map(i => i?.ri_deliverybu?.ri_name ?? "").join(","), DeliveryManagementAccount: accounts.map(i => i?.ri_deliverymanagementno?.ri_description ?? "").join(","), DeliveryManagementNumber: accounts.map(i => i?.ri_deliverymanagementno?.ri_name ?? "").join(","), ServiceHub: accounts.map(i => i?.ri_servicebuid ?? "").join(","), StoreNumber: accounts.map(i => i?.ri_storenumber ?? "").join(","), TTMRevenue: accounts.map(i => i?.ri_ttmsales ?? "").join(","), TypeofDelivery: accounts.map(i => i?.description ?? "").join(","), isProduction: 0, // constant Segment: accounts.map(i => i?.ri_segmentid ?? "").join(",") }; // ✅ Check before adding if (!isDuplicateInDataLayer(combinedParams)) { dataLayer.push(combinedParams); } } catch (error) { console.error("Error loading products:", error); } } async function fetchAccounts() { const accountFilter = `(${selectedAccounts.map(acc => `accountnumber eq '${acc}'`).join(" or ")})`; const baseUrl = "accounts?$select=accountnumber,ri_chaincode,ri_email,telephone1,name,ri_servicebuid,ri_storenumber,ri_ttmsales,ri_routetype,ri_segmentid,description" + "&$expand=msdyn_customergroupid($select=msdyn_description),ri_deliverymanagementno($select=ri_name,ri_description),ri_deliverybu($select=ri_name)" + `&$filter=${accountFilter}`; const finalUrl = `${baseUrl}`; return await apiService.getItems(finalUrl); } function isDuplicateInDataLayer(obj) { return window.dataLayer.some(entry => typeof entry === "object" && JSON.stringify(entry) === JSON.stringify(obj) ); }