define([
'jquery',
'vendor/backbone',
'vendor/underscore',
'lib/components/base/modal',
'twigjs',
'lib/components/notes/notes',
'lib/components/base/player',
'lib/common/urlparams',
'lib/common/fn'
], function($, Backbone, _, Modal, twig, NotesWrapper, Player, url_params, Fn){
var captchaFail = 0;
var Settings = {
View: Backbone.View.extend({
tagName: "div",
className: "twilio_modal",
events: {
'click .twilio__nav__item': 'nav_router',
'click .twilio__setup__tariff__item': 'setup_tarif',
'click .twilio__setup__search__result__item': 'setup_search',
'click .twilio__setup__search__result__item__suggest__btn_buy': 'buy_number',
'click .twilio__setup__search__result__item__suggest__btn_no': 'close_suggest',
'click .twilio__suggest__close': 'close_suggest',
'click .intl-tel-input': 'close_suggest',
'click document': 'close_suggest',
'click .twilio__modal__close': 'close_modal',
'click .btn__done': 'close_modal',
'keyup .twilio__setup__tariff__search-number__input' : 'search__numbers',
'click .country' : 'changeCountry',
'click .twilio__setup__y__input': 'changeStatus',
'click #twilio_sms_send':'send_sms',
'click #twilio_code_submit':'send_code',
'click .twilio__setup__tariff__search-number__text span':'showSearch',
'click #twilio_verify_user__next_step':'showBuyNumberTpl',
'click .twilio_verify_user__current__number__text__change_number' : 'change_verify_number',
'click .twilio_verify_user__captcha__refresh' : 'refresh_captcha',
'click .twilio__setup__y__balance__trial span' : 'trial_stop',
'click .twilio__billing_trial_plug__upgrade' : 'trial_stop',
'click .twilio_allready_link' : 'already_setup',
'click #twilio_sidtoken_submit' : 'save_exists_master',
'change .control--select' : 'billing_period',
'click .twilio_verify_user_link' : 'showLink',
'click .twilio__refresh__credits': 'refreshBalance',
'click .twilio__setup__credits_password_show': 'showTwilioPass',
'click .twilio__setup__y__balance__add-credits':'addCredits'
},
//_selectors: function () {
// return {
// trigger: '#twilio__nav__current'
// }
//},
initialize: function(params) {
//Нужен костыль. Собрать весь локал сторадж кроме твилио, далее почистить, а потом собрать назад.
//Или поработать только с записью в локалсторадж твилио
//Короче тут мы еще думаем
//Время мало
//Смело!!
AMOCRM.widgets.clear_cache();
if(params.widget.config.debug)console.log('settings',params);
this.widget = params.widget;
this.modal = params.modal;
this.modal.html(this.$el);
$('head').append('<link id="'+this.widget.params.widget_code+'_style" rel="stylesheet" href="' + this.widget.params.path + '/styles.css" type="text/css" />');
this.render();
return true;
},
render: function(callback){
var _this = this;
this.render_tpl({},function(){
var t={};
switch(_this.widget.params.status){
case "new_user":
t.tpl="about";
break;
case "verify":
t.tpl="verify";
break;
case "nonumber":
t.tpl="setup";
break;
case "suspended":
TW2.widget_status = "N";
t.tpl="settings";
break;
case "active":
t.tpl="settings";
break;
case "not_support":
t.tpl="support";
break;
case "flash_not_installed":
t.tpl="not_flash";
break;
case "help":
t.tpl="steps";
break;
case "amocrm_trial":
t.tpl="amo_trial";
break;
default:
t.tpl="plug";
}
t.place='.twilio__content';
_this.render_tpl(t,function(){
switch(_this.widget.params.status){
case "new_user":
$('#twilio__nav__current').removeClass();
break;
case "verify":
$('#twilio__nav__current').addClass("second second_btn");
$(".twilio_verify_user__send-sms__input__countries").intlTelInput();
$('.country-list').on('click', function(){
var current_country = $('.selected-flag').attr('title').split(': ')[1];
$('.twilio_verify_user__send-sms__input__countries').html( current_country );
});
break;
case undefined:
//_this.add_modal_plug();
$('#twilio__nav__current').addClass('second small');
$('.twilio__modal__plug').append('<br/><a href='+_this.widget.config.node_path+'>'+_this.widget.config.node_path+'</a>');
break;
case "nonumber":
$('#twilio__nav__current').removeClass("second small");
$('#twilio__nav__current').addClass("second setup");
$("#twilio__setup__input").intlTelInput({
onlyCountries: ["au", "at", "bh", "be", "br", "bg", "ca", "cy",
"cz", "de", "dk", "do", "sv", "ee", "fi", "fr", "gr", "hk", "ie", "il", "it", "jp",
"lv", "lt", "lu", "mt", "mx", "nl", "no", "nz", "pe", "pl", "pt", "pr", "ro",
"sk", "za", "es", "se", "ch", "gb", "us"]
});
var current_country = $('.selected-flag').attr('title').split(':')[0];
$('.selected-flag').append('<div class="twilio_current_country">'+ current_country +'</div>');
$('.country-list').on('click', function(){
var current_country = $('.selected-flag').attr('title').split(':')[0];
$('.twilio_current_country').html( current_country )
});
_this.get_available_numbers();
break;
case "suspended":
case "active":
$('#twilio__nav__current').removeClass("second small");
$('#twilio__nav__current').addClass("second");
$('.twilio__setup__y__your_number').intlTelInput();
$('.arrow').hide();
$('.country-list.hide').hide();
break;
case "help":
$('#twilio__nav__current').addClass("second second_btn");
break;
case "amocrm_trial":
$('#twilio__nav__current').removeClass();
$('.modal-body').addClass('twilio_advanced_plug');
break;
default:
$('#twilio__nav__current').addClass('second small');
}
});
});
},
add_modal_plug : function(){
$('.twilio_modal').addClass('twilio__plug');
$('.modal-scroller').addClass('twilio__overflow');
},
remove_modal_plug : function() {
$('.twilio_modal').removeClass('twilio__plug');
$('.modal-scroller').removeClass('twilio__overflow');
},
nav_router:function(e){
var $this = $(e.target),
_this = this,
$content = $('.twilio__content'),
nav_spinner = '<div class="twilio_content_button-input__spinner button-input__spinner"><span class="button-input__spinner__icon spinner-icon"></span></div>';
if($this.hasClass('active')) {
return;
}
$('.twilio__nav__item').removeClass('active');
$this.addClass('active');
// "Избегайте дублирования кода" (c) Чеклист
if($this.hasClass('about')){
$content.html(nav_spinner);
this.render_tpl({
tpl:'about',
place:'.twilio__content'
});
$('#twilio__nav__current').removeClass();
}else if ($this.hasClass('help')){
this.render_tpl({
tpl:'steps',
place:'.twilio__content'
});
$('#twilio__nav__current').removeClass().addClass('second second_btn');
}else if ($this.hasClass('plug')) {
this.render_tpl({
tpl:'plug',
place:'.twilio__content'
});
$('#twilio__nav__current').removeClass().addClass('second small');
}else if($this.hasClass('verify')) {
$content.html(nav_spinner);
// Двигаем ползунок
$('#twilio__nav__current').removeClass().addClass('second'+($this.hasClass('settings settings__btn')?'':' second_btn'));
this.render_tpl({
tpl:'verify',
place:'.twilio__content',
data:{
verify_number: this.widget.params.verify_number,
country_code: this.widget.params.country_code,
show_captcha: this.widget.params.show_captcha
},
},function(){
$(".twilio_verify_user__send-sms__input__countries").intlTelInput();
$('.country-list').on('click', function(){
var current_country = $('.selected-flag').attr('title').split(': ')[1];
$('.twilio_verify_user__send-sms__input__countries').html( current_country );
});
});
}else if ($this.hasClass('btn') || $this.hasClass('settings settings__btn')){
$content.html(nav_spinner);
$('#twilio__nav__current').removeClass().addClass('second'+($this.hasClass('settings settings__btn')?'':' second_btn'));
this.render_tpl({
tpl:'setup',
place:'.twilio__content'
},function(){
$("#twilio__setup__input").intlTelInput({
onlyCountries: ["au", "at", "bh", "be", "br", "bg", "ca", "cy",
"cz", "de", "dk", "do", "sv", "ee", "fi", "fr", "gr", "hk", "ie", "il", "it", "jp",
"lv", "lt", "lu", "mt", "mx", "nl", "no", "nz", "pe", "pl", "pt", "pr", "ro",
"sk", "za", "es", "se", "ch", "gb", "us"]
});
var current_country = $('.selected-flag').attr('title').split(':')[0];
$('.selected-flag').append('<div class="twilio_current_country">'+ current_country +'</div>');
$('.country-list').on('click', function(){
var current_country = $('.selected-flag').attr('title').split(':')[0];
$('.twilio_current_country').html( current_country )
});
_this.get_available_numbers();
});
}else if($this.hasClass('settings')){
$content.html(nav_spinner);
this.render_tpl({
tpl:'settings',
place:'.twilio__content'
},function(){
$('.twilio__setup__y__your_number').intlTelInput();
$('.arrow').hide();
$('.country-list.hide').hide();
});
$('#twilio__nav__current').removeClass().addClass('second');
}else if ($this.hasClass('billing')){
$('.twilio__content').html(nav_spinner);
$this.addClass('disable_click');
if(this.widget.params.trial) {
this.render_tpl({
tpl:'billing',
place:'.twilio__content'
},function(){
$this.removeClass('disable_click');
});
}else{
_this.add_modal_plug();
//Рендерим биллинг со всей историей.
var start_date = start_date || null,
end_date = end_date || null,
_this = this;
this.widget.node_request('billing/'+start_date+'/'+end_date+'', function (response, error) {
if(error){
console.log(error);
return;
_this.remove_modal_plug();
}
var t=[];
for(var i in response.usageRecords){
var category = response.usageRecords[i].category,
count = response.usageRecords[i].count,
price = response.usageRecords[i].price;
price = parseInt(price).toFixed(2);
t.push({
category:category,
count: count,
price: price});
}
var arr = response.usageRecords.length;
while (arr--) {
if (response.usageRecords[arr].category === "totalprice") {
var total = response.usageRecords[arr].price;
}
}
total = parseInt(total).toFixed(2);
console.log(total);
//var total = response.usageRecords[10].price;
_this.render_tpl({
tpl:'billing',
place:'.twilio__content',
data:{
items:t,
totalPrice: total
}
},function(){
$this.removeClass('disable_click');
});
_this.remove_modal_plug();
});
}
$('#twilio__nav__current').removeClass().addClass('third');
}
},
get_billing: function(start_date, end_date, $this) {
var start_date = start_date || null,
end_date = end_date || null,
_this = this;
var spinner = '<div class="twilio_btn_spinner__billing button-input__spinner"><span class="button-input__spinner__icon spinner-icon"></span></div>';
$('.twilio__billing').addClass('trial').append(spinner);
this.widget.node_request('billing/'+start_date+'/'+end_date+'', function (response, error) {
$('.twilio__billing').removeClass('trial');
$('.button-input__spinner').remove();
if(error){
console.log(error);
return;
_this.remove_modal_plug();//Это никогда не выполнится.
}
var t=[];
for(var i in response.usageRecords){
var category = response.usageRecords[i].category,
count = response.usageRecords[i].count,
price = response.usageRecords[i].price;
price = parseInt(price).toFixed(2);
t.push({
category:category,
count: count,
price: price});
}
var arr = response.usageRecords.length;
while (arr--) {
if (response.usageRecords[arr].category === "totalprice") {
var total = response.usageRecords[arr].price;
}
}
total = parseInt(total).toFixed(2);
if(_this.widget.config.debug)console.log(total);
//var total = response.usageRecords[10].price;
_this.render_tpl({
tpl:'billing_table',
place:'.twilio__table',
data:{
items:t,
totalPrice: total
}
},function(){
$('.type__total__history span').html('$'+total);
});
_this.remove_modal_plug();
});
},
showSearch: function() {
$('.twilio__setup__tariff__search-number__text').hide();
$('.twilio__setup__tariff__search-number__input').show().focus();
},
changeStatus: function(e) {
var $input = $('.twilio__setup__y__input').find('.switcher');
if($input.hasClass('switcher__on')) {
// Выключаем виджет
this.active_toggler("N");
this.widget.active_toggle(false);
} else {
// Включаем виджет
this.active_toggler("Y");
this.widget.active_toggle(true);
}
if(e)e.preventDefault();
},
active_toggler: function(active){
AMOCRM.widgets.clear_cache();
var _this = this;
active = active||_this.widget.params.widget_active;
$.ajax({
url: '/ajax/widgets/edit',
method: 'POST',
data: {
action: 'edit',
id: _this.widget.config.widget_id,
code: _this.widget.params.widget_code,
widget_active: active
}
}).done(_.bind(function (data) {
_this.widget.params.widget_active = active;
if(_this.widget.config.debug)console.log(data.response);
if (active == 'Y') {
$('#amo_twilio2').removeClass('install').addClass('installed');
$(document).trigger('widget:' + _this.widget.params.widget_code + ':installed');
$(document).trigger('widget:installed', [_this.widget.params.widget_code, data.response.new_settings]);
}else{
//localStorage.clear();
$('#amo_twilio2').removeClass('installed').addClass('install');
$(document).trigger('widget:' + _this.widget.params.widget_code + ':removed');
$(document).trigger('widget:removed', [_this.widget.params.widget_code, data.response.new_settings]);
}
}));
},
close_suggest: function () {
$('#twilio__setup__search__result__item__suggest').remove();
$('.twilio__setup__search__result__item').removeClass('active');
},
search__numbers: function() {
this.close_suggest();
if($('.button-input__spinner').length == 1) {
}else {
$('.twilio__setup__tariff__search-number').append('<div class="button-input__spinner"><span class="button-input__spinner__icon spinner-icon"></span></div>');
}
if (this.dt) {
clearTimeout(this.dt);
}
this.dt=setTimeout(function() {
this.get_available_numbers();
}.bind(this), 700);
},
changeCountry: function(e) {
if($('.button-input__spinner').length == 1) {
}else {
$('.twilio__setup__tariff__search-number').append('<div class="button-input__spinner"><span class="button-input__spinner__icon spinner-icon"></span></div>');
}
var current_country = null,
_this = this;
if (current_country == e.currentTarget.dataset.countryCode.toUpperCase()) {
} else {
current_country = e.currentTarget.dataset.countryCode.toUpperCase();
_this.get_available_numbers(current_country);
}
},
get_available_numbers: function (current_country) {
var _this=this;
var type = $('.twilio__setup__tariff__item.active').attr('value'),
country = current_country || $('.country.active').data('country-code').toUpperCase(),
mask = $('.twilio__setup__tariff__search-number__input').val().replace('%', 'p') || "null";
// постоянно выпадает ошибка с маской, там где она не используется
_this.add_modal_plug();
this.widget.node_request('getavailablenumbers', function (response, error) {
if (error) {
if(_this.widget.config.debug)console.log(error);
if(error.code == 20404) {
_this.remove_modal_plug();
$('.twilio__setup__search__result').html('<div class="twilio_search_error" style="font-size: 15px; color: #f37575">For this country Toll-Free numbers, are not available.</div>')
}else{
_this.remove_modal_plug();
$('.twilio__setup__search__result').html('<div class="twilio_search_error" style="font-size: 15px; color: #f37575">Your mask is not valid</div>')
}
} else {
if(response.length == 0) {
_this.remove_modal_plug();
$('.twilio__setup__search__result').html('<div class="twilio_search_error" style="font-size: 15px; color: #f37575">There\'s no numbers by your mask.</div>')
}else{
this.render_tpl({
tpl:'search_result',
data:{
item: response
},
place:'.twilio__setup__search__result'
}, function(){
_this.remove_modal_plug();
});
}
}
$('.modal-body').trigger('modal:centrify');
$('.button-input__spinner').remove();
}.bind(this),{
type:type ,
country: country,
mask: mask
});
},
setup_tarif:function(e){
this.close_suggest();
if (!$(e.target).hasClass('active')){
$('.twilio__setup__tariff__item').removeClass('active');
$(e.target).addClass('active');
}else {
return;
}
this.get_available_numbers();
if($('.button-input__spinner').length == 1) {
}else {
$('.twilio__setup__tariff__search-number').append('<div class="button-input__spinner"><span class="button-input__spinner__icon spinner-icon"></span></div>');
}
},
buy_number:function() {
var spinner = '<div class="twilio_btn_spinner button-input__spinner"><span class="button-input__spinner__icon spinner-icon"></span></div>';
$('.twilio__setup__search__result__item__suggest__btn_buy').html(spinner);
var number = $('.twilio__setup__search__result__item__suggest__span').text();
var _this = this;
if(this.widget.config.debug)console.log(number);
_this.add_modal_plug();
this.widget.node_request(_this.widget.config.use_fake?'fake_purchase':'purchase', _.bind(function (response, error){
if(_this.widget.config.debug)console.log('<-------------purchase------------>');
if(_this.widget.config.debug)console.log(response);
if(_this.widget.config.debug)console.log(error);
if(error){
_this.remove_modal_plug();
//Срочно
}else{
if(response.error){
_this.remove_modal_plug();
//Срочно
}else{
_this.remove_modal_plug();
_this.widget.params.widget_active = 'Y';
_this.widget.params.my_number = number;
_this.widget.params.status = 'active';
//_this.get_token();
_this.widget.get_token(function(){
//_this.render.bind(_this)
_this.render_tpl({
tpl:'modal'
}, function() {
_this.render_tpl({
tpl:'settings',
place:'.twilio__content'
}, function() {
$('.twilio__setup__y__your_number').intlTelInput();
_this.remove_modal_plug();
$(".twilio_verify_user__send-sms__input__countries").intlTelInput();
$('.twilio__setup__y').append('<div class="button-input button-input-with-menu btn__done btn__done">Done</div>');
});
$('#twilio__nav__current').addClass('second');
})
});
//_this.render();
_this.active_toggler("Y");
}
}
}, this), {number: number});
},
close_modal: function () {
//todo вызвать destroy
$('body').find('.modal').remove();
$('body').css({'overflow-y':'scroll'});
$('#page_holder').css({'overflow-y':'auto'});
//this.widget.destroy();
},
setup_search:function(e){
var suggest_number = '<div id="twilio__setup__search__result__item__suggest" class="twilio__setup__search__result__item__suggest">\n ' +
' <span class="twilio__suggest__close"></span>\n' +
' <div class="twilio__setup__search__result__item__suggest__title">Do you want to buy number ' +
'<span class="twilio__setup__search__result__item__suggest__span">+1 201 523 4580</span> for ';
if(this.widget.params.trial){
suggest_number+='free';
}else{
suggest_number+='$1.00';
}
suggest_number+='?</div>\n' +
' <div class="twilio__setup__search__result__item__suggest__container">\n' +
' <div class="twilio__setup__search__result__item__suggest__btn_buy">\n Buy\n' +
' </div>\n <div class="twilio__setup__search__result__item__suggest__btn_no">\n' +
' No\n </div>\n </div>\n</div>';
if (!$(e.target).hasClass('active')){
$('.twilio__setup__search__result__item').removeClass('active');
$(e.target).addClass('active');
var number = $(e.target).text();
if(this.$el.find('#twilio__setup__search__result__item__suggest')){
$('#twilio__setup__search__result__item__suggest').remove();
}
//console.log(number);
//var offset_target = $(e.target).offset();
//var position_target = $(e.target).position();
//this.$el.append(suggest_number);
//$('#twilio__setup__search__result__item__suggest').css({"left": offset_target.left, "top": + position_target.top });
//$('.twilio__setup__search__result__item__suggest__span').html(number);
var number_position = $(e.target).position();
$('.twilio__setup__search__result').append(suggest_number);
$('#twilio__setup__search__result__item__suggest').css({"left": number_position.left, "top": + number_position.top, "position":"absolute", "margin" : "-65px 0 0 130px" });
$('.twilio__setup__search__result__item__suggest__span').html(number);
}
},
destroy: function() {
console.log(2);
},
render_tpl: function(arg,callback){
arg = arg || {};
arg.tpl = arg.tpl || 'modal';
var t={
status: this.widget.params.status,
current_number: this.widget.params.my_number,
widget_status: this.widget.params.widget_active,
trial: this.widget.params.trial,
verify_number: this.widget.params.verify_number,
country_code: this.widget.params.country_code,
show_captcha: this.widget.params.show_captcha,
captcha: this.widget.params.captcha,
version: this.widget.config.version,
balance: this.widget.params.balance
},
place = arg.place || this.$el,
data = _.extend(t,arg.data),
_this = this;
if(_this.widget.config.debug)console.log(arg);
this.widget.getTemplate(
arg.tpl,
{},
_.bind(function (template) {
if(_this.widget.config.debug)console.log(data);
$(place).html(template.render(data));
$('.modal-body').trigger('modal:centrify');
if(callback)callback();
return true;
},this)
);
return true;
},
send_sms:function(e){
var _this = this;
var spinner = '<div class="twilio_btn_spinner button-input__spinner"><span class="button-input__spinner__icon spinner-icon"></span></div>';
var $input_number = $('.twilio_verify_user__send-sms__input').val().trim(),
$national_code = $('.twilio_verify_user__send-sms__input__countries').text(),
$number;
$('.twilio__verify__error').hide();
//console.log($input_number,$national_code);
if($input_number.indexOf('+')!=-1){
var error='Please remove country code from input';
}else{
$number=$national_code + $input_number.replace(/\D/g,'');
if($number.length<8 || $number.length>12){
var error='Invalid number!';
}
}
//console.log($number);
if(error){
$('<div class="twilio__verify__error">'+error+'</div>').insertAfter( '.twilio_verify_user__current__number' );
$('.twilio_verify_user__send-sms__input').focus();
e.preventDefault();
$('.twilio_content_button-input__spinner').hide();
$('.twilio_verify_user__current__number__text__change_number').show();
$('.twilio_verify_user__send-sms__input').addClass("input_error");
setTimeout(function(){$('.twilio_verify_user__send-sms__input').removeClass("input_error");},1500);
return;
}else{
$('.twilio_verify_user__text').hide();
_this.widget.params.status = "verify";
_this.widget.params.verify_number = $number; //Иначе пропадет код
}
var $flag = $('.flag-dropdown').find('.selected-flag').children('.flag').clone();
var $country_code = $('.flag-dropdown').find('.selected-flag').children('.flag').attr('class').split(' ')[1];
$('.twilio_verify_user__current__number__flags').html($flag);
$('.twilio_verify_user__current__number__text').html($number);
$('.twilio_verify_user__send-sms').hide();
$('.twilio_verify_user__current__number').show();
$('.twilio_content_button-input__spinner').show();
$('<div class="twilio__verify__info">Please wait a sms code for verification</div>').insertAfter( '.twilio_verify_user__current__number' );
_this.add_modal_plug();
this.widget.node_request(_this.widget.config.use_fake?'fake_verify':'verify', function (response, error){
if(error){
_this.remove_modal_plug();
$('.twilio__verify__info').hide()
if(_this.widget.config.debug)console.error("ERROR",error);
_this.widget.get_token(null,true);
//Надо отфильтровать когда падает нода
if(error != 'undefined' && error.text){
var error_type = error.text,
error_msg = '';
if( error_type.indexOf('invalid') >= 0){
error_msg = 'Invalid-number';
}else if ( error_type.indexOf('limit') >= 0){
error_msg = 'Limit reached by your number, please contact with support';
}else if ( error_type.indexOf('landline') >= 0){
error_msg = 'Landline-number, enter another phone.';
}else {
error_msg = error.text;
}
}else{
error_msg=error;
}
$('<div class="twilio__verify__error">'+error_msg+'</div>').insertAfter( '.twilio_verify_user__current__number' );
if (error.text.indexOf('mail')!=-1){
var mail_err = error.text.split('Mail ')[1];
$('.twilio__verify__error').addClass('mail').html(mail_err);
$('<div class="twilio_allready_link">Already have an account?</div>').insertAfter('.twilio__verify__error');
}
$('.twilio_content_button-input__spinner').hide();
$('.twilio_verify_user__current__number__text__change_number').show();
_this.change_verify_number();
}else {
_this.remove_modal_plug();
$('.twilio__verify__info').hide();
_this.widget.params.verify_number = $number;
_this.widget.params.country_code = $country_code;
_this.widget.params.show_captcha = response.show_captcha ;
_this.widget.params.captcha = response.url;
if(response.show_captcha){
$('.twilio_verify_user__captcha').show();
}
$('.twilio_verify_user__codes_container').show();
$('.twilio_verify_user__current__number__text__change_number').show();
$('.twilio_verify_user__send__btn').show();
$('.twilio_content_button-input__spinner').hide();
$('.twilio_verify_user__verification-code').show();
$('.twilio_verify_user__captcha__img').html('<img src="'+ response.url +'">');
}
},{
number:$number,
country_code: $country_code,
mail:AMOCRM.constant('user').login,
first_name:AMOCRM.constant('user').name.split(' ')[0],
second_name:AMOCRM.constant('user').name.split(' ')[1]
});
},
send_code:function(){
var _this = this;
var $input_number = _this.widget.params.verify_number,
$national_code = _this.widget.params.country_code,
$number = $input_number,
code=parseInt(document.querySelector('.twilio_verify_user__verification-code__input').value.replace(' ','')),
captcha = document.querySelector('#twilio_verify_user__captcha').value;
var spinner = '<div class="twilio_btn_spinner button-input__spinner"><span class="button-input__spinner__icon spinner-icon"></span></div>';
$('.twilio__verify__error').hide();
$('#twilio_code_submit').html(spinner);
if(code.toString().length!=6){
console.error('Invalid code!');
$('<div class="twilio__verify__error">Invalid code!</div>').insertAfter( '.twilio_verify_user__verification-code' );
$('#twilio_code_submit').html('Submit');
return;
}else{
document.querySelector('.twilio_verify_user__verification-code__input').value=code;
}
if(_this.widget.params.show_captcha){
if(!/^[\da-zA-Z ]{3,}$/.test(captcha)){
console.error('Invalid captcha!');
$('<div class="twilio__verify__error">Invalid captcha.</div>').insertAfter( '.twilio_verify_user__captcha' );
$('#twilio_code_submit').html('Submit');
return;
}
}
var spinner = '<div class="twilio_btn_spinner button-input__spinner"><span class="button-input__spinner__icon spinner-icon"></span></div>';
$('#twilio_code_submit').html(spinner);
_this.add_modal_plug();
this.widget.node_request(_this.widget.config.use_fake?'fake_sms':'sms', function (response, error) {
if(_this.widget.config.debug)console.log('<--sms-->');
if(_this.widget.config.debug)console.log(response);
if(_this.widget.config.debug)console.log(error);
if(error || response.code==400){
error=error||response.message.message;
}
if (error){
++captchaFail;
if (captchaFail >= 3) {
$('.twilio_verify_user__captcha').show();
_this.widget.params.status = "help";
_this.render_tpl({
tpl:'steps',
place:'.twilio__content'
});
}
_this.remove_modal_plug();
if(response && response.code==400){
_this.change_verify_number();
_this.refresh_captcha();
_this.widget.get_token(null, true);
}else{
_this.refresh_captcha();
}
if(typeof error != 'string')error=JSON.stringify(error);
$('<div class="twilio__verify__error">'+error+'</div>').insertAfter( '.twilio_verify_user__current__number' );
$('#twilio_code_submit').html('Submit');
return;
}else{
_this.widget.params.status = "nonumber";
_this.widget.params.trial = true;
_this.render_tpl({
tpl:'modal'
}, function() {
_this.render_tpl({
tpl:'setup',
place:'.twilio__content'
}, function(){
$("#twilio__setup__input").intlTelInput({
onlyCountries: ["au", "at", "bh", "be", "br", "bg", "ca", "cy",
"cz", "de", "dk", "do", "sv", "ee", "fi", "fr", "gr", "hk", "ie", "il", "it", "jp",
"lv", "lt", "lu", "mt", "mx", "nl", "no", "nz", "pe", "pl", "pt", "pr", "ro",
"sk", "za", "es", "se", "ch", "gb", "us"]
});
var current_country = $('.selected-flag').attr('title').split(':')[0];
$('.selected-flag').append('<div class="twilio_current_country">'+ current_country +'</div>');
$('.country-list').on('click', function(){
var current_country = $('.selected-flag').attr('title').split(':')[0];
$('.twilio_current_country').html( current_country )
});
_this.get_available_numbers();
});
$('#twilio__nav__current').addClass('second setup');
_this.remove_modal_plug();
});
}
},{
number:$number,
code:code,
captcha:captcha,
auth_key:this.widget.params.auth_key,
login:AMOCRM.constant('user').login,
api_key:this.widget.system().amohash
});
},
change_verify_number: function() {
$('.twilio_verify_user__current__number').hide();
$('.twilio_verify_user__send-sms').show();
$('.twilio_verify_user__text').show();
$('.twilio_verify_user__verification-code__input').val('');
$('.twilio_verify_user__verification-code').hide();
$('.twilio_verify_user__captcha').hide();
$('#twilio_verify_user__captcha').val('');
$('#twilio_code_submit').hide();
},
refresh_captcha: function() {
var _this=this;
_this.add_modal_plug();
this.widget.node_request(this.widget.config.use_fake?'fake_new_captcha':'new_captcha', function (response, error) {
if(_this.widget.config.debug)console.log(response);
if(_this.widget.config.debug)console.log(error);
if(error) {
_this.remove_modal_plug();
}else {
_this.remove_modal_plug();
$('.twilio_verify_user__captcha__img').html('<img src="'+ response.url +'">');
}
});
},
already_setup: function(){
console.log("Hello!!");
var _this = this;
_this.render_tpl({
tpl:'already',
place:'.twilio__content'
});
},
trial_stop: function(e) {
var _this = this,
spinner = '<div class="twilio_btn_spinner twilio_btn_spinner__stop-trial"><span class="button-input__spinner__icon spinner-icon"></span></div>',
$billing_plug = $('.twilio__billing_trial_plug'),
$balance_plug = $('.twilio__setup__y__balance__trial');
$('.twilio__credits').empty();
$billing_plug.addClass('disabled');
$balance_plug.addClass('disabled');
$('.twilio__verify__error').remove();
$billing_plug.append(spinner);
$balance_plug.append(spinner);
_this.add_modal_plug();
this.widget.node_request(_this.widget.config.use_fake?'fake_stop_trial':'stop_trial', function (response, error) {
if(error){
_this.remove_modal_plug();
if(_this.widget.config.debug)console.error(error);
$('.twilio_btn_spinner').remove();
//$('<div class="twilio__verify__error">'+error.text+'</div>').insertAfter(e.target);
$('.twilio__billing_trial_plug').removeClass('disabled');
$balance_plug.removeClass('disabled');
_this.showTwilioCredits('upgrade');
}else {
//_this.widget.params.status = 'active';
if(_this.widget.config.debug)console.log(response);
_this.widget.params.trial = false;
_this.render_tpl({
tpl:'modal'
}, function() {
_this.render_tpl({
tpl:'settings',
place:'.twilio__content'
}, function() {
_this.remove_modal_plug();
//$(".twilio_verify_user__send-sms__input__countries").intlTelInput();
$('.twilio__setup__y__your_number').intlTelInput();
});
$('#twilio__nav__current').addClass('second');
});
}
});
},
save_exists_master:function(e){
var _this=this;
var butt=$(e.target);
butt.addClass('disabled');
$('.twilio__verify__error').remove();
var sid=$('.twilio_already_user__sid__input').val();
var token=$('.twilio_already_user__token__input').val();
if(!sid || !/AC[a-z0-9]{32}/i.test(sid)){
var err=true;
$('.twilio_already_user__sid__input').addClass("input_error");
setTimeout(function(){$('.twilio_already_user__sid__input').removeClass("input_error");},1500);
}
if(!token || !/[a-z0-9]{32}/i.test(token)){
var err=true;
$('.twilio_already_user__token__input').addClass("input_error");
setTimeout(function(){$('.twilio_already_user__token__input').removeClass("input_error");},1500);
}
if(err){
$('<div class="twilio__verify__error">Invalid data indicated</div>').insertAfter( '.twilio_already_user__token__input' );
return;
}
var spinner = '<div class="twilio_btn_spinner button-input__spinner"><span class="button-input__spinner__icon spinner-icon"></span></div>';
var save_butt=butt.html();
butt.html(spinner);
_this.add_modal_plug();
_this.widget.node_request(this.widget.config.use_fake?'fake_reg_twilio_account':'reg_twilio_account',function(res,err){
if(res && res.sid && res.token){
AMOCRM.widgets.clear_cache();
_this.active_toggler("Y");
_this.widget.get_token(function(){
_this.render({});
_this.widget.get_token();
});
_this.remove_modal_plug();
}else{
_this.remove_modal_plug();
butt.html(save_butt);
console.log(err,res);
var error=JSON.stringify(err);
if(res){
if((res.status==404 && res.code == 20404) || res.status=="ENOTFOUND")error='Invalid data indicated';
if(res.status==401)error='Invalid data indicated';
}else if(err){
if(err.text){
error=err.text;
}
}
// $('.twilio_already_user__sid__input, .twilio_already_user__token__input').addClass("input_error");
// setTimeout(function(){$('.twilio_already_user__sid__input, .twilio_already_user__token__input').removeClass("input_error");},1500);
$('<div class="twilio__verify__error">'+error+'</div>').insertAfter( '.twilio_already_user__token__input' );
}
},{
sid:sid,
token:token,
login:_this.widget.system().amouser,
api_key:_this.widget.system().amohash
});
},
billing_period : function(e) {
var period = e.target.defaultValue,
now = new Date(),
start_date;
var date = new Date();
var end_date=[
now.getFullYear(),
(now.getMonth()+1<10)?'0'+(now.getMonth()+1):now.getMonth()+1,
now.getDate()
].join('-');
if (period == 'all_history') {
this.get_billing();
}else if (period == '3months'){
date.setMonth(date.getMonth()-3);
start_date = [
date.getFullYear(),
(date.getMonth()+1<10)?'0'+(date.getMonth()+1):date.getMonth()+1,
date.getDate()
].join('-');
this.get_billing(start_date, end_date);
}else if (period == 'current_month'){
date.setMonth(date.getMonth()-1);
start_date = [
date.getFullYear(),
(date.getMonth()<10)?'0'+(date.getMonth()+1):date.getMonth()+1,
date.getDate()
].join('-');
this.get_billing(start_date, end_date);
}else {
console.log('Ошибка')
}
},
//showLink: function (e) {
// $(e.target).hide();
// $('.twilio_allready_link').show();
//},
refreshBalance: function(e) {
$(e.target).addClass('rotating');
var _this = this;
_this.widget.node_request(_this.widget.config.use_fake?'fake_balance':'balance',function(response,error){
$('.twilio__setup__y').find('.twilio__error__balance').remove();
if (error) {
$(e.target).removeClass('rotating');
console.log(error);
var error = "<div class=\"twilio__error__balance\">Unable to get the balance.</div>";
$('.twilio__setup__y').append(error);
setTimeout(function(){
$('.twilio__setup__y').find('.twilio__error__balance').remove();
}, 5000);
}else {
$(e.target).removeClass('rotating');
console.log(response);
$('.twilio__setup__y__balance span').html('$'+response);
}
});
},
showTwilioCredits:function(type) {
var login = this.widget.params.twilio_mail,
password = this.widget.params.twilio_pass,
_this = this;
_this.render_tpl({
tpl:'credits',
place:'.twilio__credits',
data:{
type: type,
login: login,
password: password
}
});
},
showTwilioPass: function(e) {
var $password = $('#twilio__credits__password');
if ($password.hasClass('pass')){
$password.attr({
type: 'text'
}).removeClass('pass');
$(e.target).html('Hide');
}else{
$password.attr({
type: 'password'
}).addClass('pass');
$(e.target).html('Show');
}
},
addCredits: function(e) {
this.showTwilioCredits();
}
})
};
return Settings;
});