Skip to content

Instantly share code, notes, and snippets.

@bensoutendijk
Last active December 3, 2019 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bensoutendijk/c04b96a42bd631fc08d11ff2ce6163a6 to your computer and use it in GitHub Desktop.
Save bensoutendijk/c04b96a42bd631fc08d11ff2ce6163a6 to your computer and use it in GitHub Desktop.
// 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