Created
September 30, 2017 11:51
-
-
Save jerronimo/c8777050ae643de701ecaa823067f56a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function(){ | |
'use strict'; | |
var onSavePostCode = false; | |
var onSavePostCodePayment = false; | |
var settingsAutocompService = new GoogleAutocompleteService(), | |
isAvailable = settingsAutocompService.getFormElements('.settings form[name="contactForm"]'); | |
if(isAvailable) | |
settingsAutocompService.initAutoComplete(); | |
// TODO: Add validation for rest forms. | |
var settingsFormValid; | |
var paymentFormValid; | |
if(window.location.pathname == '/profile/settings' | |
&& window.location.hash){ | |
$('a[href="'+window.location.hash+'"]').tab('show'); | |
} | |
function radioBoxEventHandler(e) { | |
$(this).attr("value", $(this).attr("id") === "ready_1" ? true : false); | |
} | |
function prepareSettingsData() { | |
try { | |
userId = JSON.parse(localStorage.getItem("user")).artistId; | |
} catch (e) { | |
userId = 0; | |
} | |
var cityLatInput = $('form[name="paymentForm"]').find('input[name="city_lat"]'), | |
cityLngInput = $('form[name="paymentForm"]').find('input[name="city_lng"]'), | |
regnLatInput = $('form[name="paymentForm"]').find('input[name="region_lat"]'), | |
regnLngInput = $('form[name="paymentForm"]').find('input[name="region_lng"]'), | |
placeIdInput = $('form[name="paymentForm"]').find('input[name="place_id"]'), | |
regnNameInput = $('form[name="paymentForm"]').find('input[name="region_name"]'); | |
var regionLat = settingsAutocompService.coords.region.lat, | |
regionLng = settingsAutocompService.coords.region.lng, | |
cityLat = settingsAutocompService.coords.city.lat, | |
cityLng = settingsAutocompService.coords.city.lng, | |
country = settingsAutocompService.currentStore.country, | |
city = settingsAutocompService.currentStore.city, | |
region = settingsAutocompService.currentStore.region, | |
placeId = settingsAutocompService.currentStore.placeId; | |
if(cityLat && cityLng) { | |
cityLatInput.val(cityLat); | |
cityLngInput.val(cityLng); | |
} | |
if(regionLat && regionLng) { | |
regnLatInput.val(regionLat); | |
regnLngInput.val(regionLng); | |
regnNameInput.val(region); | |
} | |
if(placeId) { | |
placeIdInput.val(placeId); | |
} | |
var contactFormInputsDisabled = $('form[name="contactForm"]').find(':input:disabled').removeAttr('disabled'); | |
var paymentFormInputsDisabled = $('form[name="paymentForm"]').find(':input:disabled').removeAttr('disabled'); | |
var contactForm = $('form[name="contactForm"]').serializeArray(), | |
profileForm = $('form[name="profileForm"]').serializeArray(), | |
paymentForm = $('form[name="paymentForm"]').serializeArray(), | |
allForms = contactForm.concat(profileForm, paymentForm), | |
sendForm = ""; | |
for(var key in allForms) { | |
var k = allForms[key].name, | |
value = allForms[key].value.trim(); | |
switch (k) { | |
case 'region_name': | |
if(value != '' && region != '') { | |
value = region; | |
} | |
break; | |
case 'city': | |
if(value != '' && city != '') { | |
value = city; | |
} | |
break; | |
case 'country': | |
if(value != country) { | |
value = settingsAutocompService.findCountryByCode(settingsAutocompService.availableCountries[value]); | |
} | |
break; | |
} | |
sendForm += "profile_settings["+k+"]="+value+"&"; | |
} | |
sendForm += "profile_settings[file]=" + base64; | |
// console.log("REGION COORDS: ", settingsAutocompService.coords.region) | |
// console.log("CITY COORDS: ", settingsAutocompService.coords.city) | |
contactFormInputsDisabled.attr('disabled','disabled'); | |
paymentFormInputsDisabled.attr('disabled','disabled'); | |
return sendForm; | |
} | |
function prepareClientSettingsData() { | |
try { | |
userId = JSON.parse(localStorage.getItem("user")).userId; | |
} catch (e) { | |
userId = 0; | |
} | |
var cityLatInput = $('form[name="paymentForm"]').find('input[name="city_lat"]'), | |
cityLngInput = $('form[name="paymentForm"]').find('input[name="city_lng"]'), | |
regnLatInput = $('form[name="paymentForm"]').find('input[name="region_lat"]'), | |
regnLngInput = $('form[name="paymentForm"]').find('input[name="region_lng"]'), | |
placeIdInput = $('form[name="paymentForm"]').find('input[name="place_id"]'), | |
regnNameInput = $('form[name="paymentForm"]').find('input[name="region_name"]'); | |
var regionLat = settingsAutocompService.coords.region.lat, | |
regionLng = settingsAutocompService.coords.region.lng, | |
cityLat = settingsAutocompService.coords.city.lat, | |
cityLng = settingsAutocompService.coords.city.lng, | |
country = settingsAutocompService.currentStore.country, | |
city = settingsAutocompService.currentStore.city, | |
region = settingsAutocompService.currentStore.region, | |
placeId = settingsAutocompService.currentStore.placeId; | |
if(cityLat && cityLng) { | |
cityLatInput.val(cityLat); | |
cityLngInput.val(cityLng); | |
} | |
if(regionLat && regionLng) { | |
regnLatInput.val(regionLat); | |
regnLngInput.val(regionLng); | |
regnNameInput.val(region); | |
} | |
if(placeId) { | |
placeIdInput.val(placeId); | |
} | |
var contactFormInputsDisabled = $('form[name="contactForm"]').find(':input:disabled').removeAttr('disabled'); | |
var paymentFormInputsDisabled = $('form[name="paymentForm"]').find(':input:disabled').removeAttr('disabled'); | |
var contactForm = $('form[name="contactForm"]').serializeArray(), | |
profileForm = $('form[name="profileForm"]').serializeArray(), | |
paymentForm = $('form[name="paymentForm"]').serializeArray(), | |
allForms = contactForm.concat(profileForm, paymentForm), | |
sendForm = ""; | |
for(var key in allForms) { | |
var k = allForms[key].name, | |
value = allForms[key].value.trim(); | |
switch (k) { | |
case 'region_name': | |
if(value != '' && region != '') { | |
value = region; | |
} | |
break; | |
case 'city': | |
if(value != '' && city != '') { | |
value = city; | |
} | |
break; | |
case 'country': | |
if(value != country) { | |
value = settingsAutocompService.findCountryByCode(settingsAutocompService.availableCountries[value]); | |
} | |
break; | |
} | |
sendForm += "profile_settings["+k+"]="+value+"&"; | |
} | |
sendForm += "profile_settings[file]=" + base64; | |
contactFormInputsDisabled.attr('disabled','disabled'); | |
paymentFormInputsDisabled.attr('disabled','disabled'); | |
return sendForm; | |
} | |
function setHeight(param) { | |
sideBar.css({ | |
height: param || settingsSection.height() | |
}); | |
} | |
function settingsFormErrorHandler(data, xhrStatus) { | |
$('#loadSpinner').fadeOut(500); | |
$('#saveSettingsBtnLoader').removeClass('show-loader'); | |
if (xhrStatus && xhrStatus === 500){ | |
handleOpenConfirmModal({isAlert: true, title: 'Error', message: xhrStatus + ': ' + data, successBtnText: 'Ok', cancelBtnText: ''}); | |
return false; | |
} | |
var accountSettingsTab = $('#contact-settings'); | |
var profileSettingsTab = $('#profile-settings'); | |
var paymentSettingsTab = $('#paymentSettingsTab'); | |
var tabsObj = { | |
account_settings: accountSettingsTab, | |
profile_settings: profileSettingsTab, | |
payment_settings: paymentSettingsTab | |
}; | |
var errors = HTTPProvider.errorsSerialize(data); | |
var response = JSON.parse(data); | |
if(response.status !== "error" && response.artist && response.artist.hasOwnProperty('slug')){ | |
$('.profile ul.dropdown-menu .icon').eq(0).attr('href', '/profile/' + response.artist.slug); | |
$('.profile ul.dropdown-menu .icon').eq(1).attr('href', '/profile/edit_profile/' + response.artist.slug); | |
} else if (response.status == "error"){ | |
var errMessage = (response.message && response.message.length) ? response.message : "an error occured"; | |
handleOpenConfirmModal({isAlert: true, title: response.status, message: errMessage, successBtnText: 'Ok', cancelBtnText: ''}); | |
} | |
$(".settings form label.error").css("opacity", 0); | |
$(".settings form input.error").removeClass("error"); | |
var errorsMessageConcat = ''; | |
if(response){ | |
for(var itemError in response){ | |
if (response.hasOwnProperty(itemError)) { | |
var fieldNamePrepared = itemError.replace('profile_settings_', ''); | |
var formElem = $('.settings form input[name="' + fieldNamePrepared + '"]'); | |
var formElemName = ( formElem.length && $(formElem[0]).attr('data-field-name') ) ? $(formElem[0]).attr('data-field-name') : '' ; | |
customErrorsShow(fieldNamePrepared, response[itemError]); | |
errorsMessageConcat += '"' + (formElemName || fieldNamePrepared) + '"' + ': ' + response[itemError] + ' </br> ' | |
} | |
} | |
handleOpenConfirmModal({isAlert: true, title: 'Error', message: errorsMessageConcat, successBtnText: 'Ok', cancelBtnText: ''}); | |
} | |
if(response && response.hasOwnProperty('status') && response.status === 'success'){ | |
if (response.hasOwnProperty('profileValidate')){ | |
for (var validKey in response.profileValidate){ | |
if (response.profileValidate[validKey]){ | |
tabsObj[validKey].removeClass('fa-warning').addClass('fa-check-square-o'); | |
} else { | |
tabsObj[validKey].removeClass('fa-check-square-o').addClass('fa-warning'); | |
} | |
} | |
} | |
handleOpenConfirmModal({title: response.status, message: 'Saved!', successBtnText: 'Ok', cancelBtnText: ''}); | |
} | |
$("#settingsPageModal").modal('hide'); | |
} | |
function settingsClientFormErrorHandler(data, xhrStatus) { | |
$('#loadSpinner').fadeOut(500); | |
if (xhrStatus && xhrStatus === 500){ | |
handleOpenConfirmModal({isAlert: true, title: 'Error', message: xhrStatus + ': ' + data, successBtnText: 'Ok', cancelBtnText: ''}); | |
return false; | |
} | |
var errors = HTTPProvider.errorsSerialize(data); | |
var response = JSON.parse(data); | |
$("label.error").css("opacity", 0); | |
if(response){ | |
for(var itemError in response){ | |
if (response.hasOwnProperty(itemError)) { | |
var fieldNamePrepared = itemError.replace('profile_settings_', ''); | |
console.log(fieldNamePrepared) | |
customErrorsShow(fieldNamePrepared, response[itemError]) | |
} | |
} | |
} | |
if(response && response.hasOwnProperty('status') && response.status === 'success'){ | |
handleOpenConfirmModal({title: response.status, message: 'Saved!', successBtnText: 'Ok', cancelBtnText: ''}); | |
} | |
$("#settingsPageModal").modal('hide'); | |
} | |
function customErrorsShow(fieldName, errorText) { | |
var fieldToChange = $(".settings form input[name=\"" + fieldName + "\"]").closest('.box'); | |
$(fieldToChange).find('input').addClass('error'); | |
var form = $(fieldToChange).closest('form.main-form'); | |
var formName = $(form).attr('name'); | |
var accountSettingsTab = $('#contact-settings'); | |
var profileSettingsTab = $('#profile-settings'); | |
var paymentSettingsTab = $('#paymentSettingsTab'); | |
switch(formName) { | |
case 'contactForm': | |
accountSettingsTab.removeClass('fa-check-square-o').addClass('fa-warning'); | |
break; | |
case 'profileForm': | |
profileSettingsTab.removeClass('fa-check-square-o').addClass('fa-warning'); | |
break; | |
case 'paymentForm': | |
paymentSettingsTab.removeClass('fa-check-square-o').addClass('fa-warning'); | |
break; | |
default: | |
} | |
/*$(fieldToChange).find('label.error').css("opacity", 1).show();*/ | |
/*$(fieldToChange).find('label.error').text(errorText);*/ | |
} | |
function editButtonHandle(e) { | |
e.preventDefault(); | |
onSavePostCode = true; | |
onSavePostCodePayment = true; | |
$('#saveSettingsBtnLoader').addClass('show-loader'); | |
/*var cur = $(this);*/ | |
/*settingsFormValid = $('form[name="contactForm"]').valid();*/ | |
/*if(settingsFormValid) { | |
$('#contact-settings').removeClass('fa-warning').addClass('fa-check-square-o');*/ | |
/*if(cur.closest('.'+box).hasClass(activeClass)){ | |
cur.closest('.'+box).removeClass(activeClass); | |
} else { | |
cur.closest('.'+box).addClass(activeClass); | |
cur.closest('.box').find('h2').text(cur.closest('.box').find('input').val());*/ | |
/*$('#loadSpinner').fadeIn(200);*/ | |
var form = prepareSettingsData(); | |
HTTPProvider.prepareSend({ method: "PUT", url: "/profile/settings/edit/"+userId }); | |
setTimeout(function(){ | |
HTTPProvider.send(form, settingsFormErrorHandler); | |
},0); | |
/*}*/ | |
/*}*/ | |
} | |
function editClientButtonHandle(e) { | |
e.preventDefault(); | |
$('#saveSettingsBtnLoader').addClass('show-loader'); | |
/*var cur = $(this);*/ | |
/*if(cur.closest('.'+box).hasClass(activeClass)){ | |
cur.closest('.'+box).removeClass(activeClass); | |
} else { | |
cur.closest('.'+box).addClass(activeClass); | |
cur.closest('.box').find('h2').text(cur.closest('.box').find('input').val());*/ | |
var form = prepareClientSettingsData(); | |
HTTPProvider.prepareSend({ method: "PUT", url: "/client-profile/settings/edit/"+userId }); | |
setTimeout(function(){ | |
/*HTTPProvider.send(form, settingsClientFormErrorHandler);*/ | |
HTTPProvider.send(form, settingsFormErrorHandler); | |
},0); | |
/*}*/ | |
} | |
function resizeHandle() { | |
/*if(win.width() < 768){ | |
setHeight('auto'); | |
} else { | |
setHeight(); | |
}*/ | |
} | |
function readFile(e) { | |
if (e.target.files && e.target.files[0]) { | |
var reader = new FileReader(); | |
reader.onload = function (e) { | |
uploadCropMediaOffer.croppie('bind', { | |
url: e.target.result | |
}); | |
}; | |
reader.readAsDataURL(e.target.files[0]); | |
} | |
else { | |
console.error("Sorry - your browser doesn't support the FileReader API"); | |
} | |
} | |
function photoUploadHandler(e) { | |
e.preventDefault(); | |
uploadCropMediaOffer.croppie('result', { | |
type: 'canvas', | |
size: 'original', | |
quality: 1 | |
}).then(function (resp) { | |
base64 = resp; | |
$("div.img-box").removeAttr("style"); | |
/*$("div.img-box").css("background", "url('"+base64+"') no-repeat"); | |
$("div.img-box").css("background-size", "cover");*/ /* replaced with img for proper dimensions - Yury V. */ | |
$("div.img-box img.img-uploaded").attr("src", base64); | |
settingsFormValid = $('form[name="contactForm"]').valid(); | |
paymentFormValid = $('form[name="paymentForm"]').valid(); | |
if(settingsFormValid && paymentFormValid) { | |
var form = prepareSettingsData(); | |
HTTPProvider.prepareSend({ method: "PUT", url: "/profile/settings/edit/"+userId }); | |
HTTPProvider.send(form, settingsFormErrorHandler); | |
} | |
}); | |
}; | |
function photoClientUploadHandler(e) { | |
e.preventDefault(); | |
uploadCropMediaOffer.croppie('result', { | |
type: 'canvas', | |
size: 'viewport' | |
}).then(function (resp) { | |
base64 = resp; | |
$("div.img-client-box").removeAttr("style"); | |
$("div.img-client-box").css("background", "url('"+base64+"') no-repeat"); | |
// $("div.img-box").css("background", "url('"+base64+"') no-repeat", "background-size", "cover"); | |
var form = prepareClientSettingsData(); | |
HTTPProvider.prepareSend({ method: "PUT", url: "/client-profile/settings/edit/"+userId }); | |
/*HTTPProvider.send(form, settingsClientFormErrorHandler);*/ | |
HTTPProvider.send(form, settingsFormErrorHandler); | |
}); | |
}; | |
function photoModalHandler(e) { | |
e.preventDefault(); | |
$('#settingsPageModal .changeImageContiner').empty().removeClass('croppie-container'); | |
$('#settingsPageModal button.upload-NewMedia').prop('disabled', true); | |
uploadCropMediaOffer = $('#settingsPageModal .changeImageContiner').croppie({ | |
viewport: { | |
width: 330, | |
height: 220 | |
}, | |
boundary: { | |
width: 360, | |
height: 300 | |
} | |
}); | |
setTimeout(function () { | |
$('#settingsPageModal .changeImageContiner').croppie('bind'); | |
}, 500); | |
uploadCropMediaOffer.croppie('bind', { | |
url: '/assets/images/media-no-image.gif' | |
}); | |
$("#settingsPageModal").modal(); | |
}; | |
function photoModalHandlerClient(e) { | |
e.preventDefault(); | |
$('#settingsPageModal button.upload-NewMedia').prop('disabled', true); | |
$('#settingsPageModal button.upload-client-NewMedia').prop('disabled', true); | |
$('#settingsPageModal .changeImageContiner').empty().removeClass('croppie-container'); | |
uploadCropMediaOffer = $('#settingsPageModal .changeImageContiner').croppie({ | |
viewport: { | |
width: 320, | |
height: 320, | |
type: 'circle' | |
}, | |
boundary: { | |
width: 320, | |
height: 320 | |
} | |
}); | |
setTimeout(function () { | |
$('#settingsPageModal .changeImageContiner').croppie('bind'); | |
}, 500); | |
uploadCropMediaOffer.croppie('bind', { | |
url: '/assets/images/media-no-image.gif' | |
}); | |
$("#settingsPageModal").modal(); | |
}; | |
if($(".settings").length) { | |
var win = $(window), | |
userId = "", | |
activeClass = 'active', | |
box = 'box', | |
settingsSection = $('.settings'), | |
sideBar = settingsSection.find('.sidebar'), | |
btnEdit = settingsSection.find('.btn-edit'), | |
btnClientEdit = settingsSection.find('.btn-client-edit'), | |
img, | |
file, | |
base64; | |
var uploadCropMediaOffer; | |
$('.settings input[type="radio"]').on('change', radioBoxEventHandler); | |
$('#settingsPageModal input[type="file"]').on('change', readFile); | |
$('#settingsPageModal button.upload-NewMedia').on('click', photoUploadHandler); | |
$('#settingsPageModal #uploadNewMedia').on('change', function () { | |
$('#settingsPageModal button.upload-NewMedia').prop('disabled', false); | |
}); | |
$('#settingsPageModal #uploadClientNewMedia').on('change', function () { | |
$('#settingsPageModal button.upload-client-NewMedia').prop('disabled', false); | |
}); | |
$('#settingsPageModal button.upload-client-NewMedia').on('click', photoClientUploadHandler); | |
$(".settings input[name=\"photo\"]").on('click', photoModalHandler); | |
$(".settings input[name=\"photoClient\"]").on('click', photoModalHandlerClient); | |
btnEdit.on('click', editButtonHandle); | |
btnClientEdit.on('click', editClientButtonHandle); | |
win.on('load resize orientationchange', resizeHandle); | |
} | |
$('form[name="contactForm"] input[name="settings_address"]').on('input', function () { | |
if($(this).val() === '') { | |
$('form[name="contactForm"] input[name="post_code"]').val(''); | |
$('form[name="contactForm"] input[name="city"]').val(''); | |
$('form[name="contactForm"] input[name="address_1"]').val(''); | |
} | |
}); | |
$('form[name="paymentForm"] input[name="settings_address"]').on('focus', function () { | |
onSavePostCode = false; | |
}); | |
$('form[name="paymentForm"] input[name="billing_address"]').on('focus', function () { | |
onSavePostCodePayment = false; | |
}); | |
function showLegalName() { | |
var val = $('#sel1').val(); | |
if(val === 'individual') { | |
$('#legal').hide(); | |
$('#legal_billing').hide(); | |
$('#vat_validate').hide(); | |
} else { | |
$('#legal').show(); | |
$('#legal_billing').show(); | |
$('#vat_validate').show(); | |
} | |
} | |
$( window ).on( 'load', showLegalName ); | |
$('#sel1').on('change', showLegalName); | |
/** | |
* Upload Mangopay verify documents | |
*/ | |
$('.settings').on('change', '.mangopay-docs', handleFileSelect); | |
function handleFileSelect(evt) { | |
var file = evt.target.files[0]; | |
var that = $(this); | |
var type = that.data('type'); | |
var reader = new FileReader(); | |
if ($.inArray(file.type, ['image/jpeg','image/png','image/gif','application/pdf', 'image/jpg']) === -1){ | |
that.parent().find('.error-mangopay').show(); | |
that.parent().find('.error-mangopay').html('You can upload only png, jpeg, jpg, gif, pdf file formant'); | |
return; | |
} | |
reader.readAsDataURL(file); | |
reader.onloadend = function( event ) { | |
var userId = JSON.parse(localStorage.getItem("user")).userId; | |
$.ajax({ | |
type: 'POST', | |
url: '/profile/verify', | |
data: { | |
'file': event.target.result, | |
'type': type, | |
'user': userId | |
}, | |
beforeSend: function(){ | |
$('#loadSpinner').fadeIn(200); | |
}, | |
complete: function(){ | |
$('#loadSpinner').fadeOut(500); | |
}, | |
success: function (resp) { | |
that.parent().find('.error-mangopay').hide(); | |
that.parent().html('<h5 class="mangopay-success">'+resp.message+'</h5>'); | |
}, | |
error: function (resp) { | |
that.parent().find('.error-mangopay').show(); | |
that.parent().find('.error-mangopay').html(resp.responseJSON.message); | |
} | |
}); | |
} | |
} | |
function stylePaymentFileUploaders(){ | |
var $paymentForm = $('.settings form[name="paymentForm"]'); | |
/*$('.settings form[name="paymentForm"] input[type="file"].mangopay-docs');*/ | |
var $uploadInputs = $paymentForm.find('input[type="file"].mangopay-docs'); | |
$paymentForm.find('.input-file-wraper').addClass('js-input-file-wrap'); | |
$uploadInputs.each(function(index, input){}); | |
} | |
/** icon for account settings **/ | |
$(document).ready( function () { | |
handleDocumentLoad(); | |
$("#payment_birth_date").datepicker({ | |
dateFormat: 'dd/mm/yy', | |
constrainInput: true, | |
autoSize: true, | |
changeMonth: true, | |
changeYear: true, | |
yearRange: "1940:c", | |
maxDate: 0 | |
}); | |
}); | |
function handleDocumentLoad(){ | |
$(document).on("keydown keypress", "#payment_birth_date", function(e) { | |
e.preventDefault(); | |
return false; | |
}); | |
var paymentAutocompService = new GoogleAutocompleteServicePayment(), | |
isAvailablePaymentForm = paymentAutocompService.getFormElements('.settings form[name="paymentForm"]'); | |
if(isAvailablePaymentForm){ | |
paymentAutocompService.initAutoComplete(); | |
} | |
stylePaymentFileUploaders(); | |
} | |
$('input[name=address_1]#address_1').on('change', function () { | |
console.warn('adress changed') | |
}) | |
$('form[name=contactForm] select[name=country]').on('change', function(){ | |
if ($(this).find(":selected").length && $(this).find(":selected").data()){ | |
$('form[name=contactForm] input[name=currency]#artist-currency').val($(this).find(":selected").data().currency); | |
$('form[name=contactForm] input[name="settings_address"]').val(''); | |
$('form[name=contactForm] input[name="address_1"]').val(''); | |
$('form[name=contactForm] input[name="address_2"]').val(''); | |
$('form[name=contactForm] input[name="city"]').val(''); | |
$('form[name=contactForm] input[name="post_code"]').val(''); | |
} | |
}); | |
$('#settings_address').on('keyup', function(e) { | |
if($('#settings_address').val().length == 0) { | |
$('form[name=contactForm] input[name=address_1]#address_1').val(''); | |
$('form[name=contactForm] input[name=city]#city').val(''); | |
$('form[name=contactForm] input[name=post_code]').val(''); | |
} | |
}); | |
'use strict'; | |
if (document.querySelector('#payment_settings')) { | |
app_payment_settings = new Vue({ | |
el: '#payment_settings', | |
delimiters: ['${', '}'], | |
data: { | |
appUserAccountAddress: null, | |
appUserBillingAddress: null, | |
payment_form: { | |
billingSameAsAccountAddress: false, | |
isUKaccount: false, | |
isIBAN: false, | |
country: null, | |
currency: null, | |
billingAddress: { | |
billing_address: null, | |
address_line_one: null, | |
address_line_two: null, | |
legal_city: null, | |
legal_representative_postcode: null | |
}, | |
address_2: null, | |
city: null, | |
post_code: null, | |
vatRegistered: false, | |
vatNumber: null, | |
vatValidation: false, | |
vatValid: false, | |
vatUserConfirm: false, | |
vatFullValid: false, | |
sort_code_1: null, | |
sort_code_2: null, | |
sort_code_3: null, | |
sort_code_full: null, | |
uk_account_number: null, | |
iban_1: null, | |
iban_2: null, | |
iban_3: null, | |
iban_4: null, | |
iban_5: null, | |
iban_6: null, | |
iban_7: null, | |
iban_8: null, | |
iban_full: null | |
} | |
}, | |
created: function () { | |
if ( appUserAccountAddress | |
/* && appUserAccountAddress.hasOwnProperty('address_settings') && appUserAccountAddress.address_settings*/ | |
&& appUserAccountAddress.hasOwnProperty('address_line_one') && appUserAccountAddress.address_line_one | |
&& appUserAccountAddress.hasOwnProperty('city') && appUserAccountAddress.city | |
/*&& appUserAccountAddress.hasOwnProperty('postcode') && appUserAccountAddress.postcode - temp.disabled, waiting clarification */ ) | |
{ | |
this.appUserAccountAddress = appUserAccountAddress; | |
} | |
if (appUserBillingAddress){ | |
this.appUserBillingAddress = appUserBillingAddress; | |
this.payment_form.billingAddress = appUserBillingAddress; | |
} | |
}, | |
methods: { | |
handle_vatRegistered: function () { | |
var self = this; | |
}, | |
hanleAddressInputChange: function (e) { | |
var self = this; | |
setTimeout(function(){ | |
var addrBillingLineOne = $('form[name=paymentForm] input[name="legal_address_line_one"]'); | |
var addrBillingLineTwo = $('form[name=paymentForm] input[name="legal_address_line_two"]'); | |
var addrBillingCity = $('form[name=paymentForm] input[name="legal_city"]'); | |
var addrBillingPostCode = $('form[name=paymentForm] input[name="legal_representative_postcode"]'); | |
self.payment_form.billingAddress = { | |
billing_address: e.target.value || null, | |
address_line_one: addrBillingLineOne[0].value || null, | |
address_line_two: addrBillingLineTwo[0].value || null, | |
legal_city: addrBillingCity[0].value || null, | |
legal_representative_postcode: addrBillingPostCode[0].value || null | |
}; | |
},400); | |
}, | |
handleBillingSameAsAccountAddress: function(){ | |
var self = this; | |
/*var settingsAutocomp_currentStore = settingsAutocompService.getCurrentStore();*/ | |
var appUserAccountValues = { | |
address_line_one: $('form[name="contactForm"] input[name="address_1"]')[0].value.trim() || null, | |
address_line_two: $('form[name="contactForm"] input[name="address_2"]')[0].value.trim() || null, | |
city: $('form[name="contactForm"] input[name="city"]')[0].value.trim() || null, | |
postcode: $('form[name="contactForm"] input[name="post_code"]')[0].value.trim() || null, | |
} | |
if ( appUserAccountValues && appUserAccountValues.address_line_one && appUserAccountValues.city ) | |
{ | |
self.appUserAccountAddress = appUserAccountValues; | |
} else { | |
self.appUserAccountAddress = null; | |
self.payment_form.billingSameAsAccountAddress = false; | |
} | |
if (self.payment_form.billingSameAsAccountAddress && self.appUserAccountAddress){ | |
self.payment_form.billingAddress.billing_address = null; | |
self.payment_form.billingAddress.address_line_one = self.appUserAccountAddress.address_line_one; | |
self.payment_form.billingAddress.address_line_two = self.appUserAccountAddress.address_line_two; | |
self.payment_form.billingAddress.legal_city = self.appUserAccountAddress.city; | |
self.payment_form.billingAddress.legal_representative_postcode = self.appUserAccountAddress.postcode; | |
} else { | |
self.payment_form.billingAddress.billing_address = null; | |
self.payment_form.billingAddress.address_line_one = null; | |
self.payment_form.billingAddress.address_line_two = null; | |
self.payment_form.billingAddress.legal_city = null; | |
self.payment_form.billingAddress.legal_representative_postcode = null; | |
} | |
}, | |
ibanInputOnChange: function (e) { | |
var self = this; | |
var ibanInputCollection = document.getElementsByClassName('input-iban-number'); | |
var concatValue = ''; | |
[].forEach.call(ibanInputCollection, function (input, index) { | |
concatValue += '' + input.value; | |
}); | |
self.payment_form.iban_full = concatValue; | |
}, | |
sortCodeInputOnChange: function (e) { | |
var self = this; | |
var ibanInputCollection = document.getElementsByClassName('input-sort-code'); | |
var concatValue = ''; | |
[].forEach.call(ibanInputCollection, function (input, index) { | |
concatValue += '' + input.value; | |
}); | |
self.payment_form.sort_code_full = concatValue; | |
}, | |
setSortCode: function (value) { | |
var self = this; | |
if (value && value.length == 6){ | |
self.payment_form.sort_code_1 = value.substr(0,2) || null; | |
self.payment_form.sort_code_2 = value.substr(2,2) || null; | |
self.payment_form.sort_code_3 = value.substr(4,2) || null; | |
} | |
}, | |
verifyVAT: function (e) { | |
var self = this; | |
var legalRepresentativeCountryResidenceVal = ($('form[name=paymentForm] select[name="legal_representative_country_of_residence"]').length) ? $('form[name=paymentForm] select[name="legal_representative_country_of_residence"]')[0].value : ''; | |
var sendData = { | |
country_code: legalRepresentativeCountryResidenceVal, | |
vat_number: self.payment_form.vatNumber || '' | |
}; | |
$('#loadSpinner').fadeIn(200); | |
return $.ajax({ | |
type: 'PATCH', | |
data: JSON.stringify(sendData), | |
url: '/profile/vat/verify', | |
contentType: 'application/json;charset=utf-8', | |
dataType: 'json' | |
}).done(function (response, status) { | |
var patt = new RegExp(/invalid/gi); | |
var isVATInvalid = patt.test(response.message); | |
$('#loadSpinner').fadeOut(500); | |
self.payment_form.vatFullValid = !isVATInvalid; | |
self.payment_form.vatValidation = true; | |
self.payment_form.vatValid = true; | |
/** | |
* @todo Yury should check that part of code | |
*/ | |
var message = self.formedSuccessVatMessage(response.data); | |
handleOpenConfirmModal({isAlert: isVATInvalid, title: 'VAT verification', message: message}); | |
}).fail(function (response, status) { | |
$('#loadSpinner').fadeOut(500); | |
var errorMessage = 'an error occured'; | |
if (response.hasOwnProperty('responseJSON') && response.responseJSON && response.responseJSON.hasOwnProperty('message') && response.responseJSON.message){ | |
errorMessage = ''; | |
for (var errKey in response.responseJSON.message){ | |
errorMessage += response.responseJSON.message[errKey] + ' </br> '; | |
} | |
} | |
handleOpenConfirmModal({isAlert: true, title: 'Error', message: errorMessage}); | |
}); | |
}, | |
formedSuccessVatMessage: function(data) { | |
return '<table>' + | |
'<tr>' + | |
'<td style="color: green;">Name: </td>' + | |
'<td>'+data.name+'</td>' + | |
'</tr>' + | |
'<tr>' + | |
'<td style="color: green;">Address: </td>' + | |
'<td> '+data.address+'</td>' + | |
'</tr>' + | |
'</table>'; | |
}, | |
updateVATValidationStatus: function (status) { | |
var self = this; | |
} | |
} | |
}); | |
} | |
}); | |
var app_payment_settings; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment