jam-cloud/web/app/assets/javascripts/accounts_affiliate.js

359 lines
11 KiB
JavaScript

(function (context, $) {
"use strict";
context.JK = context.JK || {};
context.JK.AccountAffiliateScreen = function (app) {
var logger = context.JK.logger;
var rest = context.JK.Rest();
var userId;
var user = {};
var affiliatePartnerTabs = ['account', 'agreement', 'signups', 'earnings'];
var affiliatePartnerData = null;
var $screen = null;
function beforeShow(data) {
userId = context.JK.currentUserId
affiliatePartnerData = null;
}
function afterShow(data) {
rest.getAffiliatePartnerData(userId)
.done(function (response) {
affiliatePartnerData = response;
renderAffiliateTab('account')
})
.fail(app.ajaxError)
}
function events() {
// Affiliate Partner
$("#account-affiliate-partner-content-scroller").on('click', '#affiliate-partner-account-link', function (evt) {
evt.stopPropagation();
renderAffiliateTab('account');
return false;
});
$("#account-affiliate-partner-content-scroller").on('click', '#affiliate-partner-links-link', function (evt) {
evt.stopPropagation();
renderAffiliateTab('links');
return false;
});
$("#account-affiliate-partner-content-scroller").on('click', '#affiliate-partner-agreement-link', function (evt) {
evt.stopPropagation();
renderAffiliateTab('agreement');
return false;
});
$("#account-affiliate-partner-content-scroller").on('click', '#affiliate-partner-signups-link', function (evt) {
evt.stopPropagation();
renderAffiliateTab('signups');
return false;
});
$("#account-affiliate-partner-content-scroller").on('click', '#affiliate-partner-earnings-link', function (evt) {
evt.stopPropagation();
renderAffiliateTab('earnings');
return false;
});
$("#account-affiliate-partner-content-scroller").on('click', '#affiliate-profile-account-submit', function (evt) {
evt.stopPropagation();
handleUpdateAffiliateAccount();
return false;
});
}
function _renderAffiliateTableSignups(rows) {
rest.getAffiliateSignups()
.done(onAffiliateSignups)
.fail(app.ajaxError)
}
function _renderAffiliateTableEarnings(rows) {
rest.getAffiliatePayments()
.done(onAffiliatePayments)
.fail(app.ajaxError)
}
function _renderAffiliateTableLinks(rows) {
$screen.find('.affiliate-agreement').on('click', function () {
renderAffiliateTab('agreement');
return false;
})
$screen.find('.affiliate-link-page').attr('href', '/affiliate/links/' + affiliatePartnerData.account.id)
$screen.find('select.link_type').easyDropDown();
var $linkType = $screen.find('.link_type')
$linkType.on('change', function() {
logger.debug("link type changed")
updateLinks();
})
updateLinks();
}
function onAffiliateSignups(signups) {
var traffics = signupsByMonth(signups.traffics);
console.log('traffics', traffics);
var $table = $screen.find('table.traffic-table tbody')
$table.empty();
var template = $('#template-affiliate-partner-signups-row').html();
context._.each(traffics, function(item) {
var $link = $(context._.template(template, item, {variable: 'data'}));
var $day = $link.find('td.day')
var day = $day.text();
var bits = day.split('-')
if(bits.length == 3) {
$day.text(context.JK.getMonth(new Number(bits[1]) - 1) + ' ' + new Number(bits[2]))
}
$table.append($link)
})
}
function signupsByMonth(data){
var item,
i = 0,
groups = {},
output = [],
date, year, month, key,
monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
while (item = data[i++]) {
date = new Date(item.day);
year = date.getFullYear();
month = date.getMonth();
key = monthNames[month] + " " + year
groups[key] || (groups[key] = []); // exists OR create []
groups[key].push(item);
}
for (var key in groups) {
var sumVisits = groups[key].reduce(function (s, a) {
return s + a.visits;
}, 0);
var sumSignups = groups[key].reduce(function (s, a) {
return s + a.signups;
}, 0);
output.push({ month: key, signups: sumSignups, visits: sumVisits })
}
return output;
}
function onAffiliatePayments(payments) {
var $table = $screen.find('table.payment-table tbody')
$table.empty();
var template = $('#template-affiliate-partner-earnings-row').html();
context._.each(payments.payments, function(item) {
var data = {}
// if(item.payment_type == 'quarterly') {
// if(item.quarter == 0) {
// data.time = '1st Quarter ' + item.year
// }
// else if(item.quarter == 1) {
// data.time = '2nd Quarter ' + item.year
// }
// else if(item.quarter == 2) {
// data.time = '3rd Quarter ' + item.year
// }
// else if(item.quarter == 3) {
// data.time = '4th Quarter ' + item.year
// }
// data.sold = ''
// if(item.paid) {
// data.earnings = 'PAID $' + (item.due_amount_in_cents / 100).toFixed(2);
// }
// else {
// data.earnings = 'No earning were paid, as the $10 minimum threshold was not reached.'
// }
// }
// else {
data.time = context.JK.getMonth(item.month - 1) + ' ' + item.year;
if(item.jamtracks_sold == 1) {
data.sold = 'JamTracks: ' + item.jamtracks_sold + ' unit sold';
}
else if(item.jamtracks_sold > 1) {
data.sold = 'JamTracks: ' + item.jamtracks_sold + ' units sold';
}
data.earnings = '$' + (item.due_amount_in_cents / 100).toFixed(2);
if(item.subscriptions){
data.subscriptions = $.map(item.subscriptions, function(subs){
return '<div>' + getDisplayNameTier(subs.plan) + ' subscriptions - ' + subs.count + '</div>'
});
}
//}
var $earning = $(context._.template(template, data, {variable: 'data'}));
$table.append($earning)
})
}
function getDisplayNameTier(plan_code) {
var i, len, ref, subscriptionCode;
if (plan_code === '') {
plan_code = null;
}
ref = gon.global.subscription_codes;
for (i = 0, len = ref.length; i < len; i++) {
subscriptionCode = ref[i];
if (plan_code === subscriptionCode.id) {
return subscriptionCode.name;
}
}
return "Unknown plan code=" + plan_code;
}
function updateLinks() {
// affiliatePartnerData.account.id
rest.getLinks('all', affiliatePartnerData.account.id)
.done(populateLinkTable)
.fail(function() {
app.notify({text: 'Unable to fetch links. Please try again later.' })
})
}
function _renderAffiliateTab(theTab) {
affiliateTabRefresh(theTab);
var template = $('#template-affiliate-partner-' + theTab).html();
var tabHtml = context._.template(template, affiliatePartnerData[theTab], {variable: 'data'});
$('#affiliate-partner-tab-content').html(tabHtml);
if (theTab == 'signups') {
_renderAffiliateTableSignups(affiliatePartnerData[theTab]);
} else if (theTab == 'earnings') {
_renderAffiliateTableEarnings(affiliatePartnerData[theTab]);
} else if (theTab == 'links') {
_renderAffiliateTableLinks(affiliatePartnerData[theTab]);
}
}
function renderAffiliateTab(theTab) {
if (affiliatePartnerData) {
return _renderAffiliateTab(theTab);
}
rest.getAffiliatePartnerData(userId)
.done(function (response) {
affiliatePartnerData = response;
_renderAffiliateTab(theTab);
})
.fail(app.ajaxError)
}
function affiliateTabRefresh(selectedTab) {
var container = $('#account-affiliate-partner-content-scroller');
container.find('.affiliate-partner-nav a.active').removeClass('active');
if (selectedTab) {
container.find('.affiliate-partner-' + selectedTab).show();
$.each(affiliatePartnerTabs, function (index, val) {
if (val != selectedTab) {
container.find('.affiliate-partner-' + val).hide();
}
});
container.find('.affiliate-partner-nav a#affiliate-partner-' + selectedTab + '-link').addClass('active');
} else {
$.each(affiliatePartnerTabs, function (index, val) {
container.find('.affiliate-partner-' + val).hide();
});
container.find('.affiliate-partner-nav a#affiliate-partner-' + affiliatePartnerTabs[0] + '-link').addClass('active');
}
}
function handleUpdateAffiliateAccount() {
var tab_content = $('#affiliate-partner-tab-content');
var affiliate_partner_data = {
'address': {
'address1': tab_content.find('#affiliate_partner_address1').val(),
'address2': tab_content.find('#affiliate_partner_address2').val(),
'city': tab_content.find('#affiliate_partner_city').val(),
'state': tab_content.find('#affiliate_partner_state').val(),
'postal_code': tab_content.find('#affiliate_partner_postal_code').val(),
'country': tab_content.find('#affiliate_partner_country').val()
},
'tax_identifier': tab_content.find('#affiliate_partner_tax_identifier').val(),
'paypal_id': tab_content.find('#affiliate_partner_paypal_id').val()
}
var button = $('#affiliate-profile-account-submit')
button.addClass("disabled")
rest.postAffiliatePartnerData(userId, affiliate_partner_data)
.done(postUpdateAffiliateAccountSuccess)
.fail(function(jqXHR) {
button.removeClass("disabled")
alert("Unable to update affiliate information.\n\n" + jqXHR.responseText)
})
}
function postUpdateAffiliateAccountSuccess(response) {
$('#affiliate-profile-account-submit').removeClass("disabled")
app.notify(
{
title: "Affiliate Account",
text: "You have updated your affiliate partner data successfully."
},
null, true);
}
function populateLinkTable(response) {
$screen.find('table.links-table').show();
var $linkTable = $screen.find('.links-table tbody')
$linkTable.empty();
var template = $('#template-affiliate-link-entry').html();
context._.each(response, function(item) {
var $link = $(context._.template(template, item, {variable: 'data'}));
$link.find('td.copy-link a').click(copyLink)
$linkTable.append($link)
})
}
function copyLink() {
var element = $(this);
var $url = element.closest('tr').find('td.url input')
$url.select()
return false;
}
function initialize() {
var screenBindings = {
'beforeShow': beforeShow,
'afterShow': afterShow
};
app.bindScreen('account/affiliatePartner', screenBindings);
$screen = $('#account-affiliate-partner')
events();
}
this.initialize = initialize;
this.beforeShow = beforeShow;
this.afterShow = afterShow;
return this;
};
})(window, jQuery);