Last active
December 3, 2019 18:52
-
-
Save bensoutendijk/c04b96a42bd631fc08d11ff2ce6163a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create and Download Usage Reports for All Websites | |
(function() { | |
const convertDataToCSV = (data) => { | |
let result = ''; | |
let ctr = 0; | |
if (data === null || !data.length) { | |
return null; | |
} | |
columnDelimiter = ','; | |
lineDelimiter = '\n'; | |
const keys = Object.keys(data[0]); | |
result += keys.join(columnDelimiter); | |
result += lineDelimiter; | |
data.forEach((item) => { | |
ctr = 0; | |
keys.forEach((key) => { | |
if (ctr > 0) result += columnDelimiter; | |
result += item[key]; | |
ctr++; | |
}); | |
result += lineDelimiter; | |
}) | |
return result; | |
} | |
const downloadCSV = (csv, filename) => { | |
let data, link; | |
if (csv === null || !csv.length) { | |
return null; | |
} | |
filename = filename || 'export.csv'; | |
if (!csv.match(/^data:text\/csv/i)) { | |
csv = 'data:text/csv;charset=utf-8,' + csv; | |
} | |
data = encodeURI(csv); | |
link = document.createElement('a'); | |
link.setAttribute('href', data); | |
link.setAttribute('download', filename); | |
link.click(); | |
} | |
const urlParams = new URLSearchParams(window.location.search); | |
const fromdate = urlParams.get('fromdate') || new Date(Date.now() - 1000 * 60 * 60 * 24 * 30).toISOString(); | |
const todate = urlParams.get('todate') || new Date().toISOString(); | |
const usageReport = []; | |
let websites; | |
$.ajax(`https://${window.location.host}/api/websites`) | |
.then((data) => { | |
websites = data; | |
return $.when.apply($, websites.map(website => ( | |
$.ajax(`https://us.mouseflow.com/api/websites/${website.id}/stats?fromdate=${fromdate}&todate=${todate}`) | |
.then((data) => { | |
website.stats = data; | |
}) | |
))) | |
}) | |
.then(() => { | |
console.log(websites) | |
for (let index = 0; index < websites.length; index++) { | |
const website = websites[index]; | |
const dates = Object.keys(website.stats.sessionChart); | |
for (let innerIndex = 0; innerIndex < dates.length; innerIndex++) { | |
const date = dates[innerIndex]; | |
usageReport.push({ | |
"Website": website.name, | |
"Website ID": website.id, | |
"Date": new Date(date).toDateString(), | |
"Number of Sessions": website.stats.sessionChart[date], | |
}); | |
} | |
} | |
downloadCSV(convertDataToCSV(usageReport), `mouseflow_usage_report.csv`); | |
}) | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment