Skip to content

Instantly share code, notes, and snippets.

@roboli
Last active June 13, 2018 21:03
Show Gist options
  • Save roboli/377ad8feb59cc5a2b8995dcf5609f6bc to your computer and use it in GitHub Desktop.
Save roboli/377ad8feb59cc5a2b8995dcf5609f6bc to your computer and use it in GitHub Desktop.
function loadUtils(opts) {
opts = opts || {};
var $ = opts.$;
var Promise = opts.Promise;
var dbaClient = opts.dbaClient;
var tryAgainUri = opts.tryAgainUri;
var additionalQuestionsUri = opts.additionalQuestionsUri;
setupFormEvents();
function showAgreement() {
return new Promise(function(resolve) {
$('#infsheet').modal('show'); // display information sheet
var lead = buildLead();
$("#agreementFirstParty").text( lead.firstname + " " +
lead.lastname + ", " +
lead.address + ", " +
lead.postcode);
fbq('track', 'Lead', {
value: 0,
currency: 'USD' // not sure if it is neccessary
});
gtag_display_info_sheet_conversion();
ga('send', 'event', 'MainPage', 'DisplayInfoSheet');
// Disagree on information sheet
$('#infosheet-btn-disagree').click(function () {
$('#infsheet').modal('hide');
fbq('track', 'Lead', {
value: -1,
currency: 'USD' // not sure if it is neccessary
});
gtag_dont_accept_info_sheet_conversion();
ga('send', 'event', 'MainPage', 'DontAcceptInfoSheet');
resolve(0);
});
// Accept information sheet
$('#infosheet-btn-agree').click(function () {
$('#infsheet').modal('hide');
fbq('track', 'Lead', {
value: 1,
currency: 'USD' // not sure if it is neccessary
});
gtag_accept_info_sheet_conversion();
ga('send', 'event', 'MainPage', 'AcceptInfoSheet');
resolve(1);
});
});
}
function showOn(fieldName, selectorToShow, clearFunction, value) {
var actualValue = $('input[name=' + fieldName + ']:checked').val();
if (actualValue === value) {
$(selectorToShow).show();
return true;
} else {
$(selectorToShow).hide();
clearFunction();
return false;
}
}
function clearRadioCheckbox(parent) {
var children = $(parent).find('.checkbox');
children.checkbox('uncheck');
}
function setupFormEvents() {
$("#haveWorkedQuestion .ui.radio.checkbox")
.checkbox({
onChange: function() {
showOn('hasWorked', '#currentlyAtTescoQuestion', function() {
clearRadioCheckbox('#currentlyAtTescoQuestion');
}, 'Yes');
showOn('hasWorked', '#startedAtTesco', function() {
$('input[name=startDate]').val('');
}, 'Yes');
},
});
$("#currentlyAtTescoQuestion .ui.radio.checkbox")
.checkbox({
onChange: function() {
showOn('currentlyAtTesco', '#isAtTesco', function() {
$('input[name=endDate]').val('');
}, 'No');
},
});
}
var _lead;
function buildLead() {
if(_lead) {
return _lead;
}
var lead = {};
lead.leadgroup = dbaClient.leadGroup;
lead.site = 0;
lead.introducer = 0;
lead.reference = '';
var adsinfo = getUrlVars(window.location.href);
lead.source = adsinfo.utm_source;
lead.medium = adsinfo.utm_medium;
lead.term = adsinfo.utm_term;
lead.cost = 120;
lead.value = 120;
// get address and postcode
lead.title = $("select[name=title]").val();
lead.firstname = $("input[name=firstName]").val();
lead.lastname = $("input[name=lastName]").val();
lead.email = $("input[name=email]").val();
lead.phone1 = $("input[name=phone]").val();
lead.address = $("input[name=housenum]").val() + " " + $("input[name=streetname]").val();
lead.towncity = $("input[name=towncity]").val();
lead.postcode = $("input[name=postcode]").val();
lead.data40 = $("select[name=country]").val();
// get date of birth
var dob = new Date($("#dob-calendar").val());
lead.dobday = dob.getUTCDate();
lead.dobmonth = dob.getUTCMonth() + 1;
lead.dobyear = dob.getFullYear();
if (lead.dobday < 10) {
lead.dobday = "0" + lead.dobday;
}
if (lead.dobmonth < 10) {
lead.dobmonth = "0" + lead.dobmonth;
}
lead.data1 = $('input[name=hasWorked]').val();
lead.data2 = $('input[name=startDate]').val();
lead.data3 = $('input[name=currentlyAtTesco]').val();
lead.data4 = $('input[name=endDate]').val();
lead.data5 = $("select[name=country]").val();
lead.data6 = $("select[name=gender]").val();
lead.data7 = 'Yes';
lead.data8 = 'Yes';
lead.data9 = 'Yes';
// Do not create signing DBA link
lead.not_signing_dba = true;
_lead = lead;
return lead;
}
function isDuplicate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd;
}
if(mm<10){
mm='0'+mm;
}
var lead = buildLead();
var leadId, agreed;
return dbaClient.searchLead({
search: lead.email,
leadtypeid: dbaClient.leadGroup,
startdate: dd+'/'+mm+'/'+(yyyy-1),
enddate: dd+'/'+mm+'/'+yyyy
}).then(function(results) {
// Filter by email, postcode, phone1, fullname and towncity
var match = results.find(function(l) {
var fullname = lead.title.trim().toLowerCase() + '. ' + lead.firstname.trim().toLowerCase() + ' ' + lead.lastname.trim().toLowerCase();
return lead.email === l.email &&
lead.postcode.toLowerCase() === l.postcode.toLowerCase() &&
lead.phone1 === l.phone1 &&
fullname === l.fullname.trim().toLowerCase() &&
lead.towncity.trim().toLowerCase() === l.towncity.trim().toLowerCase();
});
if(match) {
// Fetch complete lead to obtain data fields
return dbaClient.getLead(match.id);
}
return match;
}).catch(function(err) {
console.log('Error', err);
});
}
var numSteps = 5;
var stepInterval = 100/numSteps;
function transitionFromTo(step1Id, step2Id, stepNumber) {
console.log(step1Id + " -> " + step2Id + ", " + stepNumber);
var percent = stepInterval * (stepNumber - 1);
$('#' + step1Id).hide();
$('#' + step2Id).show();
$('#progress-bar').progress({
percent: percent
});
$("#progress-step").text("Step " + stepNumber + " of 5");
}
$.fn.form.settings.rules.startedAtTesco = function() {
if ($('input[name=hasWorked]:checked').val() === 'Yes') {
var startDate = $('input[name=startDate]').val();
return startDate.length > 0;
} else {
return true;
}
};
$.fn.form.settings.rules.currentlyAtCheckedIfHaveWorked = function() {
var hasWorkedAnswer = $('input[name=hasWorked]:checked').val();
if (hasWorkedAnswer === 'Yes') {
var checkedInput = $('input[name=currentlyAtTesco]:checked');
return checkedInput.length !== 0;
} else {
return true;
}
};
$.fn.form.settings.rules.notCurrentlyAtTesco = function() {
if ($('input[name=currentlyAtTesco]:checked').val() === 'No') {
var endDate = $('input[name=endDate]').val();
return endDate.length > 0;
} else {
return true;
}
};
// Keep state value for validating end date
var workBetweenTwoAndSix = false;
var workBetweenSixAndSixtySix = false;
var workBeforeSixtySix = false;
$('#step1').form({
fields: {
haveWorked: {
identifier: 'haveWorkedYes',
rules: [
{
type: 'checked',
prompt: 'You must have worked at Tesco for past 6 years on an hourly rate to submit a claim'
}
]
},
startDate: {
identifier: 'startDate',
rules: [
{
type: 'startedAtTesco',
prompt: 'Please tell us when your employment started'
}
]
},
currentlyAtTesco: {
identifier: 'currentlyAtTesco',
rules: [
{
type: 'currentlyAtCheckedIfHaveWorked',
prompt: 'Please tell us if you are currently working at Tesco'
}
]
},
endDate: {
identifier: 'endDate',
rules: [
{
type: 'notCurrentlyAtTesco',
prompt: 'Please tell us when your employment ended'
}
]
}
},
onSuccess: function (e, fields) {
var from = fields.startDate.split('-');
var startDate = new Date(from[0], from[1] - 1, from[2]);
var to = fields.endDate && fields.endDate.split('-');
var endDate = fields.endDate ? new Date(to[0], to[1] - 1, to[2]) : new Date();
var lastDate = new Date(endDate.getTime());
// Check if user has worked longer than 2 months
lastDate.setMonth(lastDate.getMonth() - 2);
if(lastDate <= startDate) {
$('#warning').hide();
return $('#step1').form('add errors', ['Unfortunately, there is a 2 month minimum employment length before we can process your claim against Tesco.']);
}
var initDate = new Date();
lastDate = new Date();
// Check if user stopped working between 2 and 6 months ago
initDate.setMonth(initDate.getMonth() - 6);
lastDate.setMonth(lastDate.getMonth() - 2);
if(initDate < endDate && endDate <= lastDate) {
if(!workBetweenTwoAndSix) {
workBetweenTwoAndSix = true;
var str1 = 'The Employment Tribunal can only deal with equal pay claims which an employee brings within 6 months of '
+ 'leaving their job. We see that you left your job a little while ago. We will do our best, but because we are '
+ 'dealing with so many applications to join the group it will take us some time to process your application, and '
+ 'we might not bring your claim in time to go through the Employment Tribunal. That is not the end of your '
+ 'claim, because we can still bring it through the courts instead of the tribunal system. Court claims may take '
+ 'longer than Employment Tribunal claims to reach a conclusion. To accept this, please just continue onto the next '
+ 'page of the application process. If you would like to know more about the difference between Employment Tribunal '
+ 'claims and court claims, Harcus will be happy to discuss this with you (equalpayaction@harcus-sinclair.ltd.uk or '
+ '020 7539 2900). If you are still not sure, remember that there are other options available, and another firm of '
+ 'solicitors might guarantee to bring your claim more quickly.';
$('#warning').html(str1);
return $('#warning').show();
} else {
workBetweenTwoAndSix = false;
$('#warning').hide();
}
}
initDate = new Date();
lastDate = new Date();
// Check if user stopped working between 6 and 66 months ago (5.5 years)
initDate.setMonth(initDate.getMonth() - 66);
lastDate.setMonth(lastDate.getMonth() - 6);
if(initDate < endDate && endDate <= lastDate) {
if(!workBetweenSixAndSixtySix) {
workBetweenSixAndSixtySix = true;
var str2 = 'Important: we see that you left your job at Tesco more than 6 months ago. This means that Harcus will need '
+ 'to bring your claim in court rather than through the Employment Tribunal. Court claims may take longer than '
+ 'Employment Tribunal claims. To accept this, please continue onto the next page of the application process. After '
+ 'you have registered, we will email you a letter which will tell you more about the process. If you would like to '
+ 'know more about the difference between Employment Tribunal claims and court claims, Pay Justice will be happy to '
+ 'discuss this with you by emailing tesco@payjustice.co.uk or by calling 0161 850 5289.';
$('#warning').html(str2);
return $('#warning').show();
} else {
workBetweenSixAndSixtySix = false;
$('#warning').hide();
}
}
lastDate = new Date();
// Check if user stopped working before 66 months ago (5.5 years)
lastDate.setMonth(lastDate.getMonth() - 66);
if(endDate < lastDate) {
if(!workBeforeSixtySix) {
workBeforeSixtySix = true;
var str3 = 'You left your job at Tesco almost 6 years ago. The time limit for equal pay cases is 6 years from the end '
+ 'of your employment, so you are nearly out of time to bring your claim. We will do our best but it may take us '
+ 'several weeks to process your registration, because we are receiving a high volume of applications. We might not '
+ 'bring your claim in time, and you may lose your opportunity to claim. To accept this risk, please continue onto '
+ 'the next page of the application process. If you would like to discuss this issue, Pay Justice will be happy to '
+ 'speak with you by emailing tesco@payjustice.co.uk or by calling 0161 850 5289. If you are still not sure, remember that there are other options available, '
+ 'and another firm of solicitors might guarantee to bring your claim more quickly.';
$('#warning').html(str3);
return $('#warning').show();
} else {
workBeforeSixtySix = false;
$('#warning').hide();
}
}
transitionFromTo('step1', 'step2', 2);
}
});
$("#step1-next").click(function () {
$('#step1').form('validate form');
});
// add custom validation for postocde
$.fn.form.settings.rules.validPostcode = function(param) {
var postcode = $("#postcode").val().replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
};
// add custom validation for birth
$.fn.form.settings.rules.validBirthDay = function(param) {
var currentDate = new Date();
currentDate.setFullYear(currentDate.getFullYear() - 18);
var date = Date.parse($("#dob-calendar").val());
if(isNaN(date)) {
return false;
}
if (date > currentDate) {
return false;
}
return true;
};
$('#step2').form({
fields: {
postcode: {
identifier: 'postcode',
rules: [
{
type: 'validPostcode[]',
prompt: 'You need to provide a valid postcode'
}
]
},
housenum: {
identifier: 'housenum',
rules: [
{
type: 'minLength[1]',
prompt: 'You need to provide your house name/number'
}
]
},
streetname: {
identifier: 'streetname',
rules: [
{
type: 'minLength[1]',
prompt: 'You need to provide your street name'
}
]
},
towncity: {
identifier: 'towncity',
rules: [
{
type: 'minLength[1]',
prompt: 'You need to provide your town/city'
}
]
}
},
onSuccess: function (e, fields) {
transitionFromTo('step2', 'step3', 4);
}
});
$("#step2-back").click(function () {
transitionFromTo('step2', 'step1', 2);
});
$("#step2-next").click(function () {
$('#step2').form('validate form');
});
$('#step3').form({
fields: {
title: {
identifier: 'title',
rules: [
{
type: 'minLength[1]',
prompt: 'You need to select a title'
}
]
},
firstName: {
identifier: 'firstName',
rules: [
{
type: 'minLength[1]',
prompt: 'You need to provide your first name'
}
]
},
lastName: {
identifier: 'lastName',
rules: [
{
type: 'minLength[1]',
prompt: 'You need to provide your last name'
}
]
},
email: {
identifier: 'email',
rules: [
{
type: 'email',
prompt: 'You need to provide your email address'
}
]
},
phone: {
identifier: 'phone',
rules: [
{
type: 'regExp[/^[0][0-9]{10}/]',
prompt: 'You need to provide a telephone number (11 digits starting with 0)'
}
]
},
birth_day: {
identifier: 'dob-calendar',
rules: [
{
type: 'validBirthDay[]',
prompt: 'We are currently not taking on claims for individuals under the age of 18. Please contact us again once you have turned 18 and we will consider whether you have a claim'
}
]
},
gender: {
identifier: 'gender',
rules: [
{
type: 'minLength[1]',
prompt: 'You need to select a gender'
}
]
}
},
onSuccess: function (e, fields) {
transitionFromTo('step3', 'step4', 5);
}
});
$("#step3-back").click(function () {
transitionFromTo('step3', 'step2', 3);
$("#progress-bar").show();
});
$("#step3-next").click(function () {
$('#step3').form('validate form');
});
$('#step4').form({
fields: {
agree1: {
identifier: 'agree1',
rules: [
{
type: 'checked',
prompt: 'You must give permission for Pay Justice to have access to the provided information above.'
}
]
},
agree2: {
identifier: 'agree2',
rules: [
{
type: 'checked',
prompt: 'You must give permission for Pay Justice to have access to the provided information above.'
}
]
},
agree3: {
identifier: 'agree3',
rules: [
{
type: 'checked',
prompt: 'You must give permission for Pay Justice to have access to the provided information above.'
}
]
}
},
onSuccess: function (e, fields) {
function showAgree(leadId) {
var agreed;
$("#loading").removeClass("active");
return showAgreement().then(function(result) {
agreed = result;
var update = {
id: leadId,
data12: !!agreed && Date.now()
};
if(agreed) {
update.status = 'DBA Approved';
}
return dbaClient.updateLead(update);
}).then(function() {
if(agreed) {
location.href = additionalQuestionsUri;
}
return;
}).catch(function(err) {
console.lg('Error', err);
});
}
function checkOnfido(lead) {
var checkResult;
var onfidoDobFormat = "" + lead.dobyear + "-" + lead.dobmonth + "-" + lead.dobday;
return dbaClient.checkOnfido({
firstname: lead.firstname,
lastname: lead.lastname,
email: lead.email,
dob: onfidoDobFormat,
address: lead.address,
postcode: lead.postcode,
towncity: lead.towncity
}).then(function(result) {
checkResult = result.result;
var summary = JSON.stringify(result.summary);
return dbaClient.updateLead({ id: lead.id, data10: checkResult, data11: summary });
}).then(function() {
if(leadIdentityValid(checkResult)) {
return showAgree(lead.id);
} else {
return Promise.reject();
}
}).catch(function() {
location.href = tryAgainUri;
});
}
function createLead(lead) {
var leadId, valid, agreed;
return dbaClient.createLead(lead)
.then(function(result) {
lead.id = result.id;
return checkOnfido(lead);
})
.catch(function(err) {
console.log('Error', err);
});
}
function leadIdentityValid(identityResult) {
return identityResult && identityResult !== 'unidentified';
}
function hasAgreed(lead) {
return lead.data12 && lead.data12 !== 'false';
}
function processExistingLead(lead) {
if(leadIdentityValid(lead.data10)) {
if (hasAgreed(lead)) {
location.href = additionalQuestionsUri;
} else {
return showAgree(lead.id);
}
} else {
return checkOnfido(lead);
}
}
$("#loading").addClass("active");
// first check duplicates before submission
isDuplicate()
.then(function(lead) {
var newLead = buildLead();
if (lead) {
// Lead exists, update with new user input
return dbaClient.updateLead($.extend({ id: lead.id }, newLead))
.then(function() {
// Override old values with new input
return processExistingLead($.extend({}, lead, newLead));
});
} else {
return createLead(newLead);
}
}).then(function() {
$("#loading").removeClass("active");
}).catch(function(err) {
console.log('Error', err);
});
}
});
$('#step4-next').click(function () {
$('#step4').form('validate form');
});
$("#step4-back").click(function () {
transitionFromTo('step4', 'step3', 4);
$("#progress-bar").show();
});
$("#infosheet").scroll(function () {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
$("#infosheet-btn-agree").removeClass("disabled");
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment