You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

666 lines
33 KiB

var dash_byuser_id = app.get_vars().dashboard.byuser_id,
dash_alldata_id = app.get_vars().dashboard.alldata_id,
dash_baseurl = app.get_vars().baseurl,
dash_client_id = app.get_vars().dashboard.client_id,
dash_users = app.get_vars().dashboard.users
;
var dashboard = (function ($, window, jQuery) {
var _vars_ = {};
return {
"set_vars": function (options) {
$.extend(_vars_, options || {});
},
"get_vars" : function(){
return _vars_;
},
"_query" : {
//- Total visitors
"total_visitors" : function(ids, start, end){
gapi.client.analytics.data.ga.get({
'ids': ids,
'start-date': start.format('YYYY-MM-DD'),
'end-date': end.format('YYYY-MM-DD'),
'metrics': 'ga:users'
})
.then(function(response) {
$("#total_visitors").text(response.result.totalsForAllResults["ga:users"]);
})
.then(null, function(err) {
// Log any errors.
console.log(err);
});
},
//- Connection time + average connection time
"total_connection_time" : function(ids, start, end) {
gapi.client.analytics.data.ga.get({
'ids': ids,
'start-date': start.format('YYYY-MM-DD'),
'end-date': end.format('YYYY-MM-DD'),
'metrics': 'ga:sessionDuration,ga:avgSessionDuration',
'dimensions' : 'ga:sessionDurationBucket'
})
.then(function(response) {
//measured in seconds
var sessionDuration = parseFloat(response.result.totalsForAllResults["ga:sessionDuration"]);
var avgSessionDuration = parseFloat(response.result.totalsForAllResults["ga:avgSessionDuration"]);
$("#connection_time").text(moment().startOf('day').seconds(sessionDuration).format('HH:mm:ss'));
$("#avg_connection_time").text(moment().startOf('day').seconds(avgSessionDuration).format('HH:mm:ss'));
})
.then(null, function(err) {
// Log any errors.
console.log(err);
});
},
//- Frequency: number of connections / day, per week, per month
"total_connection" : {
"_chart" : function(ids, start, end, dimension) {
var ga_query = {
'ids': ids,
'start-date': start.format('YYYY-MM-DD'),
'end-date': end.format('YYYY-MM-DD'),
'metrics': 'ga:users',
'dimensions': dimension
};
if(dimension.indexOf("month") != -1){ga_query["sort"] = 'ga:year';}
else if(dimension.indexOf("day") != -1){ga_query["sort"] = 'ga:date';}
gapi.client.analytics.data.ga.get(ga_query)
.then(function(response) {
google.charts.setOnLoadCallback(drawLineChart);
function drawLineChart() {
var rows = dashboard._query.total_connection._data(response);
var data = new google.visualization.DataTable();
data.addColumn('string', "");
data.addColumn('number', dash_users);
data.addRows(rows);
var options = {
selectionMode : 'multiple',
aggregationTarget: 'category',
pointsVisible: true,
pointSize : 5.5,
colors: ['#058dc7'],
legend: { position: 'top', textStyle: { fontSize: 12 } },
hAxis: { textPosition: 'out', textStyle: { fontSize: 10}, slantedText: false,slantedTextAngle: 45},
vAxis: { baselineColor: '#E6E9ED', textPosition: 'in', textStyle: { fontSize: 11}, gridlines: {color : "#E6E9ED"} },
chartArea: { left: -5, top: 25, width: '100%', opacity: 0.1},
height:360,
series: { 0: { lineWidth: 3.5 } }
};
var chart = new google.visualization.LineChart(document.getElementById('total_connection'));
chart.draw(data, options);
}
})
.then(null, function(err) {
// Log any errors.
console.log(err);
});
},
"_data" : function(response) {
if((response.result.query.dimensions).indexOf("day") != -1) {
return dashboard._query.total_connection._by_day(response);
} else if((response.result.query.dimensions).indexOf("Week") != -1) {
return dashboard._query.total_connection._by_week(response);
} else if((response.result.query.dimensions).indexOf("month") != -1) {
return dashboard._query.total_connection._by_month(response);
} else {
return [];
}
},
//daily report : Friday 20 January 2017 = 'dimensions': 'ga:date'
"_by_day" : function(response) {
var rows = new Array, index = 0;
var a = moment(response.result.query["start-date"]);
if(response.result.rows) {
var b = moment(response.result.query["end-date"]);
b.add(1, 'days');
for (var m = a; m.isBefore(b); m.add(1, 'days')) {
if (typeof response.result.rows[index] != "undefined") {
rows.push([m.format('ddd D MMM YYYY'), parseInt(response.result.rows[index][2])]);
}
index++;
}
} else {
rows.push([a.format('ddd D MMM YYYY'), 0]);
}
return rows;
},
//weekly report : Set dates from "DD / MM / YYYY to DD / MM / YYYY" (from Monday to Sunday)
"_by_week" : function(response) {
var checkIndex="", windex = {}; year_month_day = "", week_day_start="", rows = new Array;
$.map(response.result.rows, function(arr,index){
if(index==0){
checkIndex = arr[2];
year_month_day=dashboard._query.total_connection.custom_weeklyreport._weeks(moment(arr[2].substr(0,4)+"-"+arr[2].substr(4,2)+"-01", 'YYYY-MM-DD'));
windex = dashboard._query.total_connection.custom_weeklyreport.search_by_week_number(year_month_day, parseInt(response.result.query["start-date"].substr(8)), parseInt(response.result.query["start-date"].substr(8)));
}
else if(checkIndex == arr[2]) {
windex = dashboard._query.total_connection.custom_weeklyreport.search_by_week_number(year_month_day, windex.nextdate, "");
} else {
checkIndex = arr[2];
year_month_day=dashboard._query.total_connection.custom_weeklyreport._weeks(moment(arr[2].substr(0,4)+"-"+arr[2].substr(4,2)+"-01", 'YYYY-MM-DD'));
windex = dashboard._query.total_connection.custom_weeklyreport.search_by_week_number(year_month_day, "start", "");
}
//check for last entry
if(response.result.totalResults-1 == index) {
var _d = (windex.index).split(" au "),
append = parseInt(response.result.query["end-date"].substr(8)),
_e = _d[1].split("/");
windex.index = _d[0]+" au "+((append < 10)?"0"+append:append)+"/"+_e[1]+"/"+_e[2];
}
rows.push([windex.index, parseInt(arr[3])]);
});
return rows;
},
//monthly report : Put "month YYYY" = 'dimensions': 'ga:date,ga:month,ga:year'
"_by_month" : function(response) {
var rows = new Array, monthsNameFr = 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_');
$.map(response.result.rows, function(arr,index){
rows.push([monthsNameFr[parseInt(arr[0])-1]+" "+arr[1], parseInt(arr[2])]);
});
return rows;
},
"_arrange_dates" : function(weekdate) {
return weekdate.substr(6)+"/"+weekdate.substr(4,2)+"/"+weekdate.substr(0,4)
},
"custom_weeklyreport" : {
"search_by_week_number" : function(dates, searchdate, append){
var new_date = {}, dateslength = (dates.length-1);
$.map(dates, function(val, index){
var _dr = val[0].split("-");
if(searchdate=="start" && index==0){
new_date.index = val[1];
new_date.nextdate = (dateslength == index)?"start":parseInt(_dr[1])+1;
return false;
}
else if(searchdate >= parseInt(_dr[0]) && searchdate <= parseInt(_dr[1])) {
if(append!=""){
var _d = val[1].split(" au "),
_e = _d[0].split("/");
new_date.index = ((append < 10)?"0"+append:append)+"/"+_e[1]+"/"+_e[2]+" au "+_d[1];
} else {
new_date.index = val[1];
}
new_date.nextdate = (dateslength == index)?"start":parseInt(_dr[1])+1;
return false;
}
});
return new_date;
},
"sameMonth" : function (a, b, other) {
if (a.month() !== b.month()) {
return other;
}
return a.date();
},
"_weeks" : function (m) {
var lastOfMonth = m.clone().endOf('month'),
lastOfMonthDate = lastOfMonth.date(),
firstOfMonth = m.clone().startOf('month'),
currentWeek = firstOfMonth.clone().day(0),
output = [],
count = 0,
startOfWeek,
endOfWeek;
while (currentWeek < lastOfMonth) {
startOfWeek = dashboard._query.total_connection.custom_weeklyreport.sameMonth(currentWeek.clone().day(0), firstOfMonth, 1);
endOfWeek = dashboard._query.total_connection.custom_weeklyreport.sameMonth(currentWeek.clone().day(6), firstOfMonth, lastOfMonthDate);
output.push([startOfWeek + '-' + endOfWeek, ((startOfWeek <10)?"0"+startOfWeek:startOfWeek)+"/"+currentWeek.format("MM/YYYY")+" au "+((endOfWeek <10)?"0"+endOfWeek:endOfWeek)+"/"+currentWeek.format("MM/YYYY"), (count ==0)?firstOfMonth.isoWeek():currentWeek.isoWeek()]);
currentWeek.add(7, 'days');
count++;
}
return output;
}
}
},
//- Number of pages visited by connections + average (average = unique pageviews/login users)
"page_visit" : function(ids, start, end){
gapi.client.analytics.data.ga.get({
'ids': ids,
'start-date': start.format('YYYY-MM-DD'),
'end-date': end.format('YYYY-MM-DD'),
'metrics': 'ga:uniquePageviews,ga:users'
})
.then(function(response) {
//var uniquePageviews = parseFloat(response.result.totalsForAllResults["ga:uniquePageviews"]);
var uniquePageviews = parseInt(response.result.totalsForAllResults["ga:uniquePageviews"]);
var users = parseInt(response.result.totalsForAllResults["ga:users"]);
var avguniquePageviews = (uniquePageviews ==0)?"0":parseFloat(uniquePageviews/users).toFixed(2);
$("#pageview_by_connection").text(uniquePageviews);
$("#avg_pageview_by_connection").text(avguniquePageviews);
})
.then(null, function(err) {
// Log any errors.
console.log(err);
});
},
//- Rebound rate
"rebound_rate" : function(ids, start, end){
gapi.client.analytics.data.ga.get({
'ids': ids,
'start-date': start.format('YYYY-MM-DD'),
'end-date': end.format('YYYY-MM-DD'),
'metrics': 'ga:bounceRate'
})
.then(function(response) {
$("#bouncerate").text(parseFloat(response.result.totalsForAllResults["ga:bounceRate"]).toFixed(2)+"%");
})
.then(null, function(err) {
// Log any errors.
console.log(err);
});
},
//- Number of registrations per connections + Conversion rate: number of registrations for events by connections
"event_registration" : function(ids, start, end){
gapi.client.analytics.data.ga.get({
'ids': ids,
'start-date': start.format('YYYY-MM-DD'),
'end-date': end.format('YYYY-MM-DD'),
'metrics': 'ga:eventValue',
'dimensions' : 'ga:eventAction,ga:eventCategory',
'filters': 'ga:eventAction==Reserve-By-Account,ga:eventAction==Reserve-Per-Account'
})
.then(function(response) {
if(typeof response.result.rows != "undefined" && (response.result.rows).length > 0) {
var seats_reserved = response.result.rows[0][2],
registration = response.result.rows[1][2];
$("#seats_reserved").text(seats_reserved);
$("#registration").text(registration);
} else {
$("#seats_reserved").text(0);
$("#registration").text(0);
}
})
.then(null, function(err) {
// Log any errors.
//console.log(err.status); == 403
//console.log(err.statusText); == "Forbidden"
});
},
//- Nb new visits - # of known visitors -% of new visits -% known visitors
"avg_visitors" : function(ids, start, end){
gapi.client.analytics.data.ga.get({
'ids': ids,
'start-date': start.format('YYYY-MM-DD'),
'end-date': end.format('YYYY-MM-DD'),
'metrics': 'ga:users',
'dimensions': 'ga:userType'
})
.then(function(response) {
if(typeof response.result.rows != "undefined") {
var new_visitors = (typeof response.result.rows[0] != "undefined")?parseInt(response.result.rows[0][1]):0,
returning_visitors = (typeof response.result.rows[1] != "undefined")?parseInt(response.result.rows[1][1]):0,
total_visitors = parseInt(response.result.totalsForAllResults["ga:users"]),
percent_new_visitors = parseFloat((new_visitors/total_visitors)*100).toFixed(2),
percent_returning_visitors = parseFloat((returning_visitors/total_visitors)*100).toFixed(2);
$("#new_visitors").text(new_visitors);
$("#returning_visitors").text(returning_visitors);
}
})
.then(null, function(err) {
// Log any errors.
console.log(err);
});
},
"avg_visitors_piechart" : function(ids, start, end) {
// initial remove the charts to avoid bug
$("#avg_visitors_piechart").empty();
$("#chartC").empty();
$("#chartD").empty();
gapi.client.analytics.data.ga.get({
'ids': ids,
'start-date': start.format('YYYY-MM-DD'),
'end-date': end.format('YYYY-MM-DD'),
'metrics': 'ga:users',
'dimensions': 'ga:userType',
'sort': '-ga:users'
})
.then(function(response) {
if(typeof response.result.rows != "undefined") {
var new_visitors = (typeof response.result.rows[0] != "undefined")?parseInt(response.result.rows[0][1]):0,
returning_visitors = (typeof response.result.rows[1] != "undefined")?parseInt(response.result.rows[1][1]):0;
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['', ''],
[app.get_vars().dashboard.new_visitors, new_visitors],
[app.get_vars().dashboard.returning_visitors, returning_visitors]
]);
var options = {
pieHole: 3/9,
colors: ['#058dc7', '#50b432'],
chartArea : {width:'100%',height:'75%'}
};
// var chart = new google.visualization.PieChart(document.getElementById('avg_visitors_piechart'));
// chart.draw(data, options);
}
// pass data to chart function
dashboard.getChartData([new_visitors+returning_visitors], ['#D24000'], '#avg_visitors_piechart', true)
dashboard.getChartData([new_visitors], ['#E59E42'], '#chartC')
dashboard.getChartData([returning_visitors], ['#D24332'], '#chartD')
}
})
.then(null, function(err) {
// Log any errors.
console.log(err);
});
},
"error_codes" : function(code){
var message = {};
switch(code){
case "403_invalidCredentials" :
message = { mtype : "signin", message : "Votre session de connexion pour Google Analytics a expiré. Veuillez vous connecter à nouveau."};
break;
case "403_insufficientPermissions" :
message = { mtype : "signout", message : "Accès interdit! Votre compte Google ne dispose pas d'autorisations suffisantes pour accéder à Google Analytics."};
break;
default : message = { mtype : "", message : ""};
break;
}
return message;
}
},
"filter" : {
"day_week_mon" : function(_this){
//check if access token has expired
var expires_in = moment(dashboard.get_vars().access_token_expiration, "YYYY-MM-DD HH:mm:ss");
if(expires_in >= moment()) {
//remove active class
$(".btn-dimension").removeClass("active");
//init
_this.addClass("active");
dashboard._query.total_connection._chart(dash_byuser_id, dashboard.get_vars().startdate, dashboard.get_vars().enddate, _this.data("btndimension"));
} else {
//check ga || refresh token
dashboard.check_valid_token();
}
}
},
"_daterange_picker" : {
"select" : function(start, end, label){
dashboard.set_vars({"startdate": start, "enddate": end});
$('#date_scope span').html(start.format('DD/MM/YYYY') + ' - ' + end.format('DD/MM/YYYY'));
//check if access token has expired
var expires_in = moment(dashboard.get_vars().access_token_expiration, "YYYY-MM-DD HH:mm:ss");
if(expires_in >= moment()) {
gapi.client.analytics.data.ga.get({
'ids': dash_alldata_id,
'start-date': moment().format('YYYY-MM-DD'),
'end-date': moment().format('YYYY-MM-DD'),
'metrics': 'ga:users',
'totalResults' : 1
})
.then(function(response) {
//enable back the buttons
$("#btn-dimension-dwm").find("button").prop("disabled", false);
//reload analytics
dashboard._query.total_connection._chart(dash_byuser_id, start, end, $(".btn-dimension").filter(".active").data("btndimension"));
dashboard._query.total_visitors(dash_alldata_id, start, end);
dashboard._query.total_connection_time(dash_byuser_id, start, end);
dashboard._query.page_visit(dash_byuser_id, start, end);
dashboard._query.rebound_rate(dash_alldata_id, start, end);
dashboard._query.event_registration(dash_alldata_id, start, end);
dashboard._query.avg_visitors(dash_alldata_id, start, end);
dashboard._query.avg_visitors_piechart(dash_alldata_id, start, end);
})
.then(null, function(err) {
if(parseInt(err.status) == 403) {
//disable buttons
$("#btn-dimension-dwm").find("button").prop("disabled", true);
if(typeof err.result.error.errors[0] != "undefined"){
var error_msg = dashboard._query.error_codes(err.status+"_"+err.result.error.errors[0].reason);
if(error_msg.mtype == "signout") {
$("#dashboardMsg").html('<strong>Accès interdit!</strong> ' + error_msg.message+' <a href="#" onclick="signOut();">Déconnexion</a>').show();
} else if(error_msg.mtype == "signin") {
$("#dashboardMsg").html('<strong>Accès interdit!</strong> ' + error_msg.message+' <a href="#" onclick="signOut();">Déconnexion</a>').show();
}
}
}
});
} else{
//check ga || refresh token
dashboard.check_valid_token();
}
}
},
reload_ga : function(){
if(typeof dashboard.get_vars().access_token != "undefined") {
gapi.analytics.ready(function () {
gapi.analytics.auth.authorize({
serverAuth: {
access_token: dashboard.get_vars().access_token
}
});
dashboard.set_vars({"startdate": moment().subtract(29, 'days'), "enddate": moment()});
dashboard._daterange_picker.select(dashboard.get_vars().startdate, dashboard.get_vars().enddate);
});
} else {
$("#dashboardMsg").html('<strong>Attention!</strong> Impossible d\'initialiser le tableau de bord. Veuillez recharger la page.').show();
}
},
check_valid_token : function() {
$.ajax({
type: 'POST',
url: dash_baseurl+"dashboard/dashboard/ganalytics",
dataType : 'json',
success: function(result) {
if(result.mtype == 'signin' || result.mtype == "error") {
$("#dashboardMsg").html('<strong>Accès interdit!</strong> '+result.message+' <a href="#" onclick="signIn();" id="signinButton">Connexion avec Google</a>').show();
} else {
$("#dashboardMsg").hide().html('');
if(typeof result.mdetail.servertime != "undefined") {
dashboard.setMomentOffset(result.mdetail.servertime.date);
}
dashboard.set_vars({"access_token": result.message, "access_token_expiration" : result.mdetail.access_token_expiration});
dashboard.reload_ga();
}
}
});
},
signin_auth : function(authResult){
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').hide();
// Send the code to the server
$.ajax({
type: 'POST',
url: dash_baseurl+"dashboard/dashboard/oauth2callback",
dataType : 'json',
async: false,
success: function(result) {
$("#dashboardMsg").hide().html('');
dashboard.setMomentOffset(result.mdetail.servertime.date);
dashboard.set_vars({"access_token": result.message, "access_token_expiration" : result.mdetail.access_token_expiration});
dashboard.reload_ga();
},
data: {
oauth_code : authResult['code']
}
});
document.location.reload();
} else {
// There was an error.
}
},
"gsignout" : function(){
$.ajax({
type: 'POST',
url: dash_baseurl+"dashboard/dashboard/gsignout",
dataType : 'json',
data : {type : "gsignout"},
success: function(result) {
$("#dashboardMsg").html('<strong>Attention! </strong> '+result.message+' <a href="#" onclick="signIn();" id="signinButton">Connexion avec Google</a>').show();
}
});
},
"setMomentOffset" : function(serverTime) {
var offset = new Date(serverTime).getTime() - Date.now();
moment.now = function() {
return offset + Date.now();
}
},
/**
* get the apex charts based on the data parameters
* @param {array} _data - to show on the labels as percentage
* @param {array} _color - speicify color of the chart
* @param {string} _selector - target element
* @param {int} _height - specify height of the chart
*/
getChartData: function(_data, _color, _selector, _height = false) {
/*
* initializing charts then supply the data
*/
var chartOptions = {
chart: {
height: _height ? 320 : 200,
color: "#fff",
type: 'radialBar',
},
series: [..._data],
colors: [..._color],
plotOptions: {
radialBar: {
hollow: {
margin: 15,
size: "55%",
},
track: {
background: "#CDD5E1",
},
dataLabels: {
name: {
show: false,
fontSize: '0px',
},
value: {
color: "#111",
fontSize: _height ? "42px" : "22px",
fontWeight: "700",
show: true,
},
},
},
},
stroke: {
lineCap: "butt",
curve: "smooth",
},
};
var chart = new ApexCharts(document.querySelector(_selector), chartOptions);
chart.render();
}
};//end of return
// Pass in jQuery.
})(jQuery, this);
function initgapiAuth() {
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: dash_client_id,
'cookiepolicy' : 'single_host_origin',
//'cookiepolicy' : 'http://dev.wylog.com', //when on prod
fetch_basic_profile : false,
scope: 'https://www.googleapis.com/auth/analytics.readonly'
}).then(function(authInstance){
});
});
}
function signIn() {
initgapiAuth();
var auth2 = gapi.auth2.getAuthInstance();
auth2.grantOfflineAccess({'redirect_uri': "postmessage", 'approval_prompt' : "force"}).then(dashboard.signin_auth);
}
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
if (auth2)
auth2.signOut().then(function () {
dashboard.gsignout();
});
}
$(function() {
if (typeof gapi === 'undefined') {
(function(w,d,s,g,js,fs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/client:platform.js';
fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));
}
var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
if(isSafari){
}
gapi.analytics.ready(function() {
google.charts.load('current', {'packages':['corechart', 'line'], 'language': 'fr'});
moment.locale('fr');
$('#date_scope').daterangepicker({
locale: {
format: 'DD/MM/YYYY',
cancelLabel : app.get_vars().dashboard.cancel,
applyLabel : app.get_vars().dashboard.apply,
customRangeLabel : app.get_vars().dashboard.custom_range,
"daysOfWeek": 'di_lu_ma_me_je_ce_sa'.split('_'),
"monthNames": 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_')
},
defaultDate : moment().startOf('month'),
startDate: moment().subtract(29, 'days'),
endDate: moment(),
maxDate: moment().endOf('month'),
ranges: {
'Revenir à aujourd\'hui': [moment(), moment()],
'Hier': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Les 7 derniers jours': [moment().subtract(6, 'days'), moment()],
'Les 30 derniers jours': [moment().subtract(29, 'days'), moment()],
'Ce mois-ci': [moment().startOf('month'), moment().endOf('month')],
'Mois précédent': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
}, dashboard._daterange_picker.select);
//check ga || refresh token
dashboard.check_valid_token();
});
});