;(function($){"use strict";ips.controller.register('core.admin.stats.overview',{_dateFilters:undefined,_dateFilterQueue:new Set(),set dateFilters(dateFilters){this._dateFilters=dateFilters;this._dateFilterQueue.forEach(cb=>cb());this._dateFilterQueue.clear();},get dateFilters(){if(this._dateFilters){return this._dateFilters;}
return{start:null,end:null,range:null,}},initialize:function(){document.addEventListener('ips:stats.setDateFilters',e=>this.updateDateFilter(e));this.on('change','[data-action="toggleApp"]',this.toggleApp);this.elem.addEventListener('stats.ready',ips.utils.debounce((...args)=>this.blockReady(...args),100));this.url=this.scope.attr('data-url');},dateFiltersKnown(){return new Promise((resolve)=>{if(this._dateFilters){return resolve();}
this._dateFilterQueue.add(resolve);setTimeout(()=>{document.dispatchEvent(new CustomEvent('reloadStatsDateFilters'));})});},async blockReady(e,data){await this.dateFiltersKnown();$(e.target).trigger('stats.loadBlock',{dateFilters:this.dateFilters,url:this.url});},toggleApp:function(){var enabledApps=Array.from(this.scope.find('[data-action="toggleApp"]:checked')).map((app)=>{return app.getAttribute('data-toggledApp')});var disabledApps=Array.from(this.scope.find('[data-action="toggleApp"]:not( :checked )')).map((app)=>{return app.getAttribute('data-toggledApp');});if(document.startViewTransition){document.startViewTransition(()=>this.toggleTiles(enabledApps));}else{this.toggleTiles(enabledApps);}
ips.utils.cookie.set('overviewExcludedApps',JSON.stringify(disabledApps),true);},toggleTiles:function(enabledApps=[]){this.scope.find('.cStatTile[data-app]').each(function(){var tile=$(this);if(tile.is('[hidden]')&&enabledApps.indexOf($(this).attr('data-app'))!==-1){tile.prop('hidden',false);}else if(enabledApps.indexOf($(this).attr('data-app'))===-1){tile.prop('hidden',true);}});},updateDateFilter:function(e){this.dateFilters={...e.detail.dateFilters};this.triggerOn('core.admin.stats.overviewBlock','stats.loadBlock',{dateFilters:e.detail.dateFilters,url:this.url});this.triggerOn('core.admin.stats.nodeFilters','stats.setDateFilters',{dateFilters:e.detail.dateFilters,url:this.url});},});}(jQuery));;
;(function($){"use strict";ips.controller.register('core.admin.stats.liveDateFilter',{dateFilters:{'start':null,'end':null,'range':null},initialize(){this.on('submit',this.updateDateFilter);this.on('change','[name="predate"]',this.changeDateField);this.on('click','[data-action="cancelDateRange"]',this.cancelDateRange);document.addEventListener('reloadStatsDateFilters',e=>this.resendDateFilters(e));this.dateFilters.range=this.elem.dataset.defaultrange;this.elem.querySelector('[name="predate"]')?.dispatchEvent(new CustomEvent('change',{bubbles:true,detail:{submit:false}}));},resendDateFilters(){const url=new URL(window.location.href);let days=parseInt(this.dateFilters.range?.toString?.()||'NaN');if(Number.isInteger(days)&&days>=0){url.updateSearchParams({param:'predate',value:days.toString()});}else{['start','end'].forEach(prop=>{let ts=null;if(typeof this.dateFilters[prop]==='string'){try{ts=Math.round((new Date(this.dateFilters[prop])).getTime()/1000);}catch(e){}}
url.updateSearchParams({param:'predate',value:null});url.updateSearchParams({param:`date[${prop}]`,value:ts});});}
if(url.toString()!==window.location.href){ips.utils.history.replaceState({},'stats.liveDateFilter',url.toString());}
this.elem.dispatchEvent(new CustomEvent('ips:stats.setDateFilters',{bubbles:true,detail:{dateFilters:this.dateFilters}}));},cancelDateRange(e){e.preventDefault();const select=this.elem.querySelector('select[name="predate"]');select.value=this.elem.dataset.defaultrange;select.dispatchEvent(new CustomEvent('change',{bubbles:true}));},changeDateField(e){const select=e.target;if(!(select instanceof HTMLSelectElement)||!select?.matches?.('select[name="predate"]')){return;}
const button=this.elem.querySelectorAll('.cStatsFilters button');if(Number(select.value)===-1){select.ipsHide();button.ipsShow();}else{this.elem.dataset.defaultrange=select.value;select.ipsShow();button.ipsHide();if(e?.detail?.submit!==false){select.closest('form')?.dispatchEvent(new CustomEvent('submit'));}}},updateDateFilter(e){e.preventDefault();e.stopPropagation();this.dateFilters={'start':null,'end':null,'range':this.elem.querySelector('[name="predate"]').value};if(Number(this.dateFilters.range)===-1){this.dateFilters.start=this.elem.querySelector('[name="date[start]"]').value;this.dateFilters.end=this.elem.querySelector('[name="date[end]"]').value;}
this.resendDateFilters();this.actuallySubmitForm();},async actuallySubmitForm(){const url=new URL(this.elem.getAttribute('action'),window.location.href);if(!url.searchParams.has('report_id')||url.searchParams.get('app')!=='core'||url.searchParams.get('module')!=='overview'||url.searchParams.get('controller')!=='mycharts'){return;}
const values=Object.fromEntries([...(new FormData(this.elem)).entries()]);const response=await ips.fetch(url.toString(),{method:'post',data:values,});console.log('got form submission response',response);return response;}});}(jQuery));;
;(function($){"use strict";ips.controller.register('core.admin.stats.filtering',{initialize:function(){this.on('click','[data-role="toggleGroupFilter"]',this.toggleGroupFilter);if($('#elGroupFilter').attr('data-hasGroupFilters')=='true'){$('#elGroupFilter').show();}},toggleGroupFilter:function(e){e.preventDefault();if($('#elGroupFilter').is(':visible')){$('#elGroupFilter').find('input[type="checkbox"]').prop('checked',true);$('#elGroupFilter').slideUp();}
else
{$('#elGroupFilter').slideDown();}}});}(jQuery));;
;(function($){"use strict";ips.controller.register('core.admin.stats.overviewBlock',{_lastURL:null,initialize(){this.on('stats.loadBlock',this.loadBlock);$(document).on('stats.nodeFilters',(...args)=>this.loadBlock(...args));this.refresh=null;this.loaded=false;this.currentCounts=[];this.url=null;this.block=this.elem.dataset.block;this.subblock=this.elem.dataset.subblock;this.savedstatid=this.elem.dataset.savedstatid;this.refreshInterval=this.elem.dataset.refresh?parseInt(this.elem.dataset.refresh):false;this.elem.dispatchEvent(new CustomEvent('stats.ready',{bubbles:true}));this.elem.addEventListener('submit',e=>this.handleSubmit(e),{capture:true});this.elem.querySelector('[data-role="removeBlock"]')?.addEventListener('click',e=>this.deleteBlock(e));},deleteBlock(e){e?.preventDefault();ips.ui.alert.show({message:ips.getString('statsreports_delete_confirm'),type:'confirm',callbacks:{ok:()=>{const url=new URL(window.location.protocol+ips.getSetting('baseURL'),window.location.origin);url.pathname+=url.pathname.endsWith('/')?"admin/":"/admin/";url.searchParams.set('app','core');url.searchParams.set('module','overview');url.searchParams.set('controller','mycharts');url.searchParams.set('do','deleteBlock');url.searchParams.set('saved_block_id',this.savedstatid);url.searchParams.set('csrfKey',ips.getSetting('csrfKey'));window.location.href=url.toString();}}});},async handleSubmit(e){e.preventDefault();e.stopPropagation();const form=e.target;const dropdown=form.closest('i-dropdown[data-dropdown-role]');if(dropdown){dropdown.createContentElement();}
if(dropdown?.dataset.dropdownRole==='saveReport'){const data=Object.fromEntries([...(new FormData(form)).entries()]);const url=(new URL(form.action,window.location.href)).toString();dropdown.contentElement.classList.add('ipsLoading','ipsLoading--small');try{const response=await ips.fetch(url,{method:"post",data});if(typeof response!=='object'||response.message!=='ok'){const err=new Error();err.jqxhr=jqxhr;throw err;}
if(this.savedstatid&&response.title&&this.elem.querySelector(`[data-role="stat_title"]`)){this.elem.querySelector('[data-role="stat_title"]').innerText=response.title;}}catch(e){if(e.jqxhr?.responseText&&dropdown.contentElement){dropdown.contentElement.innerHTML=e.jqxhr?.responseText;return;}
if(e.jqxhr?.responseText||e.jqxhr?.responseJSON){ips.ui.alert.show({message:e.jqxhr.responseText||e.jqxhr?.responseJSON});return;}
ips.ui.alert.show({message:ips.getString('unexpected_error')});return;}}else if(dropdown?.dataset.dropdownRole==='filterForm'){this.elem.dataset.nodefilter=form.querySelector('[data-role="nodeValue"]')?.value;this.currentCounts=null;}
if(this.url){this.url=this.rebuildURL();this._lastURL=this.url;await this.fetchUpdate();}else{this.elem.dispatchEvent(new CustomEvent('stats.ready',{bubbles:true}));}
dropdown?.hidePopover();if(dropdown?.dataset.dropdownRole==='saveReport'){ips.ui.flashMsg.show(ips.getString('saved'));await dropdown.resetRemoteContent();}},getCounts(elem){return[...$(elem).get(0).querySelectorAll('[data-number]')].map(el=>parseInt(el.dataset.number));},startInterval(){if(!this.refreshInterval||!this.url){return;}
clearInterval(this.refresh);this.refresh=setInterval(()=>this.fetchUpdate(),this.refreshInterval*1000);},async fetchUpdate(){const response=await ips.fetch(this.url,{type:'get'});let identifiedDifference=!this.currentCounts;const counts=this.getCounts((new DOMParser()).parseFromString(response,'text/html').body);if(!identifiedDifference){if(counts.length!==this.currentCounts.length){identifiedDifference=true;}else{for(let i=0;i<counts.length;i++){if(counts[i]!==this.currentCounts[i]){identifiedDifference=true;break;}}}}
if(identifiedDifference){this.elem.classList.add('cStatTile--updated');let contentContainer=this.elem.querySelector('[data-role="statBlockContent"]');if(contentContainer){contentContainer.innerHTML="<div>"+response+"</div>";}
this.currentCounts=counts;setTimeout(()=>this.elem.classList.remove('cStatTile--updated'),2200);$(document).trigger('contentChange',[this.scope]);}else{Debug.log("No change in values in "+this.block);}},rebuildURL(data){if(!data){const currentURL=new URL(this.url||"",location.href);data={url:this.url,dateFilters:{range:currentURL.searchParams.get('range'),start:currentURL.searchParams.get('start'),end:currentURL.searchParams.get('end'),}}}
let url=new URL(data.url,location.href);url.updateSearchParams('blockKey',this.block);url.updateSearchParams('subblock',this.subblock||null);const range=![0,-1,Number.NaN].includes(parseInt(data?.dateFilters?.range))?data.dateFilters.range.toString():null
url.updateSearchParams('range',range);url.updateSearchParams('start',(!range&&data?.dateFilters?.start?.toString())||null);url.updateSearchParams('end',(!range&&data?.dateFilters?.end?.toString())||null);url.updateSearchParams('nodes',this.elem.dataset.nodefilter||null);return url.toString();},async loadBlock(e,data){if((data.blockToRefresh!==undefined)&&(data.blockToRefresh!==this.block||data.subblockToRefresh!==this.subblock)){Debug.log("Skipping because "+data.blockToRefresh+" does not match "+this.block+" or "+data.subblockToRefresh+" does not match "+this.subblock);return;}
if(!data.url){throw new Error(`No URL provided to load this block`);}
this._lastURL=this.url;this.url=this.rebuildURL(data);if(this.url===this._lastURL){return;}
clearInterval(this.refresh);if(this.loaded){this.loaded=false;this.scope.removeClass('cStatTile--loaded').find('.cStatTile__body').addClass('ipsLoading').end().find('[data-role="statBlockContent"]').hide().html('');}
const response=await ips.fetch(this.url,{type:'get'})
this.scope.addClass('cStatTile--loaded').find('.cStatTile__body').removeClass('ipsLoading').end().find('[data-role="statBlockContent"]').hide().html(response);this.scope.find('[data-role="statBlockContent"]').fadeIn('fast');this.loaded=true;this.currentCounts=this.getCounts(this.scope);this.startInterval();$(document).trigger('contentChange',[this.scope]);}});}(jQuery));;
;(function($,_){"use strict";ips.controller.register("core.admin.stats.downloadButton",{initialize(){const update=()=>{const url=new URL(this.scope.attr('href'),window.location.origin);const locationParams=new URLSearchParams(window.location.search);url.updateSearchParams('report_id',locationParams.get('report_id')||'0');url.updateSearchParams('tab',locationParams.get('tab')||'charts');const rangeVal=document.querySelector(`[data-controller*="core.admin.stats.overview"] .cStatsFilters select[name="predate"]`)?.value||'7';if(rangeVal&&parseInt(rangeVal)===-1){url.updateSearchParams({param:'range',value:null});let startInput=document.querySelector(`[data-controller*="core.admin.stats.overview"] .cStatsFilters #dateFilterInputs input[name="date[start]"]`);let endInput=document.querySelector(`[data-controller*="core.admin.stats.overview"] .cStatsFilters #dateFilterInputs input[name="date[end]"]`);if(startInput.valueAsNumber&&endInput.valueAsNumber){url.updateSearchParams('range[start]',Math.round(startInput.valueAsNumber/1000).toString());url.updateSearchParams('range[end]',Math.round((endInput.valueAsNumber||Date.now())/1000).toString());}}else{console.log('updating range; removing start and end')
url.updateSearchParams({params:{'range[start]':null,'range[end]':null,}});url.updateSearchParams("range",rangeVal);}
this.scope.attr('href',url.toString());const menuSelectorLink=this.scope.get(0).closest('[data-controller*="core.admin.core.pageActions"]')?.querySelector('[data-role="reportSelector"]');const menuSelector=menuSelectorLink?.getAttribute('id')&&document.querySelector(`.ipsMenu#${menuSelectorLink?.getAttribute("id")}_menu`);menuSelector?.querySelectorAll('.ipsMenu_item a').forEach(link=>{const linkUrl=new URL(link.getAttribute('href'),window.location.href);linkUrl.updateSearchParams({param:'tab',value:url.searchParams.get('tab')||null});link.setAttribute('href',linkUrl.toString());});};window.addEventListener("historychange",update);document.addEventListener('input',e=>{if(e.target.matches('[data-controller*="core.admin.stats.overview"] .cStatsFilters :not([data-role="dateFilterInputs"] *)')){if(e.target.matches(`select[name="predate"]`)&&parseInt(e.target.value)===-1){Debug.log(`Not updating because the date isn't updated`);return;}
setTimeout(()=>{update();})}},{capture:true});document.addEventListener('submit',e=>{if(e.target instanceof HTMLFormElement&&e.target.matches(`[data-role="dateFilter"]`)){setTimeout(()=>update());}},{capture:true});update();}});}(jQuery));;