Commit 96e2f77d by Awais Qureshi

Merge pull request #198 from edx/awais786/ECOM-1716-google-an-events

ECOM-1716 Adding analytics.js into config.
parents d40d0d0d db80575c
......@@ -27,6 +27,10 @@
{
name: 'js/views/payment_button_view',
exclude: ['js/common']
},
{
name: 'js/pages/credit_checkout',
exclude: ['js/common']
}
]
})
import json
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import Http404
......@@ -42,7 +44,20 @@ class Checkout(TemplateView):
'payment_processors': processors_dict,
'credit_seats': [
seat for seat in course.seat_products if seat.attr.certificate_type == self.CREDIT_MODE
]
],
'analytics_data': json.dumps({
'course': {
'courseId': course.id
},
'tracking': {
'segmentApplicationId': settings.SEGMENT_KEY
},
'user': {
'username': self.request.user.get_username(),
'name': self.request.user.get_full_name(),
'email': self.request.user.email
}
})
})
return context
......
define(['backbone'], function(Backbone) {
'use strict';
/**
* Stores our course id information.
*/
return Backbone.Model.extend({
});
});
define(['backbone', 'underscore'], function(Backbone, _) {
'use strict';
/**
* Stores our tracking logic and information.
*/
return Backbone.Model.extend({
/**
* Determine if the application is tracked.
*/
isTracking: function() {
var self = this,
trackId = self.get('segmentApplicationId');
return !_(trackId).isUndefined() && !_(trackId).isNull();
}
});
});
define(['backbone'], function(Backbone) {
'use strict';
/**
* Stores our user logic and information.
*/
return Backbone.Model.extend({
});
});
require([
'jquery',
'backbone',
'js/models/user-model',
'js/models/tracking-model',
'js/models/course-model',
'js/views/clickable-view',
'js/views/analytics_view',
'js/views/payment_button_view',
'js/utils/utils'
],
function( $,Backbone, UserModel, TrackingModel, CourseModel, ClickableView, AnalyticsView, PaymentButtonView, Utils ) {
new PaymentButtonView({
el: $( '#payment-buttons')
});
var courseModel = new CourseModel(),
trackingModel = new TrackingModel(),
userModel = new UserModel();
/* jshint ignore:start */
// initModelData is set by the Django template at render time.
trackingModel.set(initModelData.tracking);
userModel.set(initModelData.user);
courseModel.set(initModelData.course);
/* jshint ignore:end */
/*
Triggering the analytics events on clicking the payment buttons on checkoutpage.
Buttons has the data-track- attributes type , event and category.
*/
new AnalyticsView({
model: trackingModel,
userModel: userModel,
courseModel: courseModel
});
// instrument the click events
_($('[data-track-type="click"]')).each(function (track) {
var properties = Utils.getNodeProperties(track.attributes,
'data-track-', ['data-track-event']);
new ClickableView({
model: trackingModel,
trackEventType: $(track).attr('data-track-event'),
trackProperties: properties,
el: track
});
});
}
);
define(['underscore'], function (_) {
'use strict';
var utils = {
/**
* Returns the attributes of a node.
*
* @param nodeAttributes Attributes of the node.
* @param startsWithAndStrip Filters only attributes that start with
* this string and strips it off the attribute.
* @param blackList Exclude attributes in this array of strings.
* @returns Hash of found attributes.
*/
getNodeProperties: function (nodeAttributes, startsWithAndStrip, blackList) {
var properties = {};
// fill in defaults
startsWithAndStrip = startsWithAndStrip || '';
blackList = blackList || [];
_(_(nodeAttributes.length).range()).each(function (i) {
var nodeName = nodeAttributes.item(i).nodeName,
strippedName;
// filter the attributes to just the ones that start with our
// selection and aren't in our blacklist
if (nodeName.indexOf(startsWithAndStrip) === 0 && !_(blackList).contains(nodeName)) {
// remove the
strippedName = nodeName.replace(startsWithAndStrip, '');
properties[strippedName] =
nodeAttributes.item(i).value;
}
});
return properties;
}
};
return utils;
});
define([
'jquery',
'backbone',
'underscore'
],
function ($, Backbone, _) {
'use strict';
/**
* This 'view' doesn't display anything, but rather sends tracking
* information in response to 'segment:track' events triggered by the
* model.
*
* Actions will only be tracked if segmentApplicationId is set in the
* model.
*/
return Backbone.View.extend({
/**
* Reference to segment.io analytics library. This is set after
* loading.
*/
initialize: function (options) {
this.options = options || {};
// wait until you have a segment application ID before kicking
// up the script
if (this.model.isTracking()) {
this.applicationIdSet();
} else {
this.listenToOnce(this.model, 'change:segmentApplicationId',
this.applicationIdSet);
}
},
applicationIdSet: function () {
var trackId = this.model.get('segmentApplicationId');
// if no ID is supplied, then don't track
if (this.model.isTracking()) {
// kick off segment
this.initSegment(trackId);
this.logUser();
// now segment has been loaded, we can track events
this.listenTo(this.model, 'segment:track', this.track);
}
},
/**
* This sets up segment.io for our application and loads the initial
* page load.
*
* this.segment is set for convenience.
*/
initSegment: function (applicationKey) {
/* jshint ignore:start */
// jscs:disable
var analytics = window.analytics = window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","group","track","ready","alias","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){var e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};analytics.SNIPPET_VERSION="3.0.1";}
// jscs:enable
/* jshint ignore:end */
// provide our application key for logging
analytics.load(applicationKey);
// this needs to be called once
analytics.page(this.buildCourseProperties());
},
/**
* Log the user.
*/
logUser: function () {
var userModel = this.options.userModel;
analytics.identify(userModel.get('username'), {
name: userModel.get('name'),
email: userModel.get('email')
});
},
buildCourseProperties: function() {
var course = {};
if (this.options.courseModel) {
course.courseId = this.options.courseModel.get('courseId');
}
if (this.model.has('page')) {
course.label = this.model.get('page');
}
return course;
},
/**
* Catch 'segment:track' events and create events and send
* to segment.io.
*
* @param eventType String event type.
*/
track: function (eventType, properties) {
var course = this.buildCourseProperties();
// send event to segment including the course ID
analytics.track(eventType, _.extend(course, properties));
}
});
}
);
define(['underscore', 'backbone'],
function (_, Backbone) {
'use strict';
/**
* Use this for triggering track events when an element is clicked.
* 'segment:track' and an event are fired when the element is clicked.
*/
return Backbone.View.extend({
initialize: function (options) {
var self = this;
self.options = options;
if (_(self.options).has('trackEventType')) {
self.render();
}
},
render: function () {
var self = this;
// track the click
self.$el.click(function () {
// track this event type along with properties
self.model.trigger('segment:track',
self.options.trackEventType,
self.options.trackProperties);
});
return this;
}
});
}
);
require([
'jquery',
'js/views/payment_button_view'
],
function( $, PaymentButtonView ) {
var paybtnview = new PaymentButtonView({
el: $( '#payment-buttons')
});
}
);
......@@ -44,9 +44,14 @@
<div id="payment-buttons" class="row center-block checkout-controls">
{% for processor_name, button_text in payment_processors.items %}
<div class="col-xs-6 ">
<button data-processor-name="{{ processor_name }}" data-sku="{{ credit_seats.0.stockrecords.first.partner_sku }}"
<button data-track-type="click"
data-track-event="edx.bi.ecommerce.credit.payment_selected"
data-track-category="{{ processor_name }}"
data-processor-name="{{ processor_name }}"
data-sku="{{ credit_seats.0.stockrecords.first.partner_sku }}"
data-course-id="{{ course.id }}"
class="btn btn-primary payment-button">
class="btn btn-primary payment-button"
>
{{ button_text }}
</button>
</div>
......@@ -56,10 +61,17 @@
<form id="payment-processor-form">
</form>
{% if analytics_data %}
<script type="text/javascript">
var initModelData = {{ analytics_data|safe }};
</script>
{% endif %}
{% endblock content %}
{% compress js %}
{% block javascript %}
<script src="{% static 'js/views/credit_checkout.js' %}"></script>
<script src="{% static 'js/pages/credit_checkout.js' %}"></script>
{% endblock %}
{% endcompress %}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment