var commonSiteObj = {}; commonSiteObj.addLoader = function () { $("#preloader").removeClass("d-none"); } commonSiteObj.hideLoader = function () { $("#preloader").addClass("d-none"); } commonSiteObj.ExportToCSV = function (moduleName, exportAPIURL) { try { commonSiteObj.addLoader(); let radPartner_DomainURL = RADPARTNER_DOMAINURL; let url = radPartner_DomainURL + exportAPIURL; fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json' } }) .then(response => { if (response.ok) { return response.json();//response.blob(); } else { throw new Error('Network response was not ok.'); } }) .then(data => { debugger if (data.success) { let fileName = moduleName + "_" + moment().format('MMDDYYYY_HHmmss') + '.xlsx'; const byteCharacters = atob(data.values); const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); const blob = new Blob([byteArray], { type: 'text/csv' }); const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; a.download = fileName; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); Swal.fire({ icon: 'success', title: 'Success', text: data.resultMessage, timer: 2000 }) } else { Swal.fire({ icon: 'error', title: 'Oops', text: data.errorMessage, timer: 2000 }); } commonSiteObj.hideLoader(); }) .catch(error => console.error('There has been a problem with your fetch operation:', error)) .finally(() => { commonSiteObj.hideLoader(); }); } catch (e) { commonSiteObj.hideLoader(); console.error("[commonSiteObj.ExportToCSV Method: ]" + ex); } } window.onload = function () { let activeTabId = '#profile'; function showTabContent(tabId) { const tabContent = document.querySelector(tabId); if (tabContent) { document.querySelectorAll('.tab-pane').forEach(tab => { tab.classList.remove('show', 'active'); }); tabContent.classList.add('show', 'active'); } } function updateActiveTab(tabId) { const tabLink = document.querySelector(`[data-bs-target="${tabId}"]`); if (tabLink) { document.querySelectorAll('.nav-link').forEach(link => { link.classList.remove('active'); }); tabLink.classList.add('active'); } } document.querySelectorAll('.nav-link').forEach(link => { link.addEventListener('click', () => { const target = link.getAttribute('data-bs-target'); activeTabId = target; updateActiveTab(activeTabId); showTabContent(target); }); }); document.querySelector('#more-tab').addEventListener('click', (event) => { event.preventDefault(); showTabContent(activeTabId); updateActiveTab(activeTabId); }); }; commonSiteObj.reDrawTableWhileResize = function (tableId) { let prevInnerWidth = window.innerWidth; let prevOuterWidth = window.outerWidth; function detectZoomChange() { const currentInnerWidth = window.innerWidth; const currentOuterWidth = window.outerWidth; if (prevInnerWidth !== currentInnerWidth || prevOuterWidth !== currentOuterWidth) { onZoomChange(); prevInnerWidth = currentInnerWidth; prevOuterWidth = currentOuterWidth; } } function onZoomChange() { setTimeout(function () { var table = $(`#${tableId}`).DataTable(); table.columns.adjust(); }, 300); } window.addEventListener('resize', detectZoomChange); } commonSiteObj.reDrawTableWhileSidebarChange = function (table) { $('#nav-toggle').on('click', function () { setTimeout(function () { table.columns.adjust(); }, 300) }); } commonSiteObj.stopHeaderPropagation = function () { $(".filter-header").on("click", function (e) { e.stopPropagation(); }) } commonSiteObj.handleColumnFilterVisibility = function (tableWrapper, cb) { $(document).on("click", "#column-filter-btn", function () { commonSiteObj.addLoader(); setTimeout(() => { const filterHeader = $(`#${tableWrapper} .filter-header`); filterHeader.toggleClass('d-none'); cb(); // Call the DataTables column adjust // Give time for UI update/rendering if needed setTimeout(() => { commonSiteObj.hideLoader(); }, 100); // adjust delay as needed }, 10); // slight delay to allow loader to appear }); }; commonSiteObj.handleColumnFilter = function (thisRef, columnArr, clearBtnId = null, resetCallback) { thisRef.api() .columns(columnArr) .every(function () { let column = this; // Create select element let select = document.createElement('select'); select.setAttribute('multiple', 'multiple'); column.header().replaceChildren(select); // Initialize Select2 $(select).select2({ placeholder: `Select`, width: 'resolve', // Set to resolve to calculate width dynamically dropdownAutoWidth: true, // Enable dropdown auto width }); // Add event listener to recalculate width on open $(select).on('select2:open', function () { $('.select2-search__field').css('width', '100%'); // Ensures the search field width is correct let dropdown = $(select).data('select2').$dropdown; dropdown.find('.select2-results').css('width', 'auto'); }); // Apply listener for user change in value $(select).on('change', function () { // Get the "text" property from each selected data // regex escape the value and store in array var data = $.map($(this).select2('data'), function (value, key) { return value.text ? '^' + $.fn.dataTable.util.escapeRegex(value.text) + '$' : null; }); // If no data selected use "" if (data.length === 0) { data = [""]; } // Join array into string with regex or (|) var val = data.join('|'); // Search for the option(s) selected column .search(val ? val : '', true, false) .draw(); }); // Add list of options column .data() .unique() .sort() .each(function (d, j) { let option = new Option(d, d); $(select).append(option); }); $('.select2-search__field').css('width', '100%'); }); if (clearBtnId) { // Clear filters functionality $(clearBtnId).on('click', function () { if (resetCallback) { resetCallback(); } else { // Reset search for each column and reset Select2 dropdowns commonSiteObj.addLoader(); setTimeout(() => { thisRef.api().columns().every(function (index) { let column = this; column.search(''); // Clear the column filter // Reset the Select2 dropdowns let select = $(column.header()).find('select'); select.val(null).trigger('change'); // Clear the selection in the Select2 // Check if this is the last iteration if (index === thisRef.api().columns().count() - 1) { commonSiteObj.hideLoader(); } }); }, 100); // Redraw the table after clearing the filters thisRef.api().draw(); } }); } } commonSiteObj.updateTableHeightWhileResize = function (tableId, heightToReduce = 0) { function resizeTable() { const height = window.innerHeight - heightToReduce; $(`#${tableId}`).closest('.dt-scroll-body').css({ // 'height': `${height}px`, 'max-height': `${height}px` }); // $(`#${tableId}`).closest('.dt-scroll-body').css('max-height', `${height}px`); }; var resizeTimer; $(window).resize(function () { clearTimeout(resizeTimer); resizeTimer = setTimeout(resizeTable, 100); }); } commonSiteObj.checkIfAllOptionsSelected = function (selector) { try { const config = { theme: 'bootstrap', minimumResultsForSearch: Infinity, closeOnSelect: false, } var allOptions = $(`${selector} option`).map(function () { if (!$(this).is(':disabled')) { return $(this).val(); } }).get(); allOptions = allOptions.filter(n => n !== "0"); const selectableOptions = allOptions.filter(n => n !== "0" && n !== "select-all"); const selectedOptions = $(selector).val()?.filter(n => n !== "select-all"); if (selectableOptions?.length === selectedOptions?.length) { $(selector).select2('destroy').select2(config); $(selector).val(["select-all", ...selectedOptions]).trigger('change'); } } catch (ex) { console.log('checkIfAllOptionsSelected' + ex); } } commonSiteObj.handleSelectAllInSelect2 = function (selector) { $(selector).on('select2:select', function (e) { const dropdown = $(`${selector}`).data('select2').$dropdown; const selectedOption = $(`${selector} option[value="${e.params.data.id}"]`); // Calculate position of the selected option const optionIndex = selectedOption.index(); const itemHeight = dropdown.find('.select2-results__option').outerHeight(); const scrollTop = optionIndex * itemHeight; var allOptions = $(`${selector} option`).map(function () { if (!$(this).is(':disabled')) { return $(this).val(); } }).get(); allOptions = allOptions.filter(n => n !== "0"); if (e.params.data.id === 'select-all') { $(selector).val(allOptions).trigger('change', ['manual']); } else { const selectableOptions = allOptions.filter(n => n !== "0" && n !== "select-all"); const selectedOptions = $(selector).val()?.filter(n => n !== "select-all"); if (selectableOptions?.length === selectedOptions?.length) { $(selector).val(["select-all", ...selectedOptions]).trigger('change', ['manual']); } else { $(selector).val(selectedOptions.filter(n => n !== "select-all")).trigger('change', ['manual']); } } // Close and reopen dropdown to reflect changes $(selector).select2('close'); $(selector).select2('open'); // Scroll to the selected option setTimeout(() => { const selectWrapper = dropdown.find('.select2-results__options') selectWrapper.scrollTop(scrollTop); }, 0); }); $(selector).on('select2:unselect', function (e) { const dropdown = $(`${selector}`).data('select2').$dropdown; const selectedOption = $(`${selector} option[value="${e.params.data.id}"]`); // Calculate position of the selected option const optionIndex = selectedOption.index(); const itemHeight = dropdown.find('.select2-results__option').outerHeight(); const scrollTop = optionIndex * itemHeight; var allOptions = $(`${selector} option`).map(function () { if (!$(this).is(':disabled')) { return $(this).val(); } }).get(); allOptions = allOptions.filter(n => n !== "0"); if (e.params.data.id === 'select-all') { $(selector).val([]).trigger('change', ['manual']); } else { const selectableOptions = allOptions.filter(n => n !== "0" && n !== "select-all"); const selectedOptions = $(selector).val()?.filter(n => n !== "select-all"); if (selectableOptions?.length === selectedOptions?.length) { $(selector).val(["select-all", ...selectedOptions]).trigger('change', ['manual']); } else { $(selector).val(selectedOptions.filter(n => n !== "select-all")).trigger('change', ['manual']); } } // Close and reopen dropdown to reflect changes $(selector).select2('close'); $(selector).select2('open'); // Scroll to the selected option setTimeout(() => { const selectWrapper = dropdown.find('.select2-results__options') selectWrapper.scrollTop(scrollTop); }, 0); }); }