'use strict';
function HandlerAcquistoController($scope, Data, $window, $http, toaster, focus, $timeout) {
$scope.item = {};
$scope.articoloBase = {};
$scope.Codice = {};
$scope.disabledCodice = false;
$scope.codiceOK = false;
$scope.errore_sconto = false;
$scope.ricalcolo_assistenza = false;
$scope.ricalcolo_prezzo = false;
//$scope.show_compilazione_automatica = true;
$scope.p_iva_autocompilante = null;
var countInserimenti = 0;
var in_test = angular.element('input#test_stripe_abilitato').val();
if (in_test) {
var stripe = Stripe('pk_test_7ZGqZj5aG6ZwqC1I3SK2LVYE');
var stripeExecutionPaymentUrl = 'acquisto/executestripepay';
} else {
var stripe = Stripe('pk_live_xMXmd4RQaKveDyXiFg9NONi7');
var stripeExecutionPaymentUrl = 'acquisto/executestripepay';
}
// Gestione del pagamento tramite bonifico
const bonifico_abilitato = angular.element('input#bonifico_abilitato').val();
$scope.abilitaBonifico = !!bonifico_abilitato;
$scope.bonificoStep = 1;
$scope.step = 1;
$scope.inviato = false;
$scope.loading = false;
$scope.loading_rivenditore = false;
$scope.loading_quantita = false;
$scope.errorMessage = "";
$scope.checkboxesError = false;
$scope.erroreBloccante = false;
$scope.linkAcquisto = "";
$scope.CreditCard = {};
$scope.loadingPayPalButton = false;
$scope.loadingStripeButton = false;
$scope.loadingBonificoButton = false;
var campiForm = [
'rag_soc',
'indirizzo',
'cap',
'comune',
'provincia',
'p_iva',
'cod_fisc',
'email',
'email2',
'pec',
'CodiceDestinatario',
'telefono',
'note'
];
/***** CLICK SUI HEADING PANNELLI *****/
$scope.headingOneClick = function () {
$('#collapseOne').collapse('show');
$('#collapseTwo').collapse('hide');
$('#collapseThree').collapse('hide');
};
$scope.headingTwoClick = function () {
//if($scope.step < 2) return;
$('#collapseOne').collapse('hide');
$('#collapseTwo').collapse('show');
$('#collapseThree').collapse('hide');
};
$scope.headingThreeClick = function () {
if ($scope.step < 3) return;
$('#collapseOne').collapse('hide');
$('#collapseTwo').collapse('hide');
$('#collapseThree').collapse('show');
};
/***** PANNELLO CARRELLO *****/
$scope.articoloClick = function () {
var nextArticolo = function () {
$('#collapseOne').collapse('hide');
$('#collapseTwo').collapse('show');
$('#collapseThree').collapse('hide');
if (!$scope.inviato)
$scope.step = 2;
};
//Disattivato da riattivare nel caso si voglia gestire un articolo agginutivo nel carrello
/*if ($scope.item.cod_articolo === 'Winfatt') {
SweetAlert.swal({
title: "",
text: "Sei sicuro di voler procedere senza aggiungere il pacchetto di assistenza?",
type: "info",
animation: false,
showCancelButton: true,
confirmButtonColor: "#31708f",
confirmButtonText: "Aggiungi Assistenza!",
cancelButtonText: "Si, Procedi.",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
$window.location.href = "https://www.winfatt.com" + $('#url_winfatt_as').attr('href');
} else {
nextArticolo();
}
});
} else {
nextArticolo();
}*/
nextArticolo();
};
$scope.annulla = function (link) {
if (confirm("Sei sicuro di voler annullare l'ordine")) {
$window.location.href = 'https://www.winfatt.com';
}
};
/***** PANNELLO DATI INTESTAZIONE *****/
function validaForm() {
if ($scope.acquistoForm.$invalid || (!$scope.item.checkbox1 || !$scope.item.checkbox2 || !$scope.item.checkbox3)) {
var campoFocus = false;
angular.forEach(campiForm, function (campo) {
if (angular.isDefined($scope.acquistoForm[campo])) {
$scope.acquistoForm[campo].$setTouched();
if (!campoFocus) {
if ($scope.acquistoForm[campo].$invalid) {
campoFocus = campo;
}
}
}
});
$scope.checkboxesError = !!(!$scope.item.checkbox1 || !$scope.item.checkbox2 || !$scope.item.checkbox3);
$scope.errorMessage = "I dati inseriti sono errati controllare tutti i campi.";
if (campoFocus) {
focus(campoFocus);
}
return false;
}
$scope.checkboxesError = false;
$scope.errorMessage = "";
return true;
}
$scope.creaNuovoOrdine = function () {
//Se già c'è una chiamata in corso impedisco l'avvio di una nuova
if ($scope.loading) return;
//Validazione del form
if (!validaForm()) return;
//Se l'ordine è gia stato inviato vado solo a visualizzare lo step 3
if ($scope.inviato) {
$('#collapseOne').collapse('hide');
$('#collapseTwo').collapse('hide');
$('#collapseThree').collapse('show');
$scope.step = 3;
$scope.inviato = true;
return;
}
//Eseguo la chimata per il nuovo ordine
$scope.submitorder();
};
$scope.submitorder = function () {
//Blocco la chiamata nel caso gia mi trovo allo step 3 (Pagamento)
if ($scope.inviato) {
$scope.step = 3;
return;
}
$scope.loading = true;
$('.manual-error').remove();
Data.post('acquisto/nuovoordine', $scope.item).then(function (data) {
if (data.success) {
$('#collapseOne').collapse('hide');
$('#collapseTwo').collapse('hide');
$('#collapseThree').collapse('show');
$scope.step = 3;
$scope.inviato = true;
$scope.abilitaBonifico = !!parseInt(data.data.pagamento_bonifico);
if ($scope.abilitaBonifico) {
$scope.setBonificoPaymentMethod();
} else {
$scope.setStripePaymentMethod();
}
$scope.errorMessage = "";
$scope.item.id = data.data.id;
$scope.item.cod_fisc = data.data.cod_fisc;
$scope.item.split_payment = data.data.split_payment;
if (data.errore_sconto) {
$scope.codiceOK = false;
$scope.item.Codice = {};
$scope.item.imponibile = data.data.imponibile;
$scope.item.imposta = data.imposta;
$scope.item.totale = data.data.totale;
delete $scope.item.imponibile_scontato;
delete $scope.item.codice_rivenditore;
$scope.errore_sconto = true;
}
if (data.ricalcolo_assistenza) {
$scope.item.imponibile = data.data.imponibile;
$scope.item.imposta = data.imposta;
$scope.item.totale = data.data.totale;
delete $scope.item.imponibile_scontato;
delete $scope.item.codice_rivenditore;
$scope.ricalcolo_assistenza = true;
}
if (data.ricalcolo_prezzo) {
$scope.item.imponibile = data.data.imponibile;
$scope.item.imposta = data.imposta;
$scope.item.totale = data.data.totale;
delete $scope.item.imponibile_scontato;
delete $scope.item.codice_rivenditore;
$scope.ricalcolo_prezzo = true;
}
if (data.scadenza_al) {
$scope.item.DescrizioneAggiuntiva = `Validità servizio fino al ${data.scadenza_al}`;
}
} else {
$scope.errorMessage = data.errorMessage;
var campoFocus = false;
angular.forEach(data.errors, function (val, campo) {
if (angular.isDefined($scope.acquistoForm[campo])) {
var errorBlock = $('#' + campo + '-ErrorBlock');
if (errorBlock)
angular.forEach(val, function (errMex) {
var html = "
" + errMex + "
";
errorBlock.append(html);
});
$scope.acquistoForm[campo].$setTouched();
$scope.acquistoForm[campo].$valid = false;
$scope.acquistoForm[campo].$invalid = true;
if (!campoFocus) {
campoFocus = campo;
focus(campoFocus);
}
}
});
if (data.erroreBloccante === true) {
$scope.erroreBloccante = true;
}
if (angular.isDefined(data.linkAcquisto)) {
$scope.linkAcquisto = data.linkAcquisto;
}
}
$scope.loading = false;
});
};
/**
* Funzione per applicare il codice rivenditore
*/
$scope.submitCodiceRivenditore = function () {
if (!$scope.item.codice_rivenditore) {
toaster.warning("Errore", "Inserire un codice sconto");
focus("codice_rivenditore");
$scope.loading_rivenditore = false;
return;
}
if (countInserimenti > 5) {
toaster.warning("Attenzione", "Hai effettuato troppi tentativi errati riprova piu tardi");
$scope.disabledCodice = true;
$scope.item.codice_rivenditore = "";
$scope.loading_rivenditore = false;
return;
}
if (angular.equals({}, $scope.articoloBase))
angular.copy($scope.item, $scope.articoloBase);
$scope.loading_rivenditore = true;
$scope.disabledCodice = true;
Data.post('acquisto/applicacodicerivenditore', $scope.item).then(function (data) {
if (data.success) {
$scope.item.imponibile_scontato = data.articolo.ImportoScontato;
$scope.item.valore_iva = data.articolo.Iva;
$scope.item.sconto = data.articolo.Sconto;
$scope.item.scontoDaVisualizzare = data.articolo.ScontoDaVisualizzare;
$scope.item.imposta = data.articolo.Imposta;
$scope.item.totale = data.articolo.Totale;
$scope.item.codice_rivenditore = data.Codice.Codice;
$scope.Codice = data.Codice;
$scope.disabledCodice = true;
$scope.codiceOK = true;
$scope.loading_rivenditore = false;
countInserimenti = 0;
toaster.success("Codice sconto applicato!");
} else {
$timeout(function () {
$scope.loading_rivenditore = false;
$scope.disabledCodice = false;
$scope.item.codice_rivenditore = "";
toaster.error("Errore", data.message);
focus("codice_rivenditore");
countInserimenti++;
}, 7000);
}
});
};
/***** PANNELLO PAGAMENTO *****/
$scope.setStripePaymentMethod = function (event) {
if ($scope.loadingPayPalButton) {
event.preventDefault();
event.stopPropagation();
return;
}
$scope.item.tipo_pagamento = 'credit_card';
$scope.showCollapseStripe();
};
$scope.setPayPalPaymentMethod = function (event) {
if ($scope.loadingStripeButton) {
event.preventDefault();
event.stopPropagation();
return;
}
$scope.item.tipo_pagamento = 'paypal';
$scope.showCollapsePaypal();
};
$scope.setBonificoPaymentMethod = (event, showBlock = true) => {
if ($scope.loadingBonificoButton) {
event.preventDefault();
event.stopPropagation();
return;
}
$scope.item.tipo_pagamento = 'bonifico';
if (showBlock) {
$scope.showCollapseBonifico();
}
};
$scope.showCollapsePaypal = function () {
$('#collapseStripe').collapse('hide');
$('#collapseBonifico').collapse('hide');
$('#collapsePayPal').collapse('show');
};
$scope.showCollapseStripe = function () {
$('#collapsePayPal').collapse('hide');
$('#collapseBonifico').collapse('hide');
$('#collapseStripe').collapse('show');
};
$scope.showCollapseBonifico = function () {
$('#collapsePayPal').collapse('hide');
$('#collapseStripe').collapse('hide');
$('#collapseBonifico').collapse('show');
};
$scope.submitPaypal = function () {
$scope.item.tipo_pagamento = 'paypal';
if ($scope.loadingPayPalButton) return;
$scope.loadingPayPalButton = true;
Data.post('acquisto/createnewpayment', $scope.item).then(function (data) {
if (data.success) {
$window.open(data.data.approvaUrl, '_self');
} else {
toaster.error("Errore", data.message, "error");
}
}).catch(function (err) {
toaster.error("Errore", err.message, "error");
$scope.loadingPayPalButton = false;
});
};
$scope.submitStripe = function () {
$scope.CreditCard.tipo_pagamento = 'credit_card';
if ($scope.loadingStripeButton) return;
$scope.showError = false;
$scope.errorMessage = "";
$scope.loadingStripeButton = true;
$scope.CreditCard.orderId = $scope.item.id;
Data.post(stripeExecutionPaymentUrl, $scope.CreditCard).then(function (response) {
handleStripeServerResponse(response);
}).catch(function (err) {
$scope.showError = true;
$scope.errorMessage = err.message;
$scope.loadingStripeButton = false;
});
// è commentato perchè sblocco il loader solo in caso di errore altrimenti rimane attivo fino al reindirizzamento di avvenuto pagamento
/*.finally(function () {
$scope.loadingStripeButton = false;
});*/
};
// metodo di pagamento tramite bonifico
$scope.submitBonifico = () => {
$scope.item.tipo_pagamento = 'bonifico';
if ($scope.loadingBonificoButton) return;
$scope.loadingBonificoButton = true;
const param = {id: $scope.item.id};
Data.post('acquisto/bonificopay', param).then((data) => {
if (data.success) {
// Mostra il blocco di fine acquisto bonifico
$scope.bonificoStep = 2;
} else {
toaster.error("Errore", data.message, "error");
}
}).catch(function (err) {
toaster.error("Errore", err.message, "error");
}).finally(() => {
$scope.loadingBonificoButton = false;
});
}
//Il response deve essere la result del paymentIntent effettuato su stripe
function handleAction(response) {
stripe.handleCardAction(
response.payment_intent_client_secret
).then(function (result) {
if (result.error) {
$timeout(function () {
$scope.loadingStripeButton = false;
$scope.errorMessage = result.error.message;
$scope.showError = true;
});
} else {
// Per sicurezza reimposto il loader a true
$scope.loadingStripeButton = true;
Data.post('acquisto/confirmintent', {
payment_intent_id: result.paymentIntent.id
}).then(function (data) {
handleStripeServerResponse(data);
});
}
});
}
function handleStripeServerResponse(response) {
if (!response.success) {
$timeout(function () {
$scope.errorMessage = response.message;
$scope.showError = true;
$scope.loadingStripeButton = false;
});
} else if (response.paymentIntent.requires_action) { // Gestione del caso di autenticazione
handleAction(response.paymentIntent);
} else {
// Pagamento avvenuto con successo
$scope.showError = false;
$scope.errorMessage = "";
$window.open("https://www.winfatt.com/fineacquisto/" + $scope.item.cod_articolo + "/ok/printcode/" + response.order.printcode, '_self');
}
}
/***** GESTIONE ACQUISTO MULTIPLO *****/
$scope.onChangeQuantita = function (quantita) {
if (!quantita < 0) {
toaster.warning("Errore", "Quantità errata, non può essere minore di zero");
$scope.loading_quantita = false;
return;
}
var data = {quantita: quantita, cod: $scope.item.cod_articolo};
if ($scope.codiceOK) {
data.sconto = $scope.Codice.Codice;
}
$scope.loading_quantita = true;
Data.post('acquisto/ricalcolaimporto', data).then(function (data) {
if (data.success) {
$scope.item.valore_iva = data.articolo.Iva;
$scope.item.imposta = data.articolo.Imposta;
$scope.item.prezzo_articolo = data.articolo.Prezzo;
$scope.item.imponibile = data.articolo.Importo;
$scope.item.totale = data.articolo.Totale;
if ($scope.codiceOK) {
$scope.item.imponibile_scontato = data.articolo.ImportoScontato;
$scope.item.sconto = data.articolo.Sconto;
$scope.item.scontoDaVisualizzare = data.articolo.ScontoDaVisualizzare;
$scope.Codice.Sconto = data.articolo.Sconto;
}
$timeout(function () {
$scope.loading_quantita = false
}, 25);
} else {
$scope.loading_quantita = false;
toaster.error("Errore", data.message);
}
});
};
/**
* Compilazione automatica tramite partita iva
*/
$scope.compilazioneAutomatica = function () {
$scope.loading_autocompilazione = true;
if (!$scope.p_iva_autocompilante || !PIVA_REGEXP.test($scope.p_iva_autocompilante)) {
toaster.warning("Errore", "Inserire una partita iva valida");
$scope.loading_autocompilazione = false;
return;
}
$http({
method: 'GET',
url: "https://data.fatturab2b.it/v1/search/" + $scope.p_iva_autocompilante,
headers: {
'Content-Type': 'application/json',
'Authorization': '01999590688#DDF3E440D12A11A6EEA31C2FAF82763E'
}
}).then((res) => {
if (angular.isDefined(res.data.PartitaIva) && res.data.PartitaIva === $scope.p_iva_autocompilante && res.data.StatoAttivita.toLowerCase() !== 'nonactive') {
$scope.item.rag_soc = res.data.RagioneSociale;
$scope.item.indirizzo = res.data.Indirizzo;
$scope.item.comune = res.data.Comune;
$scope.item.provincia = res.data.Provincia;
$scope.item.cap = res.data.Cap;
$scope.item.p_iva = res.data.PartitaIva;
$scope.item.cod_fisc = res.data.CodiceFiscale;
$scope.show_compilazione_automatica = false;
} else {
toaster.warning("Errore", "Nessun dato trovato per questa partita iva, inserire i dati manualmente");
$scope.show_compilazione_automatica = false;
}
}).catch((err) => {
toaster.warning("Errore", "Si è verificato un errore durante la chiamata compilare i dati manualmente.");
$scope.show_compilazione_automatica = false;
}).finally(() => {
$scope.loading_autocompilazione = false;
});
};
}
app.controller('HandlerAcquistoController', HandlerAcquistoController);