$( document ).ready(function() {
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": true,
"positionClass": "toast-bottom-center",
"preventDuplicates": false,
"onclick": null,
"showDuration": "600",
"hideDuration": "1000",
"timeOut": "7000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
//initGeolocationGeral();
});
function sendingForm(formId, on) {
var $form = $('#' + formId);
if (on) {
$form.find('input, select, textarea').attr('readonly', true);
$form.find('button').attr('disabled', true);
$form.find('[type="submit"]').addClass('btn-loading');
} else {
$form.find('input, select, textarea').attr('readonly', false);
$form.find('button').attr('disabled', false);
$form.find('[type="submit"]').removeClass('btn-loading');
}
}
const utf8ToBase64 = (str) => {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => {
return String.fromCharCode("0x" + p1);
}));
}
const base64ToUtf8 = (str) => {
return decodeURIComponent(atob(str).split('').map((c) => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
};
function validateMaxValue(input) {
if (parseInt(input.value) > parseInt(input.max)) {
input.value = input.max;
}
}
function inputApenasDecimal(el,event) {
el.value = el.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
var sanitizedValue = el.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
el.value = sanitizedValue;
if (event.key && !/[0-9.]/.test(event.key)) {
event.preventDefault();
}
}
function base64_encode(str) {
var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var out = "", i = 0;
var char1, char2, char3, enc1, enc2, enc3, enc4;
str = utf8_encode(str);
while (i < str.length) {
char1 = str.charCodeAt(i++);
char2 = str.charCodeAt(i++);
char3 = str.charCodeAt(i++);
enc1 = char1 >> 2;
enc2 = ((char1 & 3) << 4) | (char2 >> 4);
enc3 = ((char2 & 15) << 2) | (char3 >> 6);
enc4 = char3 & 63;
if (isNaN(char2)) {
enc3 = enc4 = 64;
} else if (isNaN(char3)) {
enc4 = 64;
}
out = out +
base64EncodeChars.charAt(enc1) +
base64EncodeChars.charAt(enc2) +
base64EncodeChars.charAt(enc3) +
base64EncodeChars.charAt(enc4);
}
return out;
}
function utf8_encode(string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
$('input').keypress(function (e) {
var key = e.which;
if(key == 13){ $(this).blur(); }
});
$(function(){
if ($('#stickytypeheader').length) {
var stickyHeaderTop = $('#stickytypeheader').offset().top;
$(window).scroll(function(){
if ($(window).width() > 768) {
if( $(window).scrollTop() > stickyHeaderTop-75 ) {
$('#stickytypeheader').css({position: 'sticky', top: '75px'});
} else {
$('#stickytypeheader').css({position: 'static', top: '0px'});
}
}
});
}
});
function delay(callback, ms) {
var timer = 0;
return function() {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
callback.apply(context, args);
}, ms || 0);
};
}
var latitudeGeral = '';
var longitudeGeral = '';
function initGeolocationGeral() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
latitudeGeral = position.coords.latitude;
longitudeGeral = position.coords.longitude;
},
(error) => { toastr.error('Não foi possível obter a sua geolocalização'); },
{ enableHighAccuracy: false, timeout: 10000},
);
}
else { toastr.error('Este browser não suporta serviços de geolocalização'); }
}
(function() {
'use strict';
$('.select2').select2({
minimumResultsForSearch: Infinity
});
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('login-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
event.preventDefault();
form.classList.add('was-validated');
if (form.checkValidity() === false) {
event.stopPropagation();
} else {
var $this = $(this);
$("#dologin input").attr("readonly", true); $("#dologin button").attr("readonly", true);
//if (latitudeGeral && longitudeGeral) {
$.ajax({
type: 'POST',
url: '/paginas/acesso/check_login.php',
data: $this.serialize(),
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&type=login&latitude='+latitudeGeral+'&longitude='+longitudeGeral;
},
success:function(data){
if(data>0){
toastr.success("Autenticado com sucesso");
setTimeout(function(){
window.location.reload();
}, 500);
}else if(data=="-1"){
toastr.warning("Login incorrecto. Tente de novo");$("#dologin input").attr("readonly", false); $("#dologin button").attr("readonly", false);
}else if(data=="-98"){
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");$("#dologin input").attr("readonly", false); $("#dologin button").attr("readonly", false);
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");$("#dologin input").attr("readonly", false); $("#dologin button").attr("readonly", false);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");$("#dologin input").attr("readonly", false); $("#dologin button").attr("readonly", false);
}
});
/*} else {
toastr.error('Para continuar é necessário autorizar a sua geolocalização');
}*/
}
}, false);
});
}, false);
})();
async function load_counters(){
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://comercial-laltrait.aplataforma.com/paginas/refresh/get-counters.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
$("#footerstuff").html(xhr.responseText);
countersLoaded = true;
} else if (xhr.readyState === 4) {
console.error('Error loading counters:', xhr.statusText);
}
};
xhr.send("page=1");
};
var countersLoaded = false;
$(document).ready(function() {
});
function loadToolTips() {
setTimeout(function(){
document.querySelectorAll('.tooltip').forEach(function(t){ t.remove(); });
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
tooltipTriggerList.forEach(function (tooltipTriggerEl) {
var existing = bootstrap.Tooltip.getInstance(tooltipTriggerEl);
if (existing) { existing.dispose(); }
new bootstrap.Tooltip(tooltipTriggerEl);
});
}, 200);
}
// Permitir tooltips em botões/links disabled (Bootstrap aplica pointer-events:none por defeito).
// Injecta CSS uma vez e regista um listener em capture phase para bloquear cliques.
(function(){
if (window.__disabledTooltipsInit) return;
window.__disabledTooltipsInit = true;
var addStyle = function(){
if (document.getElementById('disabledTooltipsStyle')) return;
var s = document.createElement('style');
s.id = 'disabledTooltipsStyle';
s.textContent = '.btn.disabled[data-bs-toggle="tooltip"], a.disabled[data-bs-toggle="tooltip"], .btn:disabled[data-bs-toggle="tooltip"] { pointer-events: auto !important; cursor: not-allowed !important; }';
document.head.appendChild(s);
};
if (document.head) { addStyle(); } else { document.addEventListener('DOMContentLoaded', addStyle); }
document.addEventListener('click', function(e){
var el = e.target.closest && e.target.closest('.btn.disabled, a.disabled, .btn:disabled');
if (el) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); return false; }
}, true);
})();
function load_contents_load(pagina,resultados,view){
var track_page = 1;
$("#"+resultados).fadeOut('fast');
setTimeout(function(){
$("#"+resultados).html("");
$('.camposLoadProdutos').attr("disabled", true);
load_contents(track_page,pagina,resultados,view);
}, 100);
};
function load_contents(track_page,pagina,resultados,view){
var load_url = $("input#"+pagina).val();
$.post(load_url, {'page': track_page}, function(data){
$("#"+resultados).html(data);
$(".produtos_loader"+view).hide();
$("#"+resultados).fadeIn();
loadToolTips();
$('.camposLoadProdutos').attr("disabled", false);
if (!countersLoaded) { load_counters(); }
});
};
function setCookie(key, value, minutes = 30) {
var expires = new Date();
expires.setTime(expires.getTime() + (minutes * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString() + ";domain=comercial-laltrait.aplataforma.com;path=/";
}
function unsetCookie(key) {
document.cookie = key + '=; Max-Age=0'
document.cookie = key + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; domain=comercial-laltrait.aplataforma.com; path=/;";
}
$('#sideBtn').click(function () {
var viewSel = ($('body').hasClass('sidenav-toggled')) ? 'open' : 'closed';
setCookie('sidebar_state',viewSel);
});
function remove_accents(strAccents) {
var strAccents = strAccents.split('');
var strAccentsOut = new Array();
var strAccentsLen = strAccents.length;
var accents = "ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëÇçðÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž";
var accentsOut = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeCcdDIIIIiiiiUUUUuuuuNnSsYyyZz";
for (var y = 0; y < strAccentsLen; y++) {
if (accents.indexOf(strAccents[y]) != -1) {
strAccentsOut[y] = accentsOut.substr(accents.indexOf(strAccents[y]), 1);
} else
strAccentsOut[y] = strAccents[y];
}
strAccentsOut = strAccentsOut.join('');
return strAccentsOut.toLowerCase();;
}
$(".pesquisa").submit(function(event) {
event.preventDefault();
var $this = $(this);
window.location.href = "https://comercial-laltrait.aplataforma.com/pt//?"+$this.serialize();
});
function gerarDocumentoFaturas() {
var documentos = '';
$('input.checkref:checkbox:checked').each(function(i, obj) {
var tmdId = $(this).attr('data-id');
if (documentos != '') { documentos += '|'; }
documentos += tmdId;
});
if (documentos != '') {
documentos = btoa(documentos);
window.open("https://comercial-laltrait.aplataforma.com/pdfDocumentos.php?documentos="+documentos, "_blank");
}
}
var modalGerarReferencia;
function gerarReferenciaMB() {
$('#modalRefContentMail, #modalRefContentSendMail').hide();
$('#modalRefLoading').show();
$('#modalRefContent').html('');
modalGerarReferencia = new bootstrap.Modal(document.getElementById('modalReferencia'), { backdrop: 'static', keyboard: false });
modalGerarReferencia.show();
var documentos = $('#idsRefs').val();
var cliente = $('#clienteRefs').val();
$.ajax({
type: 'POST',
url: '/paginas/refresh/gerar-referencia.php',
data: '&docs='+documentos+'&cliente='+cliente,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#modalRefLoading').hide();
$('#modalRefContent').html(data);
$('#modalRefContentMail, #modalRefContentSendMail').show();
$(".checkref").prop("checked", false);
$('#idsRefs').val('');
$('#btnGerarRef').html(' PAGAMENTO');
$("#btnGerarRef").addClass("disabled");
handleRefs();
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
$("#enviarRefMultibanco").submit(function(event) {
event.preventDefault();
var $this = $(this);
var serialize = $this.serialize();
var content = encodeURIComponent($('#modalRefContent').html());
content = btoa(content);
sendingForm('enviarRefMultibanco', true);
$.ajax({
type: 'POST',
url: '/paginas/mail/mail-referencia-mb.php',
data: serialize+'&content='+content,
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.href = "https://comercial-laltrait.aplataforma.com/pt/"; }, 500);
} else if(data==1){
toastr.success("E-mail enviado com sucesso");
modalGerarReferencia.hide();
$("#enviarRefMultibanco")[0].reset();
}else if(data=="-98"){
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else{
toastr.error("Não foi possivel concluir o seu pedido.");
}
sendingForm('enviarRefMultibanco', false);
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
sendingForm('enviarRefMultibanco', false);
}
});
return false;
});
function mostraMoeda(valor,simbolo=' €',decimais=2) {
valor = valor.toString();
if (typeof valor !== typeof undefined) valor = valor.replace(',','.');
if (!$.isNumeric(valor)) return valor;
var novoValor = parseFloat(valor);
var precoFinal = numberWithSpaces(novoValor.toFixed(decimais));
var finalStr = precoFinal.replace('.',',')+simbolo;
return finalStr;
}
function numberWithSpaces(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
return parts.join(".");
}
function carregarInfoValidacao(tmpid, idArtigo, novoNet, isTemplate) {
var $linha = $('.linhaArtigo' + tmpid).first();
var precoTt = parseFloat($linha.attr('data-preco-tt')) || 0;
var precoTr = parseFloat($linha.attr('data-preco-tr')) || 0;
novoNet = parseFloat(novoNet) || 0;
$.ajax({
type: 'POST',
url: '/paginas/refresh/get-info-validacao-preco.php',
data: 'idArtigo=' + encodeURIComponent(idArtigo) + '&novoNet=' + novoNet,
dataType: 'json',
beforeSend: function(xhr, settings) {
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success: function(data) {
if (!data || typeof data !== 'object') return;
var custoManual = parseFloat(data.custo_manual) || 0;
var custoPonderado = parseFloat(data.custo_ponderado) || 0;
var valorMinimo = data.valor_minimo || '0.000';
var valorMaximo = (precoTr * 2).toFixed(3);
var precoNetTmp = (novoNet > 0) ? novoNet : precoTt;
var mpvcm = precoNetTmp > 0 ? ((precoNetTmp - custoManual) / precoNetTmp * 100) : 0;
var mpvcp = precoNetTmp > 0 ? ((precoNetTmp - custoPonderado) / precoNetTmp * 100) : 0;
var ponderadoB64 = btoa(custoPonderado.toFixed(3));
$('#cm_' + tmpid).html(mostraMoeda(custoManual, '€', 3));
$('#mpvcm_' + tmpid).html(mostraMoeda(mpvcm, '%', 2));
$('#cp_' + tmpid).html(mostraMoeda(custoPonderado, '€', 3));
$('#mpvcp_' + tmpid).html(mostraMoeda(mpvcp, '%', 2));
if (data.motivo_aprovacao && novoNet > 0) {
$('#campoMotivo' + tmpid).html('
' + data.motivo_aprovacao + ' ');
} else {
$('#campoMotivo' + tmpid).html('');
}
var sufix = isTemplate ? 'Template' : 'Proposta';
$('#valorNovo_' + tmpid).attr('onchange', "calculaPerc('" + tmpid + "','" + precoTt + "','" + valorMinimo + "','" + valorMaximo + "','" + ponderadoB64 + "',false,0); changePreco" + sufix + "('" + idArtigo + "','" + tmpid + "')");
$('#varNet_' + tmpid).attr('onchange', "calculaPreco('" + tmpid + "','" + precoTt + "','" + valorMinimo + "','" + valorMaximo + "','" + ponderadoB64 + "',false,0,'',false); changePreco" + sufix + "('" + idArtigo + "','" + tmpid + "');");
$('#input_mpvcm_' + tmpid).attr('onchange', "manipulaMargem('input_mpvcm','" + tmpid + "','" + precoTt + "','" + valorMinimo + "','" + valorMaximo + "','" + ponderadoB64 + "');");
$('#input_mpvcp_' + tmpid).attr('onchange', "manipulaMargem('input_mpvcp','" + tmpid + "','" + precoTt + "','" + valorMinimo + "','" + valorMaximo + "','" + ponderadoB64 + "');");
$('#input_mpvcm_' + tmpid).val(mpvcm.toFixed(2));
$('#input_mpvcp_' + tmpid).val(mpvcp.toFixed(2));
}
});
}
function limparInfoValidacao(tmpid) {
$('#cm_' + tmpid).html('—');
$('#mpvcm_' + tmpid).html('—');
$('#cp_' + tmpid).html('—');
$('#mpvcp_' + tmpid).html('—');
$('#campoMotivo' + tmpid).html('');
$('#valorNovo_' + tmpid).removeAttr('onchange');
$('#varNet_' + tmpid).removeAttr('onchange');
$('#input_mpvcm_' + tmpid).removeAttr('onchange').val('');
$('#input_mpvcp_' + tmpid).removeAttr('onchange').val('');
}
function handleRefs() {
var total=0, ct=0, ctComprovativos=0, totalRecibo = 0;
var ids='';
var nomes = '';
var datas = '';
var idsAT = '';
var numAnexos = '';
$('input.checkref:checkbox').not(':checked').each(function(i, obj) {
var tmdId = $(this).attr('data-id');
$('#valorLiquidar_'+tmdId).val('');
$('#valorLiquidar_'+tmdId).attr("disabled", true);
});
$('input.checkref:checkbox:checked').each(function(i, obj) {
if (ct>0) {
ids += ',';
nomes += ',';
datas += ',';
idsAT += ',';
numAnexos += ',';
}
ids += $(this).val();
var tmdId = $(this).attr('data-id');
var nomeDoc = $(this).attr('data-nome');
nomes += nomeDoc;
var valor = $(this).attr('data-valor');
if (valor != 0) {
if ($('#valorLiquidar_'+tmdId).val() == '') {
$('#valorLiquidar_'+tmdId).val(valor);
}
$('#valorLiquidar_'+tmdId).attr("disabled", false);
total = total + parseFloat(valor);
}
ct++;
var anexos = $(this).attr('data-anexos');
numAnexos += anexos;
if (numAnexos > 0) { ctComprovativos++; }
var dataDoc = $(this).attr('data-data');
datas += dataDoc;
var idAT = $(this).attr('data-idat');
idsAT += idAT;
});
$('#idsRefs').val(ids);
$('#docsNomes').val(nomes);
$('#docsDatas').val(datas);
$('#docsIdsAT').val(idsAT);
$('#docsNumAnexos').val(numAnexos);
if (ct>0) {
$("#btnPartilharDocumento, #btnDescarregarDocumentos").removeClass("disabled");
} else {
$("#btnPartilharDocumento, #btnDescarregarDocumentos").addClass("disabled");
}
if (ctComprovativos) {
$("#btnPartilharComprovativos").removeClass("disabled");
} else {
$("#btnPartilharComprovativos").addClass("disabled");
}
total = total.toFixed(2)
$('#totalRefs').val(total);
if (total>0) {
$('#btnGerarRef').html(' REF. MB ('+mostraMoeda(total)+' )');
$("#btnGerarRef").removeClass("disabled");
} else {
$('#btnGerarRef').html(' REF. MB');
$("#btnGerarRef").addClass("disabled");
}
$('input.inputRecibo:not(:disabled)').each(function(i, obj) {
var valor = $(this).val();
totalRecibo = totalRecibo + parseFloat(valor);
});
totalRecibo = totalRecibo.toFixed(2);
if (totalRecibo>0) {
$('#btnEmitirRecibo').html(' LIQUIDAR ('+mostraMoeda(totalRecibo)+' )');
$("#btnEmitirRecibo").removeClass("disabled");
$('#totalRecibo').val(totalRecibo);
$('#totalReciboTxt').html(mostraMoeda(totalRecibo));
} else {
$('#btnEmitirRecibo').html(' LIQUIDAR');
$("#btnEmitirRecibo").addClass("disabled");
}
if (totalRecibo < total) {
$("#btnGerarRef").addClass("disabled");
}
}
$("#checkAll").click(function(){
$('input:checkbox').not(this).prop('checked', this.checked);
handleRefs();
});
function handleMeioPagamento() {
var valorTotal = parseFloat($('#totalRecibo').val());
var valorNum = parseFloat($('#reciboValorNum').val());
if (isNaN(valorNum)) { valorNum = 0; }
var valorCheque = parseFloat($('#reciboValorCheque').val());
if (isNaN(valorCheque)) { valorCheque = 0; }
var valorTpa = parseFloat($('#reciboValorTpa').val());
if (isNaN(valorTpa)) { valorTpa = 0; }
var somaValores = valorNum + valorCheque + valorTpa;
if (somaValores.toFixed(2) == valorTotal && valorTotal > 0) {
$('#submit_recibo').attr("disabled", false);
} else {
$('#submit_recibo').attr("disabled", true);
}
if (valorCheque > 0) {
$('.camposCheque').show();
$(".chequeInputs").attr("required", true);
$("select[data-use-select2]").each(function() {
$(this).select2({
minimumResultsForSearch: '',
width: '100%',
dropdownParent: $(this).parent()
});
});
$('.select2').on('click', () => {
let selectField = document.querySelectorAll('.select2-search__field')
selectField.forEach((element, index) => {
element.focus();
})
});
} else {
$('.camposCheque').hide();
$(".chequeInputs").attr("required", false);
}
}
var modalRecibo;
function emitirRecibo() {
$("#submitRecibo")[0].reset();
handleMeioPagamento();
sendingForm('submitRecibo', false);
modalRecibo = new bootstrap.Modal(document.getElementById('modalRecibo'), { backdrop: 'static', keyboard: false });
modalRecibo.show();
}
$("#submitRecibo").submit(function(event) {
event.preventDefault();
var $this = $(this);
var serialize = $this.serialize();
sendingForm('submitRecibo', true);
var documentos = '';
$('input.inputRecibo').each(function(i, obj) {
var tmdId = $(this).attr('data-id');
var valor = $(this).val();
if (valor != '') {
if (documentos != '') { documentos += '|'; }
documentos += tmdId+'@'+valor;
}
});
if (documentos != '') {
documentos = btoa(documentos);
$.ajax({
type: 'POST',
url: '/paginas/refresh/emitir-recibo.php',
data: serialize+'&docs='+documentos,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if(data.charAt(0)=='R'){
toastr.success("Pedido submetido com sucesso. Aguarde enquanto a página é atualizada!");
setTimeout(function(){
window.location.href = window.location.href.split('?')[0]+'?print='+data;
}, 500);
} else {
toastr.error("Não foi possivel concluir o seu pedido.");
}
sendingForm('submitRecibo', false);
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
sendingForm('submitRecibo', false);
}
});
}
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
var tmpModal;
function mailCC(idCliente, nifCliente, emailCliente, dataMin, dataMax) {
$('#cc_mail_cliente_input').prop("checked", false);
$('#cc_mail_cliente_id').val(idCliente);
$('#cc_mail_cliente_nif').val(nifCliente);
$('.tmpEmail').remove();
if (emailCliente != '') {
var arrayEmails = emailCliente.split(',');
$.each(arrayEmails, function(i,email) {
if (isValidEmailAddress(email)) {
var input = $('CLIENTE - '+email+' ');
$('#cc_lista_emails').append(input);
}
});
} else if (nifCliente != '') {
$.ajax({
type: 'POST',
url: '/paginas/refresh/get-emails-nif.php',
data: '&nif='+nifCliente,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data != '') {
var arrayEmails = data.split(',');
$.each(arrayEmails, function(i,email) {
if (isValidEmailAddress(email)) {
var input = $('CLIENTE - '+email+' ');
$('#cc_lista_emails').append(input);
}
});
}
}
});
}
$('#dataMinCC').datepicker({
showOtherMonths: true,
selectOtherMonths: true,
minDate: dataMin,
maxDate: dataMax,
dateFormat: 'dd/mm/yy',
beforeShow: function (textbox, instance) {
var txtBoxOffset = $(this).offset();
var top = txtBoxOffset.top - $(window).scrollTop();
setTimeout(function () { instance.dpDiv.css({ top: top+45 }); }, 0);
},
onSelect: function(selectedDate) {
$('#dataMaxCC').datepicker('option', 'minDate', selectedDate);
}
});
$('#dataMaxCC').datepicker({
showOtherMonths: true,
selectOtherMonths: true,
minDate: dataMin,
maxDate: dataMax,
dateFormat: 'dd/mm/yy',
beforeShow: function (textbox, instance) {
var txtBoxOffset = $(this).offset();
var top = txtBoxOffset.top - $(window).scrollTop();
setTimeout(function () { instance.dpDiv.css({ top: top+45 }); }, 0);
},
onSelect: function(selectedDate) {
$('#dataMinCC').datepicker('option', 'maxDate', selectedDate);
}
});
$('#dataMinCC, #cc_min_data').val(dataMin);
$('#dataMaxCC, #cc_max_data').val(dataMax);
tmpModal = new bootstrap.Modal(document.getElementById('modalMailCC'), { backdrop: 'static', keyboard: false });
tmpModal.show();
}
function handleTipoCC(el) {
var min = $('#cc_min_data').val();
var max = $('#cc_max_data').val();
if ($(el).val() == 0) {
$('#dataMaxCC').datepicker('option', 'maxDate', '08/05/2026');
$('#dataMinCC').datepicker('option', 'maxDate', '08/05/2026');
} else {
$('#dataMaxCC').datepicker('option', 'maxDate', max);
$('#dataMaxCC').val(max);
$('#dataMinCC').datepicker('option', 'maxDate', max);
}
}
$("#enviarContaCorrente").submit(function(event) {
event.preventDefault();
var $this = $(this);
var serialize = $this.serialize();
sendingForm('enviarContaCorrente', true);
$.ajax({
type: 'POST',
url: '/paginas/mail/mail-contacorrente.php',
data: serialize,
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if(data==1){
toastr.success("E-mail enviado com sucesso");
$('#modalMailCC').hide();
tmpModal.hide();
$("#enviarContaCorrente")[0].reset();
}else if(data=="-98"){
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else if(data=="-99"){
toastr.error("Não foi possivel concluir o seu pedido.");
}
sendingForm('enviarContaCorrente', false);
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
sendingForm('enviarContaCorrente', false);
}
});
return false;
});
function openEncomenda(id) {
$('#modalEncLoading').show();
$('#modalEncContent').html('');
var myModal = new bootstrap.Modal(document.getElementById('modalEncomenda'), { backdrop: 'static', keyboard: false });
myModal.show();
$.ajax({
type: 'POST',
url: '/paginas/refresh/detalhes-encomenda.php',
data: '&id='+id,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#modalEncLoading').hide();
$('#modalEncContent').html(data);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
function reEncomendar(id) {
if (id) {
reencomendando(true);
$.ajax({
type: 'POST',
url: '/paginas/refresh/re-encomendar.php',
data: '&id='+id,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if (data == "1") {
window.location.href = "https://comercial-laltrait.aplataforma.com/pt/checkout-encomendas";
} else {
toastr.error("Não foi possivel concluir o seu pedido.");
reencomendando(false);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
reencomendando(false);
}
});
}
}
function reencomendando(on = true) {
if (on) {
$("#btnReencomendar").attr("readonly", true);
$("#btnReencomendar").addClass("btn-loading");
} else {
$("#btnReencomendar").attr("readonly", false);
$("#btnReencomendar").removeClass("btn-loading");
}
}
var lastNif = '';
var lastPais = '';
var modalValidarNif;
function openModalValidarNIF() {
resetValidNIF();
modalValidarNif = new bootstrap.Modal(document.getElementById('modalValidarNif'), { backdrop: 'static', keyboard: false });
modalValidarNif.show();
}
function resetValidNIF() {
lastNif = '';
$('#submit_nif_footer').hide();
$('#valida_nif').val('');
$('#nif_pais').val('ES').trigger("change");
$('#valida_nif').removeClass('is-invalid').removeClass('is-valid');
$('#feedback_nif').html('');
$('#submit_nif').attr("disabled", true);
$('#submit_nif').removeClass('btn-primary').addClass('btn-disabled');
}
var searchWaitNif = 0;
var searchWaitIntervalNif;
$('#valida_nif').bind('input', function(e){
var item = $(this);
searchWaitNif = 0;
if(!searchWaitIntervalNif) searchWaitIntervalNif = setInterval(function(){
if(searchWaitNif >= 3){
clearInterval(searchWaitIntervalNif);
searchWaitIntervalNif = '';
checkValidNIF();
searchWaitNif = 0;
}
searchWaitNif++;
},200);
});
function checkValidNIF() {
var pais = $('#nif_pais').val();
var tmp = $('#valida_nif').val();
var nif = tmp;
if (nif.length>=5 && (lastNif != nif || lastPais != pais)) {
lastNif = nif;
lastPais = pais;
$('#submit_nif').addClass("btn-loading");
$('#submit_nif_footer').show();
$.ajax({
type: 'POST',
url: '/paginas/refresh/valida-nif.php',
data: '&nif='+nif+'&pais='+pais,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&type=check';
},
success:function(data){
$('#submit_nif').removeClass("btn-loading");
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if (data=="-1" || data=="-2") {
$('#feedback_nif').html('NIF não validado pela VIES nem NIF.PT ');
if (data=="-2") {
$('#feedback_nif').removeClass('invalid-feedback').addClass('valid-feedback');
$('#valida_nif').removeClass('is-invalid').addClass('is-valid');
$('#submit_nif').attr("disabled", false);
$('#submit_nif').removeClass('btn-disabled').addClass('btn-primary');
$('#submit_nif_footer').show();
$('#nc_nif, #ncp_nif').val(nif);
} else {
$('#feedback_nif').removeClass('valid-feedback').addClass('invalid-feedback');
$('#valida_nif').removeClass('is-valid').addClass('is-invalid');
$('#submit_nif').attr("disabled", true);
$('#submit_nif').removeClass('btn-primary').addClass('btn-disabled');
$('#submit_nif_footer').hide();
}
$('#submit_nif').html('CRIAR CLIENTE');
$('#submit_nif_potencial').hide();
$('#submit_nif_potencial').attr("disabled", true);
$('#submit_nif_potencial').removeClass('btn-primary').addClass('btn-disabled');
$('#tipoModalNIF').val('modalCriarCliente');
} else {
resetFormCriarCliente();
resetFormCriarClientePotencial();
var resposta = jQuery.parseJSON(data);
if(resposta.existe=="1") {
$('#feedback_nif').removeClass('invalid-feedback').addClass('valid-feedback');
$('#valida_nif').removeClass('is-invalid').addClass('is-valid');
if (resposta.resultados == 1) {
$('#lista_resultados_div').hide();
$('#nif_pais').val(resposta.pais).trigger("change");
$('#validar_nif').val(resposta.nif);
$('#feedback_nif').html('Este NIF é nosso cliente: '+resposta.nome);
$('#submit_nif').attr("disabled", false);
$('#submit_nif').removeClass('btn-disabled').addClass('btn-primary');
} else {
$('#feedback_nif').html('Resultados encontrados: '+resposta.resultados);
$('#lista_resultados_div').show();
var listagem = jQuery.parseJSON(resposta.listagem);
$('#lista_resultados').html('Selecione um resultado ');
$.each(listagem, function(i, item) {
$('#lista_resultados').append(''+item.nif+' - '+item.nome_fiscal+' ');
});
}
$('#submit_nif').html('ACEDER');
$('#submit_nif_potencial').hide();
$('#submit_nif_potencial').attr("disabled", true);
$('#submit_nif_potencial').removeClass('btn-primary').addClass('btn-disabled');
$('#submit_nif_footer').show();
$('#tipoModalNIF').val('modalDetalhesNifCliente');
} else {
$('#lista_resultados_div').hide();
$('#feedback_nif').html('Este NIF não é nosso cliente: '+resposta.nome);
$('#feedback_nif').removeClass('invalid-feedback').addClass('valid-feedback');
$('#valida_nif').removeClass('is-invalid').addClass('is-valid');
$('#submit_nif').attr("disabled", false);
$('#submit_nif').removeClass('btn-disabled').addClass('btn-primary');
$('#submit_nif').html('CRIAR CLIENTE');
$('#submit_nif_potencial').show();
$('#submit_nif_potencial').attr("disabled", false);
$('#submit_nif_potencial').removeClass('btn-disabled').addClass('btn-primary');
$('#submit_nif_footer').show();
$('#tipoModalNIF').val('modalCriarCliente');
$('#nc_nif, #ncp_nif').val(resposta.nif);
$('#nc_nome, #ncp_nome').val(resposta.nome);
$('#nc_morada, #ncp_morada').val(resposta.morada);
$('#nc_localidade, #ncp_localidade').val(resposta.localidade);
$('#nc_codigo_postal, #ncp_codigo_postal').val(resposta.codpostal);
$('#nc_pais, #ncp_pais, #nc_entrega_pais').val(resposta.pais).trigger("change");
}
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
$('#feedback_nif').html('NIF Inválido');
$('#feedback_nif').removeClass('valid-feedback').addClass('invalid-feedback');
$('#valida_nif').removeClass('is-valid').addClass('is-invalid');
$('#submit_nif').attr("disabled", true);
$('#submit_nif').removeClass('btn-primary').addClass('btn-disabled');
$('#submit_nif').removeClass("btn-loading");
$('#submit_nif_footer').hide();
$('#submit_nif_potencial').hide();
$('#submit_nif_potencial').attr("disabled", true);
$('#submit_nif_potencial').removeClass('btn-primary').addClass('btn-disabled');
}
});
} else {
if (nif.length>0 && lastNif != nif) {
$('#feedback_nif').html('NIF Inválido');
$('#feedback_nif').removeClass('valid-feedback').addClass('invalid-feedback');
$('#valida_nif').removeClass('is-valid').addClass('is-invalid');
$('#submit_nif').attr("disabled", true);
$('#submit_nif').removeClass('btn-primary').addClass('btn-disabled');
$('#submit_nif_potencial').attr("disabled", true);
$('#submit_nif_potencial').removeClass('btn-primary').addClass('btn-disabled');
$('#submit_nif_footer').hide();
}
}
}
function handleResultadoNIF(el) {
var nif = $(el).val();
$('#validar_nif').val(nif);
if (nif != '') {
$('#submit_nif').attr("disabled", false);
$('#submit_nif').removeClass('btn-disabled').addClass('btn-primary');
} else {
$('#submit_nif').attr("disabled", true);
$('#submit_nif').removeClass('btn-primary').addClass('btn-disabled');
}
}
function validaNIF(nif, ignoreFirst=true) {
nif = $.trim(nif);
if (!$.isNumeric(nif) || nif.length != 9) {
return false;
} else {
var nifSplit = nif.split("");
if ($.inArray(parseInt(nifSplit[0]), [1, 2, 3, 5, 6, 7, 8, 9]) > -1 || ignoreFirst) {
var checkDigit = 0;
for (var i = 0; i < 8; i++) {
checkDigit += parseInt(nifSplit[i]) * (10 - i - 1);
}
checkDigit = 11 - (checkDigit % 11);
if (checkDigit >= 10) checkDigit = 0;
if (checkDigit == parseInt(nifSplit[8])) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
var criarClientePotencial = false;
$("#submit_nif").click(function() {
criarClientePotencial = false;
$("#getDetalhesCliente").submit();
});
$("#submit_nif_potencial").click(function() {
criarClientePotencial = true;
$("#getDetalhesCliente").submit();
});
var modalCriarCliente;
var modalCriarClientePotencial;
var detalhesClienteModal;
$("#getDetalhesCliente").submit(function(event) {
event.preventDefault();
$('#modalDetalhesClienteLoading').show();
$('#modalDetalhesClienteContent').html('');
$('#modalNifCliente').modal('toggle');
setTimeout(function(){
$('#div_nc_estabelecimento_base').hide();
var tipoModal = $('#tipoModalNIF').val();
if (tipoModal == 'modalCriarCliente') {
if (criarClientePotencial) {
modalCriarClientePotencial = new bootstrap.Modal(document.getElementById('modalCriarClientePotencial'), { backdrop: 'static', keyboard: false });
modalCriarClientePotencial.show();
} else {
modalCriarCliente = new bootstrap.Modal(document.getElementById('modalCriarCliente'), { backdrop: 'static', keyboard: false });
modalCriarCliente.show();
}
} else if (tipoModal == 'modalDetalhesNifCliente') {
detalhesClienteModal = new bootstrap.Modal(document.getElementById('modalDetalhesNifCliente'), { backdrop: 'static', keyboard: false });
detalhesClienteModal.show();
var nif = $('#validar_nif').val();
$.ajax({
type: 'POST',
url: '/paginas/refresh/valida-nif.php',
data: '&nif='+nif,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&type=view';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#modalDetalhesClienteLoading').hide();
$('#modalDetalhesClienteContent').html(data);
$('#validaNifDataTable').DataTable({
order: [[1, 'asc']],
language: {
"sProcessing": " ",
"sLengthMenu": "Mostrar _MENU_ registos",
"sZeroRecords": "Não foram encontrados resultados",
"sEmptyTable": "Nenhum dado disponível nesta tabela",
"sInfo": "A mostrar de _START_ a _END_ de um total de _TOTAL_ registos",
"sInfoEmpty": "A mostrar 0 de un total de 0 registos",
"sInfoFiltered": "(filtrado de um total de _MAX_ registos)",
"sInfoPostFix": "",
"sSearch": "Procurar:",
"sUrl": "",
"sInfoThousands": ",",
"sLoadingRecords": "A carregar...",
"oPaginate": {
"sFirst": "Primeiro",
"sLast": "Último",
"sNext": "Seguinte",
"sPrevious": "Anterior"
},
"oAria": {
"sSortAscending": ": Ordenar a coluna de forma ascendente",
"sSortDescending": ": Ordenar a coluna de forma descendente"
},
searchPlaceholder: "Procurar...",
sSearch: ""
}, });
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
resetValidNIF();
}, 500);
return false;
});
function getDadosEstabelecimento() {
var nif = $('#nc_nif').val();
var estab = $('#nc_estabelecimento_base').val();
if (estab > 0) {
$.ajax({
type: 'POST',
url: '/paginas/refresh/valida-nif.php',
data: '&nif='+nif+'&estab='+estab,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&type=dados_estab';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
var resposta = jQuery.parseJSON(data);
if (resposta.status=="1") {
$('#nc_nome').val(resposta.nome_fiscal);
$('#nc_pais, #nc_entrega_pais').val(resposta.codigo_pais).trigger("change");
$('#nc_morada').val(resposta.morada_faturacao);
$('#nc_localidade').val(resposta.localidade_faturacao);
$('#nc_codigo_postal').val(resposta.codpostal_faturacao);
$('#nc_grupo').html(resposta.grupos);
$('#nc_grupo').val(resposta.grupo).trigger("change");
$('#nc_pagamento_nome').val(resposta.pessoa_cobranca);
$('#nc_pagamento_telefone').val(resposta.contacto_cobranca);
$('#nc_pagamento_email').val(resposta.email_cobranca);
$('#nc_prazo_pagamento').val(resposta.id_condicao_pagamento);
if (resposta.id_condicao_pagamento) {
$('#nc_prazo_pagamento').attr("disabled", true);
} else {
$('#nc_prazo_pagamento').attr("disabled", false);
}
} else {
$('#nc_nome').val('');
$('#nc_pais').val('').trigger("change");
$('#nc_morada').val('');
$('#nc_localidade').val('');
$('#nc_codigo_postal').val('');
$('#nc_grupo').html($('#nc_grupos_default').val());
$('#nc_grupo').val('').trigger("change");
$('#nc_pagamento_nome').val('');
$('#nc_pagamento_telefone').val('');
$('#nc_pagamento_email').val('');
$('#nc_prazo_pagamento').val('').trigger("change");
$('#nc_prazo_pagamento').attr("disabled", false);
}
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
} else {
$('#nc_nome').val('');
$('#nc_pais').val('').trigger("change");
$('#nc_morada').val('');
$('#nc_localidade').val('');
$('#nc_codigo_postal').val('');
$('#nc_grupo').html($('#nc_grupos_default').val());
$('#nc_grupo').val('').trigger("change");
$('#nc_pagamento_nome').val('');
$('#nc_pagamento_telefone').val('');
$('#nc_pagamento_email').val('');
$('#nc_prazo_pagamento').val('').trigger("change");
$('#nc_prazo_pagamento').attr("disabled", false);
}
}
function criarEstabelecimento() {
var opcoes = $('#estab_opcoes').val();
var nif = $('#estab_nif').val();
var nome_fiscal = $('#estab_nome_fiscal').val();
var pais = $('#estab_pais_faturacao').val();
var morada_faturacao = $('#estab_morada_faturacao').val();
var localidade_faturacao = $('#estab_localidade_faturacao').val();
var codpostal_faturacao = $('#estab_codpostal_faturacao').val();
var grupos = $('#estab_grupos').val();
var grupo = $('#estab_grupo').val();
var pessoa_cobranca = $('#estab_pessoa_cobranca').val();
var contacto_cobranca = $('#estab_contacto_cobranca').val();
var email_cobranca = $('#estab_email_cobranca').val();
var id_condicao_pagamento = $('#estab_id_condicao_pagamento').val();
$('#div_nc_estabelecimento_base').show();
$('#nc_estabelecimento_base').html(opcoes);
$('#nc_nif').val(nif);
$('#nc_nome').val(nome_fiscal);
$('#nc_pais, #nc_entrega_pais').val(pais).trigger("change");
$('#nc_morada').val(morada_faturacao);
$('#nc_localidade').val(localidade_faturacao);
$('#nc_codigo_postal').val(codpostal_faturacao);
$('#nc_grupo').html(grupos);
$('#nc_grupo').val(grupo).trigger("change");
$('#nc_pagamento_nome').val(pessoa_cobranca);
$('#nc_pagamento_telefone').val(contacto_cobranca);
$('#nc_pagamento_email').val(email_cobranca);
$('#nc_prazo_pagamento').val(id_condicao_pagamento).trigger("change");
if (id_condicao_pagamento != '') {
$('#nc_prazo_pagamento').attr("disabled", true);
} else {
$('#nc_prazo_pagamento').attr("disabled", false);
}
$('#'+$('#tipoModalNIF').val()).modal('toggle');
setTimeout(function(){
modalCriarCliente = new bootstrap.Modal(document.getElementById('modalCriarCliente'), { backdrop: 'static', keyboard: false });
modalCriarCliente.show();
}, 500);
}
function getCondicoesPagamento() {
var empresa = $('#nc_empresa_faturacao').val();
var grupo = $('#nc_grupo').val();
if (empresa != '' && grupo != '') {
$.ajax({
type: 'POST',
url: '/paginas/refresh/get_condicoes_pagamento.php',
data: '&empresa='+empresa+'&grupo='+grupo,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&type=dados_estab';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#nc_prazo_pagamento').val(data).trigger("change");
if (data != '') {
$('#nc_prazo_pagamento').attr("disabled", true);
} else {
$('#nc_prazo_pagamento').attr("disabled", false);
}
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
} else {
$('#nc_prazo_pagamento').val('');
$('#nc_prazo_pagamento').attr("disabled", false);
}
}
function checkTipologia(el) {
var valor = $(el).val();
if (valor == 'Institucionais_Concursos Públicos') {
$('.tipologiaConcurso').show();
$(".inputsConcurso").attr("required", true);
} else {
$('.tipologiaConcurso').hide();
$(".inputsConcurso").attr("required", false);
}
handleTipologiaCliente(el);
}
function handleTipologiaCliente(el) {
var nivel = $(el).find('option:selected').data('nivel');
$('#nivel_subtipologia').val(nivel);
$('.tipNiveis').hide();
$('.tipNiveis').find('input, select').each(function() {
$(this).val('').trigger('change');
$(this).prop('required', false);
});
var niveisActivos = $('.tipNivel'+nivel);
niveisActivos.each(function() {
$(this).show();
$(this).find('input, select').each(function() {
$(this).val('').trigger('change');
$(this).prop('required', true);
});
});
}
function handleSubNivelFields(el,tmpNivel) {
var nivel = $('#'+tmpNivel+'-'+el).find('option:selected').data('nivel');
$('.tipSubNiveis').hide();
$('.tipSubNiveis').find('input, select').each(function() {
$(this).val('').trigger('change');
$(this).prop('required', false);
});
var niveisActivos = $('.tipNivel'+nivel+el);
niveisActivos.each(function() {
$(this).show();
$(this).find('input, select').each(function() {
$(this).val('').trigger('change');
$(this).prop('required', true);
});
});
}
function changePais() {
var pais = $('#nc_entrega_pais').val();
if (pais == 'PT') {
$('.camposPortugal').show();
$(".inputsPortugal").attr("required", true);
} else {
$('.camposPortugal').hide();
$(".inputsPortugal").attr("required", false);
}
atualizaMorada();
changePatternPostal('nc_entrega_pais','nc_entrega_codigo_postal');
}
function changePatternPostal(origem,destino) {
var pattern = $('#'+origem+' option:selected').attr('data-regex');
$('#'+destino).attr("pattern", pattern);
if (pattern == '') {
$('#'+destino).attr("required", false);
$('#'+destino).attr("disabled", true);
} else {
$('#'+destino).attr("required", true);
$('#'+destino).attr("disabled", false);
}
}
function checkCodigoPostal() {
var codigo = $('#nc_entrega_codigo_postal').val();
if (codigo.length>=4) {
var pais = $('#nc_entrega_pais').val();
if (pais == 'PT') {
$.ajax({
type: 'POST',
url: '/paginas/refresh/get_codpostais.php',
data: '&codigo='+codigo,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
var resposta = jQuery.parseJSON(data);
if (resposta.status == 1) {
$('#nc_entrega_distrito').val(resposta.distrito);
$('#nc_entrega_concelho').val(resposta.concelho);
$('#nc_entrega_freguesia').val(resposta.freguesia);
$('#nc_entrega_localidade').val(resposta.localidade);
atualizaMorada();
var armazem = $('#nc_armazem_picking').val();
$.ajax({
type: 'POST',
url: '/paginas/refresh/get_rotas.php',
data: '&distrito='+resposta.distrito+'&concelho='+resposta.concelho+'&freguesia='+resposta.freguesia+'&armazem='+armazem,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
$('#nc_entrega_rota').html(data);
$('#nc_entrega_rota').attr("disabled", false);
},
error: function(data) { toastr.error("Não foi possivel concluir o seu pedido."); }
});
} else {
$('#nc_entrega_distrito, #nc_entrega_concelho, #nc_entrega_freguesia, #nc_entrega_localidade').val('');
$('#nc_entrega_rota').html('');
$('#nc_entrega_rota').attr("disabled", true);
}
}
},
error: function(data) { toastr.error("Não foi possivel concluir o seu pedido."); }
});
}else{
$('#nc_entrega_distrito, #nc_entrega_concelho, #nc_entrega_freguesia, #nc_entrega_localidade').val('');
$('#nc_entrega_rota').html('');
$('#nc_entrega_rota').attr("disabled", true);
}
} else {
$('#nc_entrega_distrito, #nc_entrega_concelho, #nc_entrega_freguesia, #nc_entrega_localidade').val('');
$('#nc_entrega_rota').html('');
$('#nc_entrega_rota').attr("disabled", true);
}
};
function atualizaZonaVisita(el) {
var vendedor = $(el).val();
if (vendedor) {
$.ajax({
type: 'POST',
url: '/paginas/refresh/get_zonasvisita.php',
data: '&vendedor='+vendedor,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
$('#nc_zonavisita').html(data);
},
error: function(data) { toastr.error("Não foi possivel concluir o seu pedido."); }
});
} else {
$('#nc_zonavisita').html('');
}
};
function resetFormCriarCliente() {
$('#novaFichaCliente')[0].reset();
$('#novaFichaCliente').parsley().reset();
$('#novaFichaCliente select').val('').trigger("change");
$('#nc_coordenador').val('').trigger("change");
$('#nc_vendedor').val('').trigger("change");
$('#nc_entrega_pais').val('ES').trigger("change");
resetJQuerySteps('#novo-cliente-wizard',3);
}
function resetFormCriarClientePotencial() {
$('#novaFichaClientePotencial')[0].reset();
$('#novaFichaClientePotencial').parsley().reset();
$('#novaFichaClientePotencial select').val('').trigger("change");
$('#ncp_vendedor').val('').trigger("change");
$('#ncp_entrega_pais').val('ES').trigger("change");
}
function resetJQuerySteps(elementTarget, noOfSteps){
var noOfSteps = noOfSteps - 1;
var currentIndex = $(elementTarget).steps("getCurrentIndex");
if(currentIndex >= 1){
for(var x = 0; x < currentIndex;x++){
$(elementTarget).steps("previous");
}
}
setTimeout(function resetHeaderCall(){
var y, steps;
for(y = 0, steps= 2; y < noOfSteps;y++){
try{
$('${elementTarget} > .steps > ul > li:nth-child(${steps})').removeClass("done");
$('${elementTarget} > .steps > ul > li:nth-child(${steps})').removeClass("current");
$('${elementTarget} > .steps > ul > li:nth-child(${steps})').addClass("disabled");
}
catch(err){}
steps++;
}
}, 50);
$(".done").each(function() { $(this).removeClass('done'); });
}
$("#novaFichaCliente").submit(function(event) {
event.preventDefault();
var $this = $(this);
var categoria = $('#nc_categoria').val();
var serialize = $this.serialize();
submittingCriarCliente(true);
$.ajax({
type: 'POST',
url: '/paginas/refresh/criar_cliente.php',
data: serialize+'&categoria='+categoria,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if (data == "1") {
modalCriarCliente.hide();
resetFormCriarCliente();
toastr.success("Pedido submetido com sucesso. Aguarde enquanto a página é atualizada!");
} else {
toastr.error("Não foi possivel concluir o seu pedido.");
}
submittingCriarCliente(false);
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
submittingCriarCliente(false);
}
});
});
function submittingCriarCliente(on = true) {
if (on) {
$("#novaFichaCliente input").attr("readonly", true);
$("#novaFichaCliente button").attr("readonly", true);
$('a[href="#finish"]').attr("disabled", true);
$('a[href="#finish"]').addClass("btn btn-loading");
} else {
$("#novaFichaCliente input").attr("readonly", false);
$("#novaFichaCliente button").attr("readonly", false);
$('a[href="#finish"]').attr("disabled", false);
$('a[href="#finish"]').removeClass("btn btn-loading");
}
}
$("#novaFichaClientePotencial").submit(function(event) {
event.preventDefault();
var ncp_empresa_faturacao = $('#ncp_empresa_faturacao').parsley();
var ncp_armazem_picking = $('#ncp_armazem_picking').parsley();
var ncp_nif = $('#ncp_nif').parsley();
var ncp_nome = $('#ncp_nome').parsley();
var ncp_morada = $('#ncp_morada').parsley();
var ncp_localidade = $('#ncp_localidade').parsley();
var ncp_codigo_postal = $('#ncp_codigo_postal').parsley();
var ncp_nome_comercial = $('#ncp_nome_comercial').parsley();
var ncp_vendedor = $('#ncp_vendedor').parsley();
if (ncp_empresa_faturacao.isValid() && ncp_armazem_picking.isValid() && ncp_nif.isValid() && ncp_nome.isValid() && ncp_morada.isValid() && ncp_localidade.isValid() && ncp_codigo_postal.isValid() && ncp_nome_comercial.isValid() && ncp_vendedor.isValid()) {
var $this = $(this);
var serialize = $this.serialize();
sendingForm('novaFichaClientePotencial', true);
$.ajax({
type: 'POST',
url: '/paginas/refresh/criar_cliente_potencial.php',
data: serialize,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if (data == "1") {
modalCriarClientePotencial.hide();
resetFormCriarClientePotencial();
toastr.success("Pedido submetido com sucesso. Aguarde enquanto a página é atualizada!");
} else {
toastr.error("Não foi possivel concluir o seu pedido.");
}
sendingForm('novaFichaClientePotencial', false);
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
sendingForm('novaFichaClientePotencial', false);
}
});
} else {
ncp_empresa_faturacao.validate();
ncp_armazem_picking.validate();
ncp_nif.validate();
ncp_nome.validate();
ncp_morada.validate();
ncp_localidade.validate();
ncp_codigo_postal.validate();
ncp_nome_comercial.validate();
ncp_vendedor.validate();
}
});
var maploaded = false;
var theMarker;
var theMap;
var icon = {url: "theme/img/mapmarker.png",scaledSize:new google.maps.Size(25,25),origin:new google.maps.Point(0,0),anchor:new google.maps.Point(0,0)};
$('#novo-cliente-wizard').steps({
headerTag: 'h3',
bodyTag: 'section',
autoFocus: true,
labels: {
previous: "Anterior",
next: "Seguinte",
finish: "Concluir",
},
titleTemplate: '#index#<\/span> #title#<\/span>',
onStepChanging: function(event, currentIndex, newIndex) {
if (currentIndex < newIndex) {
// Step 1 form validation
if (currentIndex === 0) {
var nc_empresa_faturacao = $('#nc_empresa_faturacao').parsley();
var nc_armazem_picking = $('#nc_armazem_picking').parsley();
var nc_nif = $('#nc_nif').parsley();
var nc_nome = $('#nc_nome').parsley();
var nc_morada = $('#nc_morada').parsley();
var nc_localidade = $('#nc_localidade').parsley();
var nc_codigo_postal = $('#nc_codigo_postal').parsley();
var nc_nome_comercial = $('#nc_nome_comercial').parsley();
var nc_grupo = $('#nc_grupo').parsley();
var nc_vendedor = $('#nc_vendedor').parsley();
var nc_coordenador = $('#nc_coordenador').parsley();
var nc_zonavisita = $('#nc_zonavisita').parsley();
var nc_categoria = $('#nc_categoria').parsley();
var nc_tipologia = $('#nc_tipologia').parsley();
var nc_concurso_inicio = $('#nc_concurso_inicio').parsley();
var nc_concurso_fim = $('#nc_concurso_fim').parsley();
var nc_contacto_nome = $('#nc_contacto_nome').parsley();
var nc_contacto_telefone = $('#nc_contacto_telefone').parsley();
var nc_contacto_email = $('#nc_contacto_email').parsley();
var a_numero_quartos = ($('#A-numero_quartos').length) ? $('#A-numero_quartos').parsley() : $('#dummy_input').parsley();
var a_restaurante = ($('#A-restaurante').length) ? $('#A-restaurante').parsley() : $('#dummy_input').parsley();
var a_nivel_qualidade = ($('#A-nivel_qualidade').length) ? $('#A-nivel_qualidade').parsley() : $('#dummy_input').parsley();
var a_numero_lugares_sentados = ($('#A-numero_lugares_sentados').length) ? $('#A-numero_lugares_sentados').parsley() : $('#dummy_input').parsley();
var a_preco_medio = ($('#A-preco_medio').length) ? $('#A-preco_medio').parsley() : $('#dummy_input').parsley();
var a_refeicoes_medias_dia = ($('#A-refeicoes_medias_dia').length) ? $('#A-refeicoes_medias_dia').parsley() : $('#dummy_input').parsley();
var b_nivel_qualidade = ($('#B-nivel_qualidade').length) ? $('#B-nivel_qualidade').parsley() : $('#dummy_input').parsley();
var b_numero_lugares_sentados = ($('#B-numero_lugares_sentados').length) ? $('#B-numero_lugares_sentados').parsley() : $('#dummy_input').parsley();
var b_preco_medio = ($('#B-preco_medio').length) ? $('#B-preco_medio').parsley() : $('#dummy_input').parsley();
var b_refeicoes_medias_dia = ($('#B-refeicoes_medias_dia').length) ? $('#B-refeicoes_medias_dia').parsley() : $('#dummy_input').parsley();
var c_fabrico_proprio = ($('#C-fabrico_proprio').length) ? $('#C-fabrico_proprio').parsley() : $('#dummy_input').parsley();
var d_concurso_publico = ($('#D-concurso_publico').length) ? $('#D-concurso_publico').parsley() : $('#dummy_input').parsley();
var d_entidade_publica = ($('#D-entidade_publica').length) ? $('#D-entidade_publica').parsley() : $('#dummy_input').parsley();
if (nc_empresa_faturacao.isValid() && nc_armazem_picking.isValid() && nc_nif.isValid() && nc_nome.isValid() && nc_morada.isValid() && nc_localidade.isValid() && nc_codigo_postal.isValid() && nc_nome_comercial.isValid() && nc_grupo.isValid() && nc_vendedor.isValid() && nc_coordenador.isValid() && nc_zonavisita.isValid() && nc_categoria.isValid() && nc_tipologia.isValid() && nc_contacto_nome.isValid() && nc_contacto_telefone.isValid() && nc_contacto_email.isValid() && a_numero_quartos.isValid() && a_restaurante.isValid() && a_nivel_qualidade.isValid() && a_numero_lugares_sentados.isValid() && a_preco_medio.isValid() && a_refeicoes_medias_dia.isValid() && b_nivel_qualidade.isValid() && b_numero_lugares_sentados.isValid() && b_preco_medio.isValid() && b_refeicoes_medias_dia.isValid() && c_fabrico_proprio.isValid() && d_concurso_publico.isValid() && d_entidade_publica.isValid()) {
if (validaNIF($('#nc_nif').val()) || $('#nc_pais').val() != 'PT') {
return true;
} else {
$('#nc_nif').addClass('parsley-error');
}
} else {
nc_empresa_faturacao.validate();
nc_armazem_picking.validate();
nc_nif.validate();
nc_nome.validate();
nc_morada.validate();
nc_localidade.validate();
nc_codigo_postal.validate();
nc_nome_comercial.validate();
nc_grupo.validate();
nc_vendedor.validate();
nc_coordenador.validate();
nc_zonavisita.validate();
nc_categoria.validate();
nc_tipologia.validate();
nc_concurso_inicio.validate();
nc_concurso_fim.validate();
nc_contacto_nome.validate();
nc_contacto_telefone.validate();
nc_contacto_email.validate();
a_numero_quartos.validate();
a_restaurante.validate();
a_nivel_qualidade.validate();
a_numero_lugares_sentados.validate();
a_preco_medio.validate();
a_refeicoes_medias_dia.validate();
b_nivel_qualidade.validate();
b_numero_lugares_sentados.validate();
b_preco_medio.validate();
b_refeicoes_medias_dia.validate();
c_fabrico_proprio.validate();
d_concurso_publico.validate();
d_entidade_publica.validate();
}
}
// Step 2 form validation
if (currentIndex === 1) {
var nc_pagamento_nome = $('#nc_pagamento_nome').parsley();
var nc_pagamento_telefone = $('#nc_pagamento_telefone').parsley();
var nc_pagamento_email = $('#nc_pagamento_email').parsley();
var nc_consumo_expectavel = $('#nc_consumo_expectavel').parsley();
var nc_prazo_pagamento = $('#nc_prazo_pagamento').parsley();
var nc_negociacao_precos = $('#nc_negociacao_precos').parsley();
var nc_tipo_encomendas = $('#nc_tipo_encomendas').parsley();
var nc_tipo_entregas = $('#nc_tipo_entregas').parsley();
if (nc_pagamento_nome.isValid() && nc_pagamento_telefone.isValid() && nc_pagamento_email.isValid() && nc_consumo_expectavel.isValid() && nc_prazo_pagamento.isValid() && nc_negociacao_precos.isValid() && nc_tipo_encomendas.isValid() && nc_tipo_entregas.isValid()) {
return true;
} else {
nc_pagamento_nome.validate();
nc_pagamento_telefone.validate();
nc_pagamento_email.validate();
nc_consumo_expectavel.validate();
nc_prazo_pagamento.validate();
nc_negociacao_precos.validate();
nc_tipo_encomendas.validate();
nc_tipo_entregas.validate();
}
}
// Always allow step back to the previous step even if the current step is not valid.
} else {
return true;
}
},
onStepChanged: function (event, currentIndex, priorIndex) {
if (priorIndex == 1 && !maploaded) {
setTimeout(function(){
theMap = new GMaps({
div: '#theMap',
zoom: 6,
center: {lat: 39.3340399, lng: -7.6547444},
mapTypeControl: false,
zoomControl : true,
zoomControlOpt: { style : 'SMALL', position: 'TOP_LEFT' },
panControl : false,
disableDefaultUI: true
});
var styles = [{"featureType":"transit","stylers":[{"visibility":"off"}]}];
theMap.addStyle({styledMapName:"Styled Map", styles:styles, mapTypeId:"map_style" });
theMap.setStyle("map_style");
}, 200);
maploaded = true;
}
},
onFinishing: function(e, currentIndex) {
var nc_entrega_pais = $('#nc_entrega_pais').parsley();
var nc_entrega_distrito = $('#nc_entrega_distrito').parsley();
var nc_entrega_concelho = $('#nc_entrega_concelho').parsley();
var nc_entrega_freguesia = $('#nc_entrega_freguesia').parsley();
var nc_entrega_codigo_postal = $('#nc_entrega_codigo_postal').parsley();
var nc_entrega_localidade = $('#nc_entrega_localidade').parsley();
var nc_entrega_morada = $('#nc_entrega_morada').parsley();
var nc_pin_confirm = $('#nc_pin_confirm').parsley();
var nc_entrega_rota = $('#nc_entrega_rota').parsley();
var nc_entrega_manha_inicio = $('#nc_entrega_manha_inicio').parsley();
var nc_entrega_manha_fim = $('#nc_entrega_manha_fim').parsley();
var nc_entrega_tarde_inicio = $('#nc_entrega_tarde_inicio').parsley();
var nc_entrega_tarde_fim = $('#nc_entrega_tarde_fim').parsley();
if (nc_entrega_pais.isValid() && nc_entrega_distrito.isValid() && nc_entrega_concelho.isValid() && nc_entrega_freguesia.isValid() && nc_entrega_codigo_postal.isValid() && nc_entrega_localidade.isValid() && nc_entrega_morada.isValid() && nc_pin_confirm.isValid() && nc_entrega_rota.isValid() && nc_entrega_manha_inicio.isValid() && nc_entrega_manha_fim.isValid() && nc_entrega_tarde_inicio.isValid() && nc_entrega_tarde_fim.isValid()) {
var form = $(this);
form.find(':disabled').prop('disabled', false);
form.submit();
return true;
} else {
nc_entrega_pais.validate();
nc_entrega_distrito.validate();
nc_entrega_concelho.validate();
nc_entrega_freguesia.validate();
nc_entrega_codigo_postal.validate();
nc_entrega_morada.validate();
nc_pin_confirm.validate();
nc_entrega_rota.validate();
nc_entrega_manha_inicio.validate();
nc_entrega_manha_fim.validate();
nc_entrega_tarde_inicio.validate();
nc_entrega_tarde_fim.validate();
}
}
});
function atualizaMorada() {
var address = $('#nc_entrega_morada').val()+' '+$('#nc_entrega_codigo_postal').val()+' '+$('#nc_entrega_freguesia option:selected').html()+' '+$('#nc_entrega_localidade').val()+' '+$('#nc_entrega_concelho option:selected').html()+' '+$('#nc_entrega_distrito option:selected').html()+' - '+$('#nc_entrega_pais option:selected').html();
if (maploaded) {
GMaps.geocode({
address: address,
callback: function(results, status) {
if (status == 'OK') {
var latlng = results[0].geometry.location;
var latitude = latlng.lat();
var longitude = latlng.lng();
theMap.removeMarkers();
if (theMarker) { theMarker.setMap(null); }
theMarker = theMap.addMarker({
lat: latitude,
lng: longitude,
draggable: true
});
google.maps.event.addListener(theMarker, "dragend", function () {
document.getElementById('nc_entrega_latitude').value = theMarker.getPosition().lat().toFixed(6);
document.getElementById('nc_entrega_longitude').value = theMarker.getPosition().lng().toFixed(6);
});
theMap.fitZoom();
theMap.setZoom(theMap.getZoom() > 18 ? 18 : theMap.getZoom());
$("#nc_entrega_latitude").val(latitude);
$("#nc_entrega_longitude").val(longitude);
}
}
});
}
}
function copiarMoradaFiscal() {
var codigoPostal = $('#nc_codigo_postal').val();
$('#nc_entrega_codigo_postal').val(codigoPostal.split(' ')[0]);
$('#nc_entrega_localidade').val($('#nc_localidade').val());
$('#nc_entrega_morada').val($('#nc_morada').val()).trigger('change');
checkCodigoPostal();
}
function getHorasSeguintes(origem, destino, start=0, end=24, extraName='') {
if (origem == 'nc_entrega_manha_inicio'+extraName) {
$('#nc_entrega_manha_fim'+extraName).html(' ').attr("disabled", true);
$('#nc_entrega_tarde_inicio'+extraName).html(' ').attr("disabled", true);
$('#nc_entrega_tarde_fim'+extraName).html(' ').attr("disabled", true);
} else if (origem == 'nc_entrega_manha_fim'+extraName) {
$('#nc_entrega_tarde_inicio'+extraName).html(' ').attr("disabled", true);
$('#nc_entrega_tarde_fim'+extraName).html(' ').attr("disabled", true);
} else if (origem == 'nc_entrega_tarde_inicio'+extraName) {
$('#nc_entrega_tarde_fim'+extraName).html(' ').attr("disabled", true);
}
var index = parseInt($('#'+origem+' option:selected').attr('data-index'), 10) || 0;
var minDiff = 5; // 2h30m = 5 half-hours
var ct = 0;
var imprimidos = 0;
var hrStr;
var minStr;
for (let hr = start; hr <= end; hr++) {
for (let min = 0; min < 60; min += 30) {
if (hr === end && min > 0) break;
hrStr = hr.toString().padStart(2, "0") + ":";
minStr = min === 0 ? "00" : "30";
var val = hrStr + minStr;
var optionIndex = ct;
if (origem.includes("manha") && destino.includes("tarde")) {
if (optionIndex > index) {
if (hr === 24) val = "23:59";
$('#'+destino).append(''+val+' ');
imprimidos++;
}
} else {
if (optionIndex >= index + minDiff) {
if (hr === 24) val = "23:59";
$('#'+destino).append(''+val+' ');
imprimidos++;
}
}
ct++;
}
}
// Special case for 24:00
if ((destino == 'nc_entrega_manha_fim'+extraName || destino == 'nc_entrega_tarde_fim'+extraName) && hrStr == '24:' && index && imprimidos == 0) {
$('#'+destino).append('23:59 ');
imprimidos++;
}
if (imprimidos>0) {
$('#'+destino).attr("disabled", false);
}
if (imprimidos>0 && destino.includes("fim") && $('#'+origem).val()) {
$('#'+destino).attr("required", true);
} else {
$('#'+destino).attr("required", false);
}
/*if (imprimidos>0 && destino.includes("tarde")) {
$('#'+destino).attr("required", true);
} else {
$('#'+destino).attr("required", false);
}*/
}
function getHorariosSeguintes(idSelectInicio, idSelectFim) {
var $selectFim = $('#' + idSelectFim);
var selectedIndex = $('#' + idSelectInicio + ' option:selected').data('index');
$selectFim.val('').trigger('change');
$selectFim.find('option').each(function() {
$(this).prop('disabled', false).prop('hidden', false);
});
$selectFim.find('option').each(function() {
var $option = $(this);
if ($option.val() === "") {
return;
}
var optionIndex = $option.data('index');
if (typeof optionIndex !== 'undefined') {
if (typeof selectedIndex === 'undefined' || optionIndex > selectedIndex) {
} else {
$option.prop('disabled', true).prop('hidden', true);
}
}
});
if ($selectFim.hasClass("select2-hidden-accessible")) {
$selectFim.select2('destroy');
}
$selectFim.select2({
minimumResultsForSearch: '',
width: '100%',
dropdownParent: $selectFim.parent()
});
}
function formatImageOption(data) {
if (!data.id) { return data.text; }
var $result= $(
' ' + data.text + ' '
);
return $result;
};
function formatImageOptionSelected(data) {
if (!data.id) { return data.text; }
var $result= $(
' '
);
return $result;
};
function formatIconOption(data) {
if (!data.id) { return data.text; }
var $result= $(
' ' + data.text + ' '
);
return $result;
};
$(document).ready(function() {
$(".noinput").keypress(function (e) { return false; });
$(".noinput").keydown(function(e) { return false; });
$(".onlyNumbers").keypress(function (e) {
if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});
$("select[data-use-select2]").each(function() {
$(this).select2({
minimumResultsForSearch: '',
width: '100%',
dropdownParent: $(this).parent()
});
});
$("select[data-use-select2-clear]").each(function() {
$(this).select2({
allowClear: true,
minimumResultsForSearch: '',
width: '100%',
dropdownParent: $(this).parent()
});
$(this).on('change', function (e) {
// Check if the value is cleared (empty)
if ($(this).val() === '' || $(this).val() === null) {
console.log('Clear button clicked or value reset for select:', $(this).attr('id'));
// if element name contains the word 'fim'
if ($(this).attr('id').includes('entrega_tarde_fim')) {
// the name of the element im testing is "nc_entrega_tarde_fim3", i need to get the nc_entrega_tarde_inicio3
var extraName = $(this).attr('id').replace('entrega_tarde_fim', 'entrega_tarde_inicio');
// now i need to get the value of the element with id extraName
var inicioValue = $('#'+extraName).val();
if (inicioValue) {
$(this).attr("required", true);
} else {
$(this).attr("required", false);
}
} else if ($(this).attr('id').includes('entrega_tarde_inicio')) {
var extraName = $(this).attr('id').replace('entrega_tarde_inicio', 'entrega_tarde_fim');
$('#'+extraName).attr("required", false);
}
}
});
});
$("select[data-use-select2-multiple]").each(function() {
$(this).select2({
minimumResultsForSearch: '',
width: '100%',
closeOnSelect: false,
dropdownParent: $(this).parent()
});
});
$("select[data-use-select2-flag]").each(function() {
$(this).select2({
minimumResultsForSearch: '',
dropdownParent: $(this).parent(),
templateResult: formatImageOption,
templateSelection: formatImageOptionSelected
});
});
$("select[data-use-select2-icon]").each(function() {
$(this).select2({
minimumResultsForSearch: '',
width: '100%',
dropdownParent: $(this).parent(),
templateResult: formatIconOption,
templateSelection: formatIconOption
});
});
$('.select2').on('click', function() {
let selectField = $(this).parent().find('.select2-search__field');
selectField.each(function(index, element) {
if (element.tagName === 'INPUT') {
element.focus();
}
});
});
$('#nc_entrega_codigo_postal').keyup(delay(function (event) {
if (event.shiftKey) return false;
checkCodigoPostal();
}, 500));
});
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}
var produtoDetalhesModal;
var temPadraoCarregado = false;
var temArmazensCarregado = false;
var temHistoricoCarregado = false;
var temStockCarregado = false;
function openProduto(id,bloqueados = 0, title = '', idCliente = '') {
temPadraoCarregado = false;
$('#divOpcoesPadrao').hide();
temHistoricoCarregado = false;
temArmazensCarregado = false;
temStockCarregado = false;
$("#add_cliente_padrao").show();
$("#del_cliente_padrao, #rever_alteracoes_padrao, #save_padrao, #cancelar_rever_alteracoes_padrao").hide();
$('#modalProdLoading').show();
$('#modalProdContent').html('');
if (title != '') {
$('#motalProdTitle').html(b64_to_utf8(title));
}
produtoDetalhesModal = Fancybox.show([{
src: '#modalProduto',
type: 'inline'
}]);
$.ajax({
type: 'POST',
url: '/paginas/refresh/detalhes-produto.php',
data: '&id='+id+'&idCliente='+idCliente+'&bloqueados='+bloqueados+'&pagina=',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#modalProdLoading').hide();
$('#modalProdContent').html(data);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
function selecionarTodasLinhasCot(tmpIdCot) {
var selLinhaCot = ($("#selLinhaCot"+tmpIdCot).is(":checked")) ? 1 : 0;
if (selLinhaCot == 1) {
$('.selLinhaCot'+tmpIdCot).prop('checked', true).trigger('change');
} else {
$('.selLinhaCot'+tmpIdCot).prop('checked', false).trigger('change');
}
}
var contaChecks=0;
function handleCheckPadroes() {
contaChecks=0;
var ids='';
$('input.checkpadrao:checkbox:checked').each(function(i, obj) {
if (contaChecks>0) ids += ',';
ids += $(this).val();
contaChecks++;
});
if (contaChecks>0) {
$("#del_cliente_padrao").show();
} else {
$("#del_cliente_padrao, #rever_alteracoes_padrao, #save_padrao, #cancelar_rever_alteracoes_padrao").hide();
}
checkTemPadroesPorGravar();
}
function checkTemPadroesPorGravar() {
var camposEditados = false;
$('input.inputNovoVarNet').each(function(i, obj) {
var tmdId = $(this).attr('data-tmpid');
if ($(this).val() == 'cotacao') {
if (parseFloat($('#valorNovo_'+tmdId).val()) > 0) { camposEditados = true; }
} else {
if (parseFloat($(this).val()) != 0 && $(this).val()!='' && parseFloat($('#valorNovo_'+tmdId).val()) > 0 && $('#dataVigor_'+tmdId).val() != '') { camposEditados = true; }
}
});
if (camposEditados) {
$("#rever_alteracoes_padrao").show();
$("#save_padrao, #cancelar_rever_alteracoes_padrao").hide();
} else {
$("#rever_alteracoes_padrao, #save_padrao, #cancelar_rever_alteracoes_padrao").hide();
}
}
var contaChecks=0;
function handleCheckCotacoes(tmpIdCliente) {
contaChecks=0;
var ids='';
$('input.checkpadrao'+tmpIdCliente+':checkbox').not(':checked').each(function(i, obj) {
var tmdId = $(this).attr('data-tmpid');
$('#valorNovo_'+tmdId).val('');
$('#campoMotivo'+tmdId).val('-');
$('#valorNovo_'+tmdId+', #varNet_'+tmdId).attr("disabled", true);
$('#varNet_'+tmdId).val('');
});
$('input.checkpadrao'+tmpIdCliente+':checkbox:checked').each(function(i, obj) {
if (contaChecks>0) ids += ',';
ids += $(this).val();
var valor = $(this).attr('data-valor');
var tmdId = $(this).attr('data-tmpid');
if ($('#valorNovo_'+tmdId).val() == '') {
$('#valorNovo_'+tmdId).val(valor);
}
$('#valorNovo_'+tmdId+', #varNet_'+tmdId).attr("disabled", false);
if ($('#varNet_'+tmdId).val() == '') { $('#varNet_'+tmdId).val('0.00'); }
contaChecks++;
});
if (contaChecks>0) {
$('#accoesPreco'+tmpIdCliente).show();
} else {
$('#accoesPreco'+tmpIdCliente).hide();
}
checkTemCotacoesPorGravar(tmpIdCliente);
}
function aplicarPrecoCotacoes(tmpIdCliente, tipo) {
$('input.checkpadrao'+tmpIdCliente+':checkbox:checked').each(function(i, obj) {
var tmdId = $(this).attr('data-tmpid');
var preco = $('#preco'+tipo+tmdId).val();
$('#valorNovo_'+tmdId).val(preco).trigger("change");
});
}
function checkTemCotacoesPorGravar(tmpId) {
var camposEditados = false;
$('input.inputNovoVarNet'+tmpId+':not(:disabled)').each(function(i, obj) {
var tmdId = $(this).attr('data-tmpid');
if (parseFloat($(this).val()) != 0 || parseFloat($('#valorNovo_'+tmdId).val()) > 0) { camposEditados = true; }
});
if (camposEditados) {
$("#save_padrao"+tmpId+", #save_proposta"+tmpId).removeClass('disabled');
} else {
$("#save_padrao"+tmpId+", #save_proposta"+tmpId).addClass('disabled');
}
}
function reverAlteracoesPadrao() {
$("#rever_alteracoes_padrao, #add_cliente_padrao, #del_cliente_padrao").hide();
$("#save_padrao, #cancelar_rever_alteracoes_padrao").show();
$('.linhas_padrao').hide();
$('input.inputNovoVarNet:not(:disabled)').each(function(i, obj) {
var tmdId = $(this).attr('data-tmpid');
if ($(this).val() == 'cotacao') {
if (parseFloat($('#valorNovo_'+tmdId).val()) > 0) {
$('#tr_'+tmdId).show();
$('#tr_'+tmdId+' input').attr("readonly", true);
$('#tr_'+tmdId+' input:checkbox').attr("disabled", true);
}
} else {
if (parseFloat($(this).val()) != 0) {
$('#tr_'+tmdId).show();
$('#tr_'+tmdId+' input').attr("readonly", true);
$('#tr_'+tmdId+' input:checkbox').attr("disabled", true);
}
}
});
}
function cancelarReverAlteracoesPadrao() {
$("#rever_alteracoes_padrao, #add_cliente_padrao").show();
$("#save_padrao, #cancelar_rever_alteracoes_padrao").hide();
$('.linhas_padrao').show();
$('input.inputNovoVarNet:not(:disabled)').each(function(i, obj) {
var tmdId = $(this).attr('data-tmpid');
if (parseFloat($(this).val()) != 0) {
$('#tr_'+tmdId+' input').attr("readonly", false);
$('.inputReadonly').attr("readonly", true);
if ($(this).val() != 'novo') {
$('#tr_'+tmdId+' input:checkbox').attr("disabled", false);
}
}
});
handleCheckPadroes();
}
var modalSavePropostaCotacao;
function openModalSavePropostaCotacao(id) {
modalSavePropostaCotacao = new bootstrap.Modal(document.getElementById('modalSavePropostaCotacao'+id), { backdrop: 'static', keyboard: false });
modalSavePropostaCotacao.show();
}
function guardaPropostaCotacao(tmpIdCliente = '', enviarEmail = 0) {
var padroes = '';
$('#save_padrao').addClass("btn-loading");
$('input.inputNovoVarNet'+tmpIdCliente+':not(:disabled)').each(function(i, obj) {
var cliente = $(this).attr('data-cliente');
var tmdId = $(this).attr('data-tmpid');
var preco = $(this).attr('data-atual');
var varNet = $(this).val();
var varValor = $('#valorNovo_'+tmdId).val();
var minimo = $(this).attr('data-minimo');
var varData = $('#dataVigor_'+tmdId).val();
var artigo = $(this).attr('data-artigo');
var cartid = $(this).attr('data-cartid');
var cotid = $(this).attr('data-cotid');
if (parseFloat(varValor) > 0) {
if (padroes != '') { padroes += '|'; }
padroes += cliente+'@'+preco+'@'+varValor+'@'+varData+'@'+artigo+'@'+cartid+'@'+cotid;
}
});
if (padroes != '') {
padroes = btoa(padroes);
var serialize = '';
if (enviarEmail) {
serialize = $('#submeterPropostaCotacao'+tmpIdCliente).serialize()+'&enviarEmail=1';
}
sendingForm('submeterPropostaCotacao'+tmpIdCliente, true);
$.ajax({
type: 'POST',
url: '/paginas/refresh/guardar-proposta-cotacao.php',
data: '&padroes='+padroes+serialize,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if(data=="1"){
toastr.success("Alterações efectuadas com sucesso");
//sendingForm('submeterPropostaCotacao'+tmpIdCliente, false);
//modalSavePropostaCotacao.hide();
setTimeout(function(){
window.location.reload();
}, 250);
} else {
toastr.error("Não foi possivel concluir o seu pedido.");
sendingForm('submeterPropostaCotacao'+tmpIdCliente, false);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
sendingForm('submeterPropostaCotacao'+tmpIdCliente, false);
modalSavePropostaCotacao.hide();
}
});
}
}
var modalSavePadraoCotacao;
function openModalSavePadraoCotacao(id) {
modalSavePadraoCotacao = new bootstrap.Modal(document.getElementById('modalSavePadraoCotacao'+id), { backdrop: 'static', keyboard: false });
modalSavePadraoCotacao.show();
}
function rejeitarPedidosCotacoes(tmpIdCliente) {
var pedidos = '';
$('input.inputNovoVarNet'+tmpIdCliente+':not(:disabled)').each(function(i, obj) {
var cotid = $(this).attr('data-cotid');
if (pedidos != '') { pedidos += '|'; }
pedidos += cotid;
});
if (pedidos != '') {
pedidos = btoa(pedidos);
Swal2.fire({
title: "Rejeitar Pedido(s) de Cotação",
text: 'Tem a certeza que quer rejeitar este(s) pedido(s)?',
icon: "error",
showCancelButton: true,
confirmButtonColor: "#e82646",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
return $.ajax({
url: "/paginas/refresh/rejeitar-pedido-cotacao.php",
data: "&pedidos="+pedidos+"&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=IDd308018b8f28a8405c9d1968f2b6ad8b",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
toastr.warning("Pedido(s) rejeitado(s) com sucesso.");
setTimeout(function(){
window.location.reload();
}, 500);
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
}
}
function guardaAlteracoesPadrao(submit='', campoID = '', tmpIdCliente = '', isCotacao = 0, enviarEmail = 0) {
var padroes = '';
var pedirMotivo = false;
var artigosAbaixoLimite = [];
if (submit == 'padroes-cliente') {
$('#save_cliente_padrao').addClass("btn-loading");
var artigosJaIncluidos = {};
$('input.inputNovoVarNet'+tmpIdCliente+':not(:disabled)').each(function(i, obj) {
var tmdId = $(this).attr('data-tmpid');
if ($('#valorNovo_'+tmdId).hasClass('bg-secondary')) {
var cliente = $(this).attr('data-cliente');
var preco = $(this).attr('data-atual');
var varNet = $(this).val();
var varValor = $('#valorNovo_'+tmdId).val();
var minimo = $('#valorNovo_'+tmdId).attr('data-minimo');
var varData = $('#dataVigor_'+tmdId).val();
var artigo = $(this).attr('data-artigo');
var design = $(this).attr('data-design') || artigo;
var cartid = $(this).attr('data-cartid');
var cotid = $(this).attr('data-cotid');
if (parseFloat(varValor) > 0) {
if (padroes != '') { padroes += '|'; }
padroes += cliente+'@'+preco+'@'+varValor+'@'+varData+'@'+artigo+'@'+cartid+'@'+cotid;
artigosJaIncluidos[tmdId] = true;
if (parseFloat(varValor) < parseFloat(minimo)) {
pedirMotivo = true;
artigosAbaixoLimite.push({artigo: artigo, design: design, novoPreco: varValor});
}
}
}
});
// Include off-DOM changes from precosAlterados
if (typeof precosAlterados !== 'undefined') {
for (var tmdId in precosAlterados) {
if (!artigosJaIncluidos[tmdId]) {
var dados = precosAlterados[tmdId];
if (parseFloat(dados.novoPreco) > 0) {
if (padroes != '') { padroes += '|'; }
padroes += dados.cliente+'@'+dados.precoAtual+'@'+dados.novoPreco+'@'+dados.dataVigor+'@'+dados.artigo+'@'+(dados.cartid||'0')+'@'+(dados.cotid||'0');
if (parseFloat(dados.novoPreco) < parseFloat(dados.minimo)) {
pedirMotivo = true;
artigosAbaixoLimite.push({artigo: dados.artigo, design: dados.design || dados.artigo, novoPreco: dados.novoPreco});
}
}
}
}
}
} else if (campoID == '') {
$('#save_padrao').addClass("btn-loading");
$('input.inputNovoVarNet'+tmpIdCliente+':not(:disabled)').each(function(i, obj) {
var cliente = $(this).attr('data-cliente');
var tmdId = $(this).attr('data-tmpid');
var preco = $(this).attr('data-atual');
var varNet = $(this).val();
var varValor = $('#valorNovo_'+tmdId).val();
var minimo = $(this).attr('data-minimo');
var varData = $('#dataVigor_'+tmdId).val();
var artigo = $(this).attr('data-artigo');
var design = $(this).attr('data-design') || artigo;
var cartid = $(this).attr('data-cartid');
var cotid = $(this).attr('data-cotid');
if (parseFloat(varValor) > 0) {
if (padroes != '') { padroes += '|'; }
padroes += cliente+'@'+preco+'@'+varValor+'@'+varData+'@'+artigo+'@'+cartid+'@'+cotid;
if (parseFloat(varValor) < parseFloat(minimo)) {
pedirMotivo = true;
artigosAbaixoLimite.push({artigo: artigo, design: design, novoPreco: varValor});
}
}
});
} else {
$('#save_padrao'+campoID).addClass("btn-loading");
var cliente = $('#valorNovo_'+campoID).attr('data-cliente');
var preco = $('#valorNovo_'+campoID).attr('data-preco');
var varValor = $('#valorNovo_'+campoID).val();
var minimo = $('#valorNovo_'+campoID).attr('data-minimo');
var artigo = $('#valorNovo_'+campoID).attr('data-artigo');
var design = $('#varNet_'+campoID).attr('data-design') || artigo;
var varData = '08/05/2026';
if ($('#dataVigor_'+campoID).length) {
varData = $('#dataVigor_'+campoID).val();
}
if (varValor>0) {
var cotid = $('#valorNovo_'+campoID).attr('data-cotid');
padroes = cliente+'@'+preco+'@'+varValor+'@'+varData+'@'+artigo+'@0@'+cotid;
if (parseFloat(varValor) < parseFloat(minimo)) {
pedirMotivo = true;
artigosAbaixoLimite.push({artigo: artigo, design: design, novoPreco: varValor});
}
}
}
if (padroes != '') {
padroes = btoa(padroes);
var serialize = '';
if (isCotacao && enviarEmail) {
serialize = $('#submeterPadraoCotacao'+tmpIdCliente).serialize()+'&enviarEmail=1';
}
if (isCotacao) { sendingForm('submeterPadraoCotacao'+tmpIdCliente, true); }
$('#save_padrao'+campoID).removeClass("btn-loading");
if (submit == 'pendentes') { $('.fancybox__container').css('visibility', 'hidden'); }
var htmlSwal = '';
if (pedirMotivo) {
htmlSwal = 'Existe(m) artigo(s) Abaixo do Limite Coordenador! ';
htmlSwal += '';
for (var i = 0; i < artigosAbaixoLimite.length; i++) {
var art = artigosAbaixoLimite[i];
htmlSwal += '
';
htmlSwal += '
';
htmlSwal += '' + art.artigo + ' - ' + art.design + ' ';
htmlSwal += '' + parseFloat(art.novoPreco).toFixed(3) + ' € ';
htmlSwal += '
';
htmlSwal += '
';
htmlSwal += '';
htmlSwal += ' ';
htmlSwal += '
';
htmlSwal += '
';
}
htmlSwal += '
';
} else {
htmlSwal = 'Confirma a gravação das alterações?';
}
Swal2.fire({
title: pedirMotivo ? "Limite Coordenador" : "Confirmar",
html: htmlSwal,
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#13bfa6",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
width: pedirMotivo ? '600px' : 'auto',
didOpen: function() {
if (pedirMotivo) {
$('.btn-replicar-motivo').on('click', function() {
var idx = $(this).attr('data-idx');
var motivo = $('.swall_motivo_artigo[data-idx="'+idx+'"]').val();
if (motivo != '') {
$('.swall_motivo_artigo').each(function() {
if ($(this).val() == '') { $(this).val(motivo); }
});
}
});
}
},
preConfirm: function() {
if (pedirMotivo) {
var todosPreenchidos = true;
var observacoesObj = {};
$('.swall_motivo_artigo').each(function() {
$(this).removeClass("is-invalid");
if ($(this).val() == '') {
$(this).addClass("is-invalid");
todosPreenchidos = false;
} else {
var idx = $(this).attr('data-idx');
observacoesObj[artigosAbaixoLimite[idx].artigo] = $(this).val();
}
});
if (!todosPreenchidos) { return false; }
// Base64 para evitar problemas de URL-encoding/escaping
return btoa(unescape(encodeURIComponent(JSON.stringify(observacoesObj))));
}
return '';
}
}).then(function(result) {
if (result.isConfirmed) {
var observacoes = result.value;
ajaxSubmitAlteracoesPadrao(padroes, serialize, submit, campoID, isCotacao, tmpIdCliente, observacoes);
if (submit == 'pendentes') { $('.fancybox__container').css('visibility', 'visible'); }
} else {
$('#save_cliente_padrao').removeClass("btn-loading");
$('#save_padrao'+campoID).removeClass("btn-loading");
if (submit == 'pendentes') { $('.fancybox__container').css('visibility', 'visible'); }
}
});
}
}
function ajaxSubmitAlteracoesPadraoComplete(result, submit, campoID, isCotacao, tmpIdCliente) {
if (result == "-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if (result == "1") {
toastr.success("Alterações efectuadas com sucesso");
if (submit == 'padroes-cliente') {
filtrarListaPadroes(true,true,0);
} else if (submit == 'pendentes') {
$('.art'+campoID).remove();
var tmpArtigoId = $('#artigoTmpID').val();
var numPadroes = parseInt($('#numPadroes'+tmpArtigoId).html())-1;
$('#numPadroes'+tmpArtigoId).html(numPadroes);
if (numPadroes == 0) { $('.art'+tmpArtigoId).remove(); }
} else if (submit == 'gerir-padrao') {
$('#save_padrao'+campoID).removeClass("btn-loading");
$('#botao_save_padrao'+campoID).removeClass('col-12').addClass('col-6');
$('#botao_apagar_padrao'+campoID).show();
$('#apagar_padrao'+campoID).show();
$('#valorNovo_'+campoID).removeClass('bg-secondary');
if (checkTemAlterados()) {
$('#save_cliente_padrao').show();
} else {
$('#save_cliente_padrao').hide();
}
} else if (submit == '-submit') {
setTimeout(function(){ window.location.reload(); }, 250);
} else {
Fancybox.close();
}
} else {
toastr.error("Não foi possivel concluir o seu pedido.");
}
if (isCotacao) {
sendingForm('submeterPadraoCotacao'+tmpIdCliente, false);
modalSavePadraoCotacao.hide();
} else {
$('#save_padrao, #save_cliente_padrao').removeClass("btn-loading");
$('#save_padrao'+campoID).removeClass("btn-loading");
}
}
function ajaxSubmitAlteracoesPadrao(padroes, serialize, submit, campoID, isCotacao, tmpIdCliente, observacoes = '') {
var freepass = 0;
if ($('#campoMargemObjetivo').length) {
var margemObjetivo = parseFloat($('#campoMargemObjetivo').html());
var margemPrevistaGrupo = parseFloat($('#campoGrupoMargemPrevista').html());
if (margemObjetivo > 0 && margemPrevistaGrupo > margemObjetivo) {
freepass = 1;
}
}
// Contar artigos para decidir se usa progresso
var totalArtigos = atob(padroes).split('|').length;
var progressId = '';
var pollInterval = null;
if (totalArtigos > 1) {
progressId = '_' + Date.now() + '_' + Math.random().toString(36).substr(2, 6);
// Mostrar SweetAlert com barra de progresso imediatamente
Swal2.fire({
title: 'A gravar...',
html: '0 de ' + totalArtigos + ' artigos gravados
' +
'',
icon: null,
allowOutsideClick: false,
allowEscapeKey: false,
showConfirmButton: false,
showCancelButton: false
});
// Iniciar polling imediatamente
pollInterval = setInterval(function() {
$.ajax({
type: 'GET',
url: '/paginas/refresh/guardar-padrao-progress.php?id=' + progressId,
dataType: 'json',
cache: false,
success: function(progress) {
if (progress && progress.total > 0) {
var pct = Math.round((progress.current / progress.total) * 100);
$('#swal_progress_bar').css('width', pct + '%');
$('#swal_progress_text').html(progress.current + ' de ' + progress.total + ' artigos gravados');
if (progress.done) {
clearInterval(pollInterval);
$('#swal_progress_bar').css('width', '100%').removeClass('progress-bar-animated');
setTimeout(function() {
Swal2.close();
ajaxSubmitAlteracoesPadraoComplete(progress.result, submit, campoID, isCotacao, tmpIdCliente);
}, 500);
}
}
}
});
}, 1000);
}
$.ajax({
type: 'POST',
url: '/paginas/refresh/guardar-padrao-submit.php',
data: '&submit='+submit+'&observacoes='+encodeURIComponent(observacoes)+'&padroes='+padroes+serialize+'&freepass='+freepass+'&progressId='+progressId,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
// Se não usa progresso (1 artigo), processar resposta direta
if (!progressId) {
ajaxSubmitAlteracoesPadraoComplete(data, submit, campoID, isCotacao, tmpIdCliente);
}
// Se usa progresso, o polling já está a correr — nada a fazer aqui
},
error: function(data) {
if (pollInterval) { clearInterval(pollInterval); }
Swal2.close();
toastr.error("Não foi possivel concluir o seu pedido.");
if (isCotacao) {
sendingForm('submeterPadraoCotacao'+tmpIdCliente, false);
modalSavePadraoCotacao.hide();
} else {
$('#save_padrao, #save_cliente_padrao').removeClass("btn-loading");
$('#save_padrao'+campoID).removeClass("btn-loading");
}
}
});
}
function apagarClientePadrao(submit='', campoID = '') {
var padroes = '';
var titulo = '';
var texto = '';
var dataVars = '';
if (submit == 'padroes-cliente') {
titulo = 'Apagar Padrões';
texto = 'Tem a certeza que quer apagar estes padrões?';
$('#del_cliente_padrao').addClass("btn-loading");
$('input.checkpadrao:checkbox:checked').each(function(i, obj) {
var id = $(this).attr('data-artigo');
if (padroes != '') { padroes += '|'; }
padroes += id;
});
var cliente = $('#pc_idCliente').val();
if (padroes != '') {
padroes = btoa(padroes);
}
dataVars = '&padroes='+padroes+'&cliente='+cliente;
} else if (campoID == '') {
titulo = 'Apagar Padrões';
texto = 'Tem a certeza que quer apagar estes padrões?';
$('#del_cliente_padrao').addClass("btn-loading");
$('input.checkpadrao:checkbox:checked').each(function(i, obj) {
var id = $(this).attr('data-cliente');
if (padroes != '') { padroes += '|'; }
padroes += id;
});
var artigo = $('#artigoDetalhes').val();
if (padroes != '') {
padroes = btoa(padroes);
}
dataVars = '&padroes='+padroes+'&artigo='+artigo;
} else {
titulo = 'Apagar Padrão';
texto = 'Tem a certeza que quer apagar este padrão?';
$('#apagar_padrao'+campoID).addClass("btn-loading");
var id = $('#valorNovo_'+campoID).attr('data-cliente');
padroes = id;
var artigo = $('#valorNovo_'+campoID).attr('data-artigo');
if (padroes != '') {
padroes = btoa(padroes);
}
dataVars = '&padroes='+padroes+'&artigo='+artigo;
}
if (padroes != '') {
Swal2.fire({
title: titulo,
html: texto,
icon: "error",
showCancelButton: true,
confirmButtonColor: "#e82646",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
return $.ajax({
type: 'POST',
url: '/paginas/refresh/apagar-padrao.php',
data: dataVars,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
}
});
}
}).then(function(result) {
if (result.isConfirmed) {
var data = result.value;
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if (data == "1") {
if (submit == 'padroes-cliente') {
toastr.success("Padrões apagados com sucesso.");
filtrarListaPadroes(true,true,0);
} else if (campoID == '') {
toastr.success("Padrões apagados com sucesso.");
Fancybox.close();
} else {
toastr.success("Padrão apagado com sucesso.");
$('.art'+campoID).remove();
var tmpArtigoId = $('#artigoTmpID').val();
var numPadroes = parseInt($('#numPadroes'+tmpArtigoId).html())-1;
$('#numPadroes'+tmpArtigoId).html(numPadroes);
if (numPadroes == 0) { $('.art'+tmpArtigoId).remove(); }
}
} else {
toastr.error("Não foi possivel concluir o seu pedido.");
}
$('#del_cliente_padrao, #apagar_padrao'+campoID).removeClass("btn-loading");
} else {
$('#del_cliente_padrao, #apagar_padrao'+campoID).removeClass("btn-loading");
}
});
}
}
var addClienteModal;
function adicionarClientePadrao() {
$('#modalAddClienteLoading').show();
$('#modalAddClienteContent').html('');
addClienteModal = new bootstrap.Modal(document.getElementById('modalAddCliente'), { backdrop: false, keyboard: false });
addClienteModal.show();
var artigo = $('#artigoDetalhes').val();
$.ajax({
type: 'POST',
url: '/paginas/refresh/add-cliente-list.php',
data: '&artigo='+artigo,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#modalAddClienteLoading').hide();
$('#modalAddClienteContent').html(data);
$('#btnSubmitAddCliente').show();
$("select[data-use-select2]").each(function() {
$(this).select2({
minimumResultsForSearch: '',
width: '100%',
dropdownParent: $(this).parent()
});
});
$('.select2').on('click', () => {
let selectField = document.querySelectorAll('.select2-search__field')
selectField.forEach((element, index) => {
element.focus();
})
});
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
$("#formAddClientePadrao").submit(function(event) {
event.preventDefault();
var clienteSel = $('#novo_cliente_select option:selected');
var tmpid = clienteSel.attr('data-tmpid');
var cliente = clienteSel.attr('data-cliente');
var nif = clienteSel.attr('data-nif');
var nome = clienteSel.attr('data-nome');
var abreviatura = clienteSel.attr('data-abreviatura');
var artigo = clienteSel.attr('data-artigo');
var valorPonderado = clienteSel.attr('data-ponderado');
var valorMinimo = parseFloat(clienteSel.attr('data-minimo')).toFixed(3);
var precoTr = parseFloat($('#artigoPrecoTr').val());
var valorMaximo = precoTr*2;
valorMaximo = precoTr.toFixed(3);
$("tbody#listaPadroes").append('
0,000€ Ant: 0,000€ ');
addClienteModal.hide();
$('#scrollPadraoList').scrollTop($('#scrollPadraoList')[0].scrollHeight);
handleCheckPadroes();
});
function calculaPreco(tmdId,price,min,max,ponderado,check=true,minimoAprovacao=0,cotacao='',checkout=false,campo='',isEscoar=false) {
ponderado = (ponderado || '').toString().replace(/[^A-Za-z0-9+/=]/g, '');
var tmpCampo = (campo != '') ? campo : 'varNet';
var percentage = parseFloat($('#'+tmpCampo+'_'+tmdId).val());
if (campo == 'varNet') {
var calcPrice = parseFloat(price) / (1 - (percentage / 100)),
newPrice = calcPrice.toFixed(3);
var custoManual = $('#valorNovo_'+tmdId).attr('data-cm');
var calcPercCM = ((parseFloat(newPrice) - parseFloat(custoManual)) / parseFloat(newPrice)) * 100,
newPercCM = calcPercCM.toFixed(2);
$('#varCM_'+tmdId).html(newPercCM);
} else {
var calcPrice = parseFloat(price) + ((parseFloat(price) / 100) * percentage),
newPrice = calcPrice.toFixed(3);
}
/*if (newPrice > parseFloat(max)) {
$('#valorNovo_'+tmdId).val(max);
newPrice = parseFloat(max);
calculaPerc(tmdId,price,min,max);
}*/
if (!isEscoar || newPrice == 0) {
if (newPrice < parseFloat(min) && newPrice >= parseFloat(base64ToUtf8(ponderado))) {
} else if (newPrice < parseFloat(base64ToUtf8(ponderado)) && min >= parseFloat(base64ToUtf8(ponderado))) {
$('#valorNovo_'+tmdId).val(min);
newPrice = parseFloat(min);
calculaPerc(tmdId,price,min,max);
}
}
if (checkout) {
$('#valorNovo_'+tmdId).val(newPrice).trigger('change');
}else{
$('#valorNovo_'+tmdId).val(newPrice);
}
if (campo == 'varTT') {
var priceNet = $('#valorNovo_'+tmdId).attr('data-preco');
var calcPercNet = ((parseFloat(newPrice) - parseFloat(price)) / parseFloat(newPrice)) * 100,
newPercNet = calcPercNet.toFixed(2);
$('#varNet_'+tmdId).val(newPercNet);
var custoManual = $('#valorNovo_'+tmdId).attr('data-cm');
var calcPercCM = ((parseFloat(newPrice) - parseFloat(custoManual)) / parseFloat(newPrice)) * 100,
newPercCM = calcPercCM.toFixed(2);
$('#varCM_'+tmdId).html(newPercCM);
}
var precoAtual = parseFloat($('#valorNovo_'+tmdId).attr('data-precoatual'));
var bloqueadoNovo = $("#valorNovo_"+tmdId).attr('data-bloqueado');
if (precoAtual > 0 && (precoAtual != newPrice || bloqueadoNovo == 1)) {
$('#valorNovo_'+tmdId).removeClass('bg-warning').addClass('bg-secondary');
$('#save_cliente_padrao').show();
} else if (precoAtual == newPrice) {
$('#valorNovo_'+tmdId).removeClass('bg-secondary');
if (checkTemAlterados()) {
$('#save_cliente_padrao').show();
} else {
$('#save_cliente_padrao').hide();
}
}
if (check) {
checkTemPadroesPorGravar();
}
if (minimoAprovacao>0) {
var bloqueado = $("#valorPadrao_"+tmdId).attr('data-bloqueado');
var padrao = ($("#valorPadrao_"+tmdId).is(":checked")) ? 1 : 0;
if (padrao == 0 && bloqueado == 0) {
$('#btnAprovacao_'+tmdId).removeClass('disabled');
$('#btnEscalar_'+tmdId).addClass('disabled');
} else {
if (newPrice>=parseFloat(minimoAprovacao)) {
$('#btnAprovacao_'+tmdId).removeClass('disabled');
$('#btnEscalar_'+tmdId).addClass('disabled');
} else {
$('#btnAprovacao_'+tmdId).addClass('disabled');
$('#btnEscalar_'+tmdId).removeClass('disabled');
}
}
}
if (cotacao) {
checkTemCotacoesPorGravar(cotacao);
}
if ($('#campoMotivo'+tmdId).length) {
var cliente = $('#varNet_'+tmdId).attr('data-cliente');
var artigo = $('#varNet_'+tmdId).attr('data-artigo');
getMotivo(tmdId, cliente, artigo, newPrice);
}
calculaMargens(tmdId);
}
function calculaPerc(tmdId,price,min,max,ponderado,check=true,minimoAprovacao=0,cotacao='',checkout=false,campo='',isEscoar=false) {
ponderado = (ponderado || '').toString().replace(/[^A-Za-z0-9+/=]/g, '');
var newPrice = parseFloat($('#valorNovo_'+tmdId).val());
/*if (newPrice > parseFloat(max)) {
$('#valorNovo_'+tmdId).val(max);
newPrice = parseFloat(max);
}*/
if (!isEscoar || newPrice == 0) {
if (newPrice < parseFloat(min) && newPrice >= parseFloat(atob(ponderado))) {
} else if (newPrice < parseFloat(atob(ponderado)) && min >= parseFloat(atob(ponderado))) {
$('#valorNovo_'+tmdId).val(min);
newPrice = parseFloat(min);
}
}
if (campo == 'varNetRaioX') {
var calcPerc = ((parseFloat(newPrice) / parseFloat(price)) - 1) * 100;
newPerc = calcPerc.toFixed(2);
} else if (campo == 'varNet') {
var calcPerc = ((parseFloat(newPrice) - parseFloat(price)) / parseFloat(newPrice)) * 100,
newPerc = calcPerc.toFixed(2);
} else {
var calcPerc = (parseFloat(newPrice) * 100 / parseFloat(price)) - 100,
newPerc = calcPerc.toFixed(2);
}
$('#varNet_'+tmdId).val(newPerc);
if ($('#varTT_'+tmdId).length) {
var priceTT = $('#valorNovo_'+tmdId).attr('data-tt');
var calcPercTT = (parseFloat(newPrice) * 100 / parseFloat(priceTT)) - 100,
newPercTT = calcPercTT.toFixed(2);
$('#varTT_'+tmdId).val(newPercTT);
var custoManual = $('#valorNovo_'+tmdId).attr('data-cm');
var calcPercCM = ((parseFloat(newPrice) - parseFloat(custoManual)) / parseFloat(newPrice)) * 100,
newPercCM = calcPercCM.toFixed(2);
$('#varCM_'+tmdId).html(newPercCM);
}
var precoAtual = parseFloat($('#valorNovo_'+tmdId).attr('data-precoatual'));
var bloqueadoNovo = $("#valorNovo_"+tmdId).attr('data-bloqueado');
if (precoAtual > 0 && (precoAtual != newPrice || bloqueadoNovo == 1)) {
$('#valorNovo_'+tmdId).removeClass('bg-warning').addClass('bg-secondary');
$('#save_cliente_padrao').show();
} else if (precoAtual == newPrice) {
$('#valorNovo_'+tmdId).removeClass('bg-secondary');
if (checkTemAlterados()) {
$('#save_cliente_padrao').show();
} else {
$('#save_cliente_padrao').hide();
}
}
if (check) {
checkTemPadroesPorGravar();
}
if (minimoAprovacao>0) {
var bloqueado = $("#valorPadrao_"+tmdId).attr('data-bloqueado');
var padrao = ($("#valorPadrao_"+tmdId).is(":checked")) ? 1 : 0;
if (padrao == 0 && bloqueado == 0) {
$('#btnAprovacao_'+tmdId).removeClass('disabled');
$('#btnEscalar_'+tmdId).addClass('disabled');
} else {
if (newPrice>=parseFloat(minimoAprovacao)) {
$('#btnAprovacao_'+tmdId).removeClass('disabled');
$('#btnEscalar_'+tmdId).addClass('disabled');
} else {
$('#btnAprovacao_'+tmdId).addClass('disabled');
$('#btnEscalar_'+tmdId).removeClass('disabled');
}
}
}
if (cotacao) {
checkTemCotacoesPorGravar(cotacao);
}
if ($('#campoMotivo'+tmdId).length) {
var cliente = $('#varNet_'+tmdId).attr('data-cliente');
var artigo = $('#varNet_'+tmdId).attr('data-artigo');
getMotivo(tmdId, cliente, artigo, newPrice);
}
calculaMargens(tmdId);
}
function checkTemAlterados() {
var temAlterados = false;
$('#linhasGerirPadrao tr').each(function() {
if ($(this).find('.inputNovoPreco').hasClass('bg-secondary')) {
temAlterados = true;
}
});
return temAlterados;
}
function triggerChange(id) {
$('#'+id).trigger('change');
}
function calculaMargens(tmpId) {
var preco = parseFloat($('#valorNovo_'+tmpId).val());
if ($('#cm_'+tmpId).length && $('#mpvcm_'+tmpId).length) {
var cm = parseFloat($('#cm_'+tmpId).html().replace('€','').replace(',','.'));
var margem = (preco-cm)/preco*100;
$('#mpvcm_'+tmpId).html(mostraMoeda(margem,'%',2));
if ($('#input_mpvcm_'+tmpId).length) {
$('#input_mpvcm_'+tmpId).val(margem.toFixed(2));
}
}
if ($('#cp_'+tmpId).length && $('#mpvcp_'+tmpId).length) {
var cp = parseFloat($('#cp_'+tmpId).html().replace('€','').replace(',','.'));
var margem = (preco-cp)/preco*100;
$('#mpvcp_'+tmpId).html(mostraMoeda(margem,'%',2));
if ($('#input_mpvcp_'+tmpId).length) {
$('#input_mpvcp_'+tmpId).val(margem.toFixed(2));
}
}
if ($('#margemlibertada_'+tmpId).length ) {
var custoManual = parseFloat($('#valorNovo_'+tmpId).attr('data-cm'));
var margemlibertada = ((preco - custoManual) / preco)*100;
$('#margemlibertada_'+tmpId).html(mostraMoeda(margemlibertada,'%'));
}
}
function manipulaMargem(campo,tmpId,price,min,max,ponderado) {
var margem = parseFloat($('#'+campo+'_'+tmpId).val());
if (campo == 'input_mpvcm') {
var cm = parseFloat($('#cm_' + tmpId).html().replace('€', '').replace(',', '.'));
var preco = (cm / (1 - (margem / 100))).toFixed(3);
$('#valorNovo_' + tmpId).val(preco).trigger('change');
} else if (campo == 'input_mpvcp') {
var cp = parseFloat($('#cp_' + tmpId).html().replace('€', '').replace(',', '.'));
var preco = (cp / (1 - (margem / 100))).toFixed(3);
$('#valorNovo_' + tmpId).val(preco).trigger('change');
}
calculaPerc(tmpId,price,min,max,ponderado,false,0);
}
function selMargensBtn(el,input) {
$('.selMargensBtn').html($(el).html());
$('.inputsOpcoes').hide();
$('.inputsOpcoes_'+input).show();
}
function checkPrecoNovoCliente(tmdId,min,max,ponderado,check=true) {
var newPrice = parseFloat($('#valorNovo_'+tmdId).val());
/*if (newPrice > parseFloat(max)) {
$('#valorNovo_'+tmdId).val(max);
newPrice = parseFloat(max);
}*/
if (newPrice < parseFloat(min) && newPrice >= parseFloat(atob(ponderado))) {
} else if (newPrice < parseFloat(min)) {
$('#valorNovo_'+tmdId).val(min);
newPrice = parseFloat(min);
}
if (check) {
checkTemPadroesPorGravar();
}
if ($('#campoMotivo'+tmdId).length) {
var cliente = $('#varNet_'+tmdId).attr('data-cliente');
var artigo = $('#varNet_'+tmdId).attr('data-artigo');
getMotivo(tmdId, cliente, artigo, newPrice);
}
}
function getMotivo(tmpId, cliente, artigo, preco) {
if (artigo && preco) {
$.ajax({
type: 'POST',
url: '/paginas/refresh/get-motivo.php',
data: '&cliente='+cliente+'&artigo='+artigo+'&preco='+preco+'&ispadraoaprovar=0',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
$('#campoMotivo'+tmpId).html(data);
},
error: function(data) { toastr.error("Não foi possivel concluir o seu pedido."); }
});
} else {
$('#campoMotivo'+tmpId).html('-');
}
}
function handleTabPadroes(id,artigo,tr = 0,tt = 0,bloqueados = 0, idCliente = 0) {
if (id == 'padroes') {
if (!temPadraoCarregado) {
$.ajax({
type: 'POST',
url: '/paginas/refresh/detalhes-produto.php',
data: '&id='+artigo+'&preco_tr='+tr+'&preco_tt='+tt+'&bloqueados='+bloqueados+'&type=padrao',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
temPadraoCarregado = true;
$('#tab-padrao').html(data);
$('.precoDatePicker').datepicker({
showOtherMonths: true,
selectOtherMonths: true,
dateFormat: 'dd/mm/yy',
minDate: '08/05/2026',
beforeShow: function (textbox, instance) {
var txtBoxOffset = $(this).offset();
var top = txtBoxOffset.top - $(window).scrollTop();
setTimeout(function () { instance.dpDiv.css({ top: top+45 }); }, 0);
}
});
loadToolTips();
$('#divOpcoesPadrao').show();
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
} else {
$('#divOpcoesPadrao').show();
$("#add_cliente_padrao").show();
$("#rever_alteracoes_padrao, #save_padrao, #cancelar_rever_alteracoes_padrao").hide();
}
} else if (id == 'armazens') {
if (!temArmazensCarregado) {
$.ajax({
type: 'POST',
url: '/paginas/refresh/detalhes-produto.php',
data: '&id='+artigo+'&type=armazens',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
temArmazensCarregado = true;
$('#tab-armazens').html(data);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
} else {
$("#add_cliente_padrao").show();
$("#rever_alteracoes_padrao, #save_padrao, #cancelar_rever_alteracoes_padrao").hide();
}
} else if (id == 'historico') {
if (!temHistoricoCarregado) {
$.ajax({
type: 'POST',
url: '/paginas/refresh/detalhes-produto.php',
data: '&id='+artigo+'&idCliente='+idCliente+'&type=historico',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
temHistoricoCarregado = true;
$('#tab-historico').html(data);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
} else {
$("#add_cliente_padrao").show();
$("#rever_alteracoes_padrao, #save_padrao, #cancelar_rever_alteracoes_padrao").hide();
}
} else if (id == 'stock') {
if (!temStockCarregado) {
$.ajax({
type: 'POST',
url: '/paginas/refresh/detalhes-produto.php',
data: '&id='+artigo+'&type=stock',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
temStockCarregado = true;
$('#tab-stock').html(data);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
} else {
$("#add_cliente_padrao").show();
$("#rever_alteracoes_padrao, #save_padrao, #cancelar_rever_alteracoes_padrao").hide();
}
} else {
$('#divOpcoesPadrao').hide();
}
}
function removePadrao(produto){
if(produto>=1){
setTimeout(function(){
$.ajax({
url: "/paginas/refresh/remover-cart-padrao.php",
data: "&produto="+produto+"&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID123897d18276f6b8d8bb38f3de2afb1a",
type: "POST",
success:function(result){
if(result==1){
window.location.reload();
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
return false;
}, 100);
};
};
function loadPadroes() {
$('#padroesContent').html('');
$.ajax({
type: 'POST',
url: '/paginas/produtos/aprovacoes_load.php',
data: '&a=1',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#padroesContent').html(data);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
function filtrarPadroesAprovacao() {
limparSelLinhasEnc();
var filtros = '*';
var escaladas = $('#filtro_escaladas').val();
if (escaladas!=0) {
$('.linhaAprovacaoArtigo').hide();
filtros += '[data-escaladas="1"]';
} else {
$('.linhaAprovacaoArtigo').show();
}
var vendedor = $('#filtro_vendedor').val();
if (vendedor!=0) {
filtros += '[data-vendedor="'+vendedor+'"]';
}
var cliente = $('#filtro_cliente').val();
if (cliente!=0) {
filtros += '[data-cliente="'+cliente+'"]';
}
var artigo = $('#filtro_artigo').val();
if (artigo!=0) {
$('.linhaAprovacaoArtigo').hide();
filtros += '[data-artigo*="'+artigo+'"]';
}
var motivo = $('#filtro_motivo').val();
if (motivo!=0) {
$('.linhaAprovacaoArtigo').hide();
filtros += '[data-motivo*="'+motivo+'"]';
}
if (filtros != '*') {
$('.linhaAprovacaoCliente').hide();
$(filtros).show();
} else {
$('.linhaAprovacaoCliente').show();
}
if ($('.linhaAprovacaoCliente:visible').length == 0) {
$('.semResultados').show();
} else {
$('.semResultados').hide();
}
}
function rejeitarPadrao(id,cliente){
if(id){
var preco = $('#valorNovo_'+id).val();
var datavigor = $('#dataVigor_'+id).val();
var vendedor = $('#valorNovo_'+id).attr('data-vendedor');
var detalhes = id+'@'+preco+'@'+datavigor;
detalhes = btoa(detalhes);
Swal2.fire({
title: "Rejeitar Padrão",
html: 'Tem a certeza que quer rejeitar este padrão? ',
icon: "error",
showCancelButton: true,
confirmButtonColor: "#e82646",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
$('#swall_motivo_nao_aprovado').removeClass("is-invalid");
var motivo = document.getElementById('swall_motivo_nao_aprovado').value;
if (motivo == '') { $('#swall_motivo_nao_aprovado').addClass("is-invalid"); return false; }
var artigoPC = $('#ppIdArtigo').val() || '';
var filtroPC = $('#filtarPP_raiox').val() || '';
return $.ajax({
url: "/paginas/refresh/handle-padrao.php",
data: "&detalhes="+detalhes+'&motivo='+motivo+'&id_vendedor='+vendedor+"&status=Rejeitado&id_artigo_pc="+encodeURIComponent(artigoPC)+"&filtro_pc="+encodeURIComponent(filtroPC)+"&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=IDa7f2d82fe2b771e7a24508f7db274f32",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
$('#trLinha'+id).remove();
if ($('*[data-cardcliente="'+cliente+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardcliente="'+cliente+'"]').remove();
}
decrementarContadorGerirPrecos();
limparSelLinhasEnc();
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
};
function decrementarContadorGerirPrecos() {
var idArtigo = $('#ppIdArtigo').val();
var filtroAtual = $('#filtarPP_raiox').val();
if (!idArtigo || !filtroAtual) { return; }
var $btn = $('.btnGerirProduto[data-artigo="'+idArtigo+'"][data-filtro="'+filtroAtual+'"]');
if (!$btn.length) { return; }
var $count = $btn.find('.gerir-count');
var novo = parseInt($count.text()) - 1;
if (isNaN(novo) || novo < 0) { novo = 0; }
$count.text(novo);
if (novo == 0) {
$btn.removeClass('btn-warning').addClass('btn-gray');
}
}
function aprovarPadrao(id,cliente){
if(id){
var preco = $('#valorNovo_'+id).val();
var datavigor = $('#dataVigor_'+id).val();
var vendedor = $('#valorNovo_'+id).attr('data-vendedor');
var detalhes = id+'@'+preco+'@'+datavigor;
detalhes = btoa(detalhes);
Swal2.fire({
title: "Aprovar Padrão",
html: 'Tem a certeza que quer aprovar este padrão?',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#13bfa6",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
var artigoPC = $('#ppIdArtigo').val() || '';
var filtroPC = $('#filtarPP_raiox').val() || '';
return $.ajax({
url: "/paginas/refresh/handle-padrao.php",
data: "&detalhes="+detalhes+'&id_vendedor='+vendedor+"&status=Aprovado&id_artigo_pc="+encodeURIComponent(artigoPC)+"&filtro_pc="+encodeURIComponent(filtroPC)+"&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID75e25450f69d67278082c8e4da28ec25",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
$('#trLinha'+id).remove();
if ($('*[data-cardcliente="'+cliente+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardcliente="'+cliente+'"]').remove();
}
decrementarContadorGerirPrecos();
limparSelLinhasEnc();
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
};
function escalarPadrao(id,cliente){
if(id){
var preco = $('#valorNovo_'+id).val();
var datavigor = $('#dataVigor_'+id).val();
var detalhes = id+'@'+preco+'@'+datavigor;
detalhes = btoa(detalhes);
Swal2.fire({
title: "Escalar Padrão",
html: 'Tem a certeza que quer escalar este padrão? ',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#1170e4",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
$('#swall_observacoes_escalar').removeClass("is-invalid");
var observacoes = document.getElementById('swall_observacoes_escalar').value;
if (observacoes == '') { $('#swall_observacoes_escalar').addClass("is-invalid"); return false; }
return $.ajax({
url: "/paginas/refresh/handle-padrao.php",
data: "&detalhes="+detalhes+'&observacoes='+observacoes+"&status=Escalado&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=IDeba0f0966ac9f357f1553d303ff1df1e",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
loadPadroes();
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
};
function limparLinhasAprovacoesSelecionadas(tipo) {
var ct=0;
var campoVerificacao = '';
if (tipo == 'escalar') {
campoVerificacao = 'btnEscalar_';
} else if (tipo == 'aprovar') {
campoVerificacao = 'btnAprovacao_';
} else {
campoVerificacao = 'btnRejeitar_';
}
$('input.selLinha:checkbox:checked').each(function(i, obj) {
var tmpId = $(this).val();
if (!$('#'+campoVerificacao+tmpId).hasClass('disabled')) {
var cliente = $(this).attr('data-cliente');
$('#trLinha'+tmpId).remove();
if ($('*[data-cardcliente="'+cliente+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardcliente="'+cliente+'"]').remove();
}
}
});
}
function rejeitarLinhaAprovacoes(){
var detalhes = getArrayEncsSelecionadasPost('rejeitar');
if (!detalhes) { toastr.error("Não foram encontradas linhas para Rejeitar"); return false; }
Swal2.fire({
title: "Rejeitar Padrões",
html: 'Tem a certeza que quer rejeitar esta(s) linha(s)? ',
icon: "error",
showCancelButton: true,
confirmButtonColor: "#e82646",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
$('#swall_motivo_nao_aprovado').removeClass("is-invalid");
var motivo = document.getElementById('swall_motivo_nao_aprovado').value;
if (motivo == '') { $('#swall_motivo_nao_aprovado').addClass("is-invalid"); return false; }
return $.ajax({
url: "/paginas/refresh/handle-padrao.php",
data: "&detalhes="+detalhes+'&motivo='+motivo+"&status=Rejeitado&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=IDc66c8a19ea669963d2c7462ff0d0c537",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
limparLinhasAprovacoesSelecionadas('rejeitar');
limparSelLinhasEnc();
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
function aprovarLinhaAprovacoes(){
var detalhes = getArrayEncsSelecionadasPost('aprovar');
if (!detalhes) { toastr.error("Não foram encontradas linhas para Aprovar"); return false; }
Swal2.fire({
title: "Aprovar Padrões",
html: 'Tem a certeza que quer aprovar esta(s) linha(s)?',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#13bfa6",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
return $.ajax({
url: "/paginas/refresh/handle-padrao.php",
data: "&detalhes="+detalhes+"&status=Aprovado&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=IDd8427c4d4e4a86bbdff20dff5b4f0678",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
limparLinhasAprovacoesSelecionadas('aprovar');
limparSelLinhasEnc();
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
function escalarLinhaAprovacoes(){
var detalhes = getArrayEncsSelecionadasPost('escalar');
if (!detalhes) { toastr.error("Não foram encontradas linhas para Escalar"); return false; }
Swal2.fire({
title: "Escalar Padrões",
html: 'Tem a certeza que quer escalar esta(s) linha(s)? ',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#1170e4",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
$('#swall_observacoes_escalar').removeClass("is-invalid");
var observacoes = document.getElementById('swall_observacoes_escalar').value;
if (observacoes == '') { $('#swall_observacoes_escalar').addClass("is-invalid"); return false; }
return $.ajax({
url: "/paginas/refresh/handle-padrao.php",
data: "&detalhes="+detalhes+'&observacoes='+observacoes+"&status=Escalado&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID63ca27e9416a6096eca359ea55312b0d",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
loadPadroes();
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
function rejeitarLinhaEnc(id,encomenda,cliente,ultrapassada = 0){
if(id){
var preco = $('#valorNovo_'+id).val();
var id_linha_encomenda = $('#valorNovo_'+id).attr('data-linha-encomenda');
var vendedor = $('#valorNovo_'+id).attr('data-vendedor');
var padrao = ($("#valorPadrao_"+id).is(":checked")) ? 1 : 0;
var detalhes = id+'@'+preco+'@'+'@'+padrao+'@'+id_linha_encomenda;
detalhes = btoa(detalhes);
var aviso = (ultrapassada == 1) ? ' Corre o risco de a entrega não ser feita nesta data. Entre em contacto com o responsável de rota para garantir que a entrega é feita na data prevista!' : '';
Swal2.fire({
title: "Rejeitar Linha Encomenda",
html: 'Tem a certeza que quer rejeitar esta linha?'+aviso+' ',
icon: "error",
showCancelButton: true,
confirmButtonColor: "#e82646",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
$('#swall_motivo_nao_aprovado').removeClass("is-invalid");
var motivo = document.getElementById('swall_motivo_nao_aprovado').value;
if (motivo == '') { $('#swall_motivo_nao_aprovado').addClass("is-invalid"); return false; }
var artigoPC = $('#ppIdArtigo').val() || '';
var filtroPC = $('#filtarPP_raiox').val() || '';
return $.ajax({
url: "/paginas/refresh/handle-linha-enc.php",
data: "&detalhes="+detalhes+'&motivo='+motivo+'&id_vendedor='+vendedor+"&status=Rejeitado&id_artigo_pc="+encodeURIComponent(artigoPC)+"&filtro_pc="+encodeURIComponent(filtroPC)+"&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=IDea5b8045b0bf7712b61b79f3964db43e",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
limparSelLinhasEnc();
$('#trLinha'+id).remove();
if ($('*[data-cardencomenda="'+encomenda+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardencomenda="'+encomenda+'"]').remove();
}
if ($('*[data-cardcliente="'+cliente+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardcliente="'+cliente+'"]').remove();
}
decrementarContadorGerirPrecos();
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
};
function aprovarLinhaEnc(id,encomenda,cliente,ultrapassada = 0,avisoFaltaStock = 0){
if(id){
if (avisoFaltaStock == 1) {
Swal2.fire({
title: "Aprovar Linha Encomenda",
html: 'Está a aprovar uma falta de stock sem haver stock disponível para satisfazer a encomenda. Deseja continuar?',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#13bfa6",
confirmButtonText: 'OK',
cancelButtonText: 'Cancelar'
}).then(function(result) {
if (result.isConfirmed) {
aprovarLinhaEnc(id, encomenda, cliente, ultrapassada, 0);
}
});
return;
}
var preco = $('#valorNovo_'+id).val();
var id_linha_encomenda = $('#valorNovo_'+id).attr('data-linha-encomenda');
var vendedor = $('#valorNovo_'+id).attr('data-vendedor');
var padrao = ($("#valorPadrao_"+id).is(":checked")) ? 1 : 0;
var detalhes = id+'@'+preco+'@'+'@'+padrao+'@'+id_linha_encomenda;
detalhes = btoa(detalhes);
var aviso = (ultrapassada == 1) ? ' Corre o risco de a entrega não ser feita nesta data. Entre em contacto com o responsável de rota para garantir que a entrega é feita na data prevista!' : '';
Swal2.fire({
title: "Aprovar Linha Encomenda",
html: 'Tem a certeza que quer aprovar esta linha?'+aviso+'',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#13bfa6",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
var artigoPC = $('#ppIdArtigo').val() || '';
var filtroPC = $('#filtarPP_raiox').val() || '';
return $.ajax({
url: "/paginas/refresh/handle-linha-enc.php",
data: "&detalhes="+detalhes+'&id_vendedor='+vendedor+"&status=Aprovado&id_artigo_pc="+encodeURIComponent(artigoPC)+"&filtro_pc="+encodeURIComponent(filtroPC)+"&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID614f637fed7152f3369b6fee1af21382",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
limparSelLinhasEnc();
$('#trLinha'+id).remove();
if ($('*[data-cardencomenda="'+encomenda+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardencomenda="'+encomenda+'"]').remove();
}
if ($('*[data-cardcliente="'+cliente+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardcliente="'+cliente+'"]').remove();
}
decrementarContadorGerirPrecos();
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
};
function escalarLinhaEnc(id,encomenda,cliente){
if(id){
var preco = $('#valorNovo_'+id).val();
var id_linha_encomenda = $('#valorNovo_'+id).attr('data-linha-encomenda');
var padrao = ($("#valorPadrao_"+id).is(":checked")) ? 1 : 0;
var detalhes = id+'@'+preco+'@'+'@'+padrao+'@'+id_linha_encomenda;
detalhes = btoa(detalhes);
Swal2.fire({
title: "Escalar Linha Encomenda",
html: 'Tem a certeza que quer escalar esta linha? ',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#1170e4",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
$('#swall_observacoes_escalar').removeClass("is-invalid");
var observacoes = document.getElementById('swall_observacoes_escalar').value;
if (observacoes == '') { $('#swall_observacoes_escalar').addClass("is-invalid"); return false; }
return $.ajax({
url: "/paginas/refresh/handle-linha-enc.php",
data: "&detalhes="+detalhes+'&observacoes='+observacoes+"&status=Escalado&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID748ab1f959e89daebf4bfd3965f84000",
type: "POST"
}).then(function(ajaxResult) {
return { ajaxResult: ajaxResult, observacoes: observacoes };
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value.ajaxResult==1){
limparSelLinhasEnc();
$('.coluna_motivos'+id).append(' Escalado : '+result.value.observacoes+' ');
$('#btnEscalar_'+id).addClass('disabled');
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
};
function rejeitarLinhaEncForn(id,encomenda,cliente){
if(id){
var qtt = $('#quantity_'+id).val();
var detalhes = id+'@'+qtt;
detalhes = btoa(detalhes);
Swal2.fire({
title: "Rejeitar Linha Encomenda",
html: 'Tem a certeza que quer rejeitar esta linha? ',
icon: "error",
showCancelButton: true,
confirmButtonColor: "#e82646",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
$('#swall_motivo_nao_aprovado').removeClass("is-invalid");
var motivo = document.getElementById('swall_motivo_nao_aprovado').value;
if (motivo == '') { $('#swall_motivo_nao_aprovado').addClass("is-invalid"); return false; }
return $.ajax({
url: "/paginas/refresh/handle-linha-enc-forn.php",
data: "&detalhes="+detalhes+'&motivo='+motivo+"&status=Rejeitado&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=IDf29f582bb9af4d9730d4fbf688fc710b",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
limparSelLinhasEnc();
$('#trLinha'+id).remove();
if ($('*[data-cardencomenda="'+encomenda+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardencomenda="'+encomenda+'"]').remove();
}
if ($('*[data-cardcliente="'+cliente+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardcliente="'+cliente+'"]').remove();
}
decrementarContadorGerirPrecos();
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
};
function aprovarLinhaEncForn(id,encomenda,cliente){
if(id){
var qtt = $('#quantity_'+id).val();
var detalhes = id+'@'+qtt;
detalhes = btoa(detalhes);
Swal2.fire({
title: "Aprovar Linha Encomenda",
html: 'Tem a certeza que quer aprovar esta linha? ',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#13bfa6",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
var motivo = document.getElementById('swall_observacoes_aprovar').value;
/*if (motivo == '') { $('#swall_observacoes_aprovar').addClass("is-invalid"); return false; }*/
return $.ajax({
url: "/paginas/refresh/handle-linha-enc-forn.php",
data: "&detalhes="+detalhes+'&observacoes='+motivo+"&status=Aprovado&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=IDd0564ff2cc3018f3ce44ad0a353dbc3e",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
limparSelLinhasEnc();
$('#trLinha'+id).remove();
if ($('*[data-cardencomenda="'+encomenda+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardencomenda="'+encomenda+'"]').remove();
}
if ($('*[data-cardcliente="'+cliente+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardcliente="'+cliente+'"]').remove();
}
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
};
function loadEncsAprovacao() {
$('#encsAprovacaoContent').html('');
$.ajax({
type: 'POST',
url: '/paginas/produtos/encomendas_aprovacoes_load.php',
data: '&a=1',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#encsAprovacaoContent').html(data);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
function filtrarEncsAprovacao() {
limparSelLinhasEnc();
var filtros = '*';
var escaladas = $('#filtro_escaladas').val();
if (escaladas!=0) {
$('.linhaAprovacaoArtigo').hide();
filtros += '[data-escaladas="1"]';
} else {
$('.linhaAprovacaoArtigo').show();
}
var vendedor = $('#filtro_vendedor').val();
if (vendedor!=0) {
filtros += '[data-vendedor="'+vendedor+'"]';
}
var cliente = $('#filtro_cliente').val();
if (cliente!=0) {
filtros += '[data-cliente="'+cliente+'"]';
}
var artigo = $('#filtro_artigo').val();
if (artigo!=0) {
$('.linhaAprovacaoArtigo').hide();
filtros += '[data-artigo*="'+artigo+'"]';
}
var entrega = $('#filtro_dataentrega').val();
if (entrega!=0) {
filtros += '[data-entrega*="'+entrega+'"]';
}
var motivo = $('#filtro_motivo').val();
if (motivo!=0) {
$('.linhaAprovacaoArtigo').hide();
filtros += '[data-motivo*="'+motivo+'"]';
}
if (filtros != '*') {
$('.linhaAprovacaoCliente').hide();
$(filtros).show();
} else {
$('.linhaAprovacaoCliente').show();
}
if ($('.linhaAprovacaoCliente:visible').length == 0) {
$('.semResultados').show();
} else {
$('.semResultados').hide();
}
}
function selecionarTodosChecks(el, classe) {
var selBtn = ($(el).is(":checked")) ? 1 : 0;
if (selBtn == 1) {
$('.'+classe+':visible').not(':disabled').prop('checked', true).trigger('change');
} else {
$('.'+classe).not(':disabled').prop('checked', false).trigger('change');
}
}
function limparSelLinhasEnc() {
$('.selLinha, .selLinhaEnc').prop('checked', false);
$('.trLinha').removeClass('bg-primary-transparent');
handleChecksLinhaEnc();
}
function selecionarTodasLinhasEnc(tmpIdEnc) {
var selLinhaEnc = ($("#selLinhaEnc"+tmpIdEnc).is(":checked")) ? 1 : 0;
if (selLinhaEnc == 1) {
$('.selLinhaEnc'+tmpIdEnc+':visible').not(':disabled').prop('checked', true).trigger('change');
} else {
$('.selLinhaEnc'+tmpIdEnc).not(':disabled').prop('checked', false).trigger('change');
}
}
function selecionarLinhaEnc(tmpId,tmpCliente) {
var selLinha = ($("#selLinha"+tmpId).is(":checked")) ? 1 : 0;
if (selLinha == 1) {
$('#trLinha'+tmpId).addClass('bg-primary-transparent');
} else {
$('#trLinha'+tmpId).removeClass('bg-primary-transparent');
}
handleChecksLinhaEnc();
handleChecksClienteLinhaEnc(tmpCliente);
}
function selecionarLinhaEncForn(tmpId,tmpCliente) {
var selLinha = ($("#selLinha"+tmpId).is(":checked")) ? 1 : 0;
if (selLinha == 1) {
$('#trLinha'+tmpId).addClass('bg-primary-transparent');
} else {
$('#trLinha'+tmpId).removeClass('bg-primary-transparent');
}
handleChecksLinhaEncForn();
handleChecksClienteLinhaEnc(tmpCliente);
}
function handleChecksClienteLinhaEnc(tmpCliente) {
var ct=0;
$('input.selLinhaCliente'+tmpCliente+':checkbox:checked').each(function(i, obj) {
ct++;
});
if (ct > 0) {
$('#btnNotificar'+tmpCliente).removeClass('disabled');
} else {
$('#btnNotificar'+tmpCliente).addClass('disabled');
}
}
function handleChecksLinhaEnc() {
var ct=0;
var ids='';
var podeEscalar = false;
var podeAprovar = false;
var podeRejeitar = false;
$('input.selLinha:checkbox:checked').each(function(i, obj) {
var id = $(this).val();
if (!$('#btnEscalar_'+id).hasClass('disabled')) { podeEscalar = true; }
if (!$('#btnAprovacao_'+id).hasClass('disabled')) { podeAprovar = true; }
if (!$('#btnRejeitar_'+id).hasClass('disabled')) { podeRejeitar = true; }
if (ct>0) ids += ',';
ids += id;
ct++;
});
$('#ids_selecionados').val(ids);
if (ct > 0) {
$('#barraOpcoes').show();
if (podeEscalar) {
$('#btnEscalarSelecionados').removeClass('disabled');
} else {
$('#btnEscalarSelecionados').addClass('disabled');
}
if (podeAprovar) {
$('#btnAprovacaoSelecionados').removeClass('disabled');
} else {
$('#btnAprovacaoSelecionados').addClass('disabled');
}
if (podeRejeitar) {
$('#btnRejeitarSelecionados').removeClass('disabled');
} else {
$('#btnRejeitarSelecionados').addClass('disabled');
}
} else {
$('#barraOpcoes').hide();
}
}
function handleChecksLinhaEncForn() {
var ct=0;
var ids='';
$('input.selLinha:checkbox:checked').each(function(i, obj) {
var id = $(this).val();
if (ct>0) ids += ',';
ids += id;
ct++;
});
$('#ids_selecionados').val(ids);
if (ct > 0) {
$('#barraOpcoes').show();
} else {
$('#barraOpcoes').hide();
}
}
function limparLinhasEncsSelecionadas(tipo) {
var ct=0;
var campoVerificacao = '';
if (tipo == 'escalar') {
campoVerificacao = 'btnEscalar_';
} else if (tipo == 'aprovar') {
campoVerificacao = 'btnAprovacao_';
} else {
campoVerificacao = 'btnRejeitar_';
}
$('input.selLinha:checkbox:checked').each(function(i, obj) {
var tmpId = $(this).val();
if (!$('#'+campoVerificacao+tmpId).hasClass('disabled')) {
var encomenda = $(this).attr('data-encomenda');
var cliente = $(this).attr('data-cliente');
$('#trLinha'+tmpId).remove();
if ($('*[data-cardencomenda="'+encomenda+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardencomenda="'+encomenda+'"]').remove();
}
if ($('*[data-cardcliente="'+cliente+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardcliente="'+cliente+'"]').remove();
}
}
});
}
function limparLinhasEncsFornSelecionadas(tipo) {
var ct=0;
var campoVerificacao = '';
if (tipo == 'aprovar') {
campoVerificacao = 'btnAprovacao_';
} else {
campoVerificacao = 'btnRejeitar_';
}
$('input.selLinha:checkbox:checked').each(function(i, obj) {
var tmpId = $(this).val();
if (!$('#'+campoVerificacao+tmpId).hasClass('disabled')) {
var encomenda = $(this).attr('data-encomenda');
var fornecedor = $(this).attr('data-fornecedor');
$('#trLinha'+tmpId).remove();
if ($('*[data-cardencomenda="'+encomenda+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardencomenda="'+encomenda+'"]').remove();
}
if ($('*[data-cardfornecedor="'+fornecedor+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardfornecedor="'+fornecedor+'"]').remove();
}
}
});
}
function getArrayEncsSelecionadasPost(tipo) {
var ct=0;
var detalhes='';
var campoVerificacao = 'btnEscalar_';
if (tipo == 'escalar') {
campoVerificacao = '';
} else if (tipo == 'aprovar') {
campoVerificacao = 'btnAprovacao_';
} else {
campoVerificacao = 'btnRejeitar_';
}
$('input.selLinha:checkbox:checked').each(function(i, obj) {
var tmpId = $(this).val();
if (!$('#'+campoVerificacao+tmpId).hasClass('disabled')) {
var preco = $('#valorNovo_'+tmpId).val();
var id_linha_encomenda = $('#valorNovo_'+tmpId).attr('data-linha-encomenda');
var datavigor = $('#dataVigor_'+tmpId).val();
var padrao = ($("#valorPadrao_"+tmpId).is(":checked")) ? 1 : 0;
var infolinha = tmpId+'@'+preco+'@'+datavigor+'@'+padrao+'@'+id_linha_encomenda;
if (ct>0) detalhes += '|';
detalhes += infolinha;
ct++;
}
});
detalhes = btoa(detalhes);
return detalhes;
}
function getArrayEncsFornSelecionadasPost(tipo) {
var ct=0;
var detalhes='';
$('input.selLinha:checkbox:checked').each(function(i, obj) {
var tmpId = $(this).val();
var qtt = $('#quantity_'+tmpId).val();
var infolinha = tmpId+'@'+qtt;
if (ct>0) detalhes += '|';
detalhes += infolinha;
ct++;
});
detalhes = btoa(detalhes);
return detalhes;
}
function rejeitarLinhaEncSelecionadas(){
var detalhes = getArrayEncsSelecionadasPost('rejeitar');
if (!detalhes) { toastr.error("Não foram encontradas linhas para Rejeitar"); return false; }
Swal2.fire({
title: "Rejeitar Linha(s) Encomenda(s)",
html: 'Tem a certeza que quer rejeitar esta(s) linha(s)? ',
icon: "error",
showCancelButton: true,
confirmButtonColor: "#e82646",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
$('#swall_motivo_nao_aprovado').removeClass("is-invalid");
var motivo = document.getElementById('swall_motivo_nao_aprovado').value;
if (motivo == '') { $('#swall_motivo_nao_aprovado').addClass("is-invalid"); return false; }
return $.ajax({
url: "/paginas/refresh/handle-linha-enc.php",
data: "&detalhes="+detalhes+'&motivo='+motivo+"&status=Rejeitado&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID0dfe1c4a62d9f8381c559585ec97a835",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
limparLinhasEncsSelecionadas('rejeitar');
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
function aprovarLinhaEncSelecionadas(){
var detalhes = getArrayEncsSelecionadasPost('aprovar');
if (!detalhes) { toastr.error("Não foram encontradas linhas para Aprovar"); return false; }
Swal2.fire({
title: "Aprovar Linha(s) Encomenda(s)",
html: 'Tem a certeza que quer aprovar esta(s) linha(s)?',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#13bfa6",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
return $.ajax({
url: "/paginas/refresh/handle-linha-enc.php",
data: "&detalhes="+detalhes+"&status=Aprovado&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=IDe48dae0bc6bfe2ea8490424f1a040b2a",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
limparLinhasEncsSelecionadas('aprovar');
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
function escalarLinhaEncSelecionadas(){
var detalhes = getArrayEncsSelecionadasPost('escalar');
if (!detalhes) { toastr.error("Não foram encontradas linhas para Escalar"); return false; }
Swal2.fire({
title: "Escalar Linha(s) Encomenda(s)",
html: 'Tem a certeza que quer escalar esta(s) linha(s)? ',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#1170e4",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
$('#swall_observacoes_escalar').removeClass("is-invalid");
var observacoes = document.getElementById('swall_observacoes_escalar').value;
if (observacoes == '') { $('#swall_observacoes_escalar').addClass("is-invalid"); return false; }
return $.ajax({
url: "/paginas/refresh/handle-linha-enc.php",
data: "&detalhes="+detalhes+'&observacoes='+observacoes+"&status=Escalado&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=IDb3d08f6fe547d7f3359e4ca7ffdb4661",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
setTimeout(function(){
window.location.reload();
}, 250);
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
function filtrarEncsFornAprovacao() {
limparSelLinhasEnc();
var filtros = '*';
var empresa = $('#filtro_empresa').val();
if (empresa!=0) {
filtros += '[data-empresa="'+empresa+'"]';
}
var armazem = $('#filtro_armazem').val();
if (armazem!=0) {
filtros += '[data-armazem*="'+armazem+'"]';
}
var fornecedor = $('#filtro_fornecedor').val();
if (fornecedor!=0) {
filtros += '[data-fornecedor="'+fornecedor+'"]';
}
var artigo = $('#filtro_artigo').val();
if (artigo!=0) {
$('.linhaAprovacaoArtigo').hide();
filtros += '[data-artigo*="'+artigo+'"]';
}
var motivo = $('#filtro_motivo').val();
if (motivo!=0) {
$('.linhaAprovacaoArtigo').hide();
filtros += '[data-motivo*="'+motivo+'"]';
}
if (filtros != '*') {
$('.linhaAprovacaoCliente').hide();
$(filtros).show();
} else {
$('.linhaAprovacaoCliente').show();
}
if ($('.linhaAprovacaoCliente:visible').length == 0) {
$('.semResultados').show();
} else {
$('.semResultados').hide();
}
}
function handleQTForn(produtoid,minimo,multiplo,unit,qtOriginal,diasOriginal) {
if (!minimo) minimo = 1;
minimo = parseInt(minimo);
if (!multiplo) multiplo = 1;
multiplo = parseInt(multiplo);
var new_qty = parseInt($("#quantity_"+produtoid).val());
new_qty = Math.ceil(new_qty/multiplo)*multiplo;
if(new_qty < minimo){
toastr.warning("Não pode encomendar abaixo da quantidade mínima");
new_qty = minimo;
}
if(new_qty < multiplo){
toastr.warning("Não pode encomendar abaixo da quantidade mínima");
new_qty = multiplo;
}
$("#quantity_"+produtoid).val(new_qty.toFixed(2)+' '+unit);
var newDias = Math.ceil(new_qty*parseInt(diasOriginal)/parseInt(qtOriginal));
$("#days_"+produtoid).val(newDias);
}
function handleDaysForn(produtoid,minimo,multiplo,unit,qtOriginal,diasOriginal) {
if (!minimo) minimo = 1;
minimo = parseInt(minimo);
if (!multiplo) multiplo = 1;
multiplo = parseInt(multiplo);
var new_days = parseInt($("#days_"+produtoid).val());
if(new_days < 1){
toastr.warning("Não pode encomendar abaixo da quantidade mínima");
new_days = 1;
}
$("#days_"+produtoid).val(new_days);
var new_qty = Math.ceil(new_days*parseInt(qtOriginal)/parseInt(diasOriginal));
new_qty = Math.ceil(new_qty/multiplo)*multiplo;
$("#quantity_"+produtoid).val(new_qty.toFixed(2)+' '+unit);
handleQTForn(produtoid,minimo,multiplo,unit,qtOriginal,diasOriginal);
}
function loadEncsFornAprovacao() {
$('#encsFornAprovacaoContent').html('');
$.ajax({
type: 'POST',
url: '/paginas/produtos/encomendas_fornecedor_aprovacoes_load.php',
data: '&a=1',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#encsFornAprovacaoContent').html(data);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
function rejeitarLinhaEncFornSelecionadas(){
var detalhes = getArrayEncsFornSelecionadasPost('rejeitar');
if (!detalhes) { toastr.error("Não foram encontradas linhas para Rejeitar"); return false; }
Swal2.fire({
title: "Rejeitar Linha(s) Encomenda(s)",
html: 'Tem a certeza que quer rejeitar esta(s) linha(s)? ',
icon: "error",
showCancelButton: true,
confirmButtonColor: "#e82646",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
$('#swall_motivo_nao_aprovado').removeClass("is-invalid");
var motivo = document.getElementById('swall_motivo_nao_aprovado').value;
if (motivo == '') { $('#swall_motivo_nao_aprovado').addClass("is-invalid"); return false; }
return $.ajax({
url: "/paginas/refresh/handle-linha-enc-forn.php",
data: "&detalhes="+detalhes+'&motivo='+motivo+"&status=Rejeitado&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=IDe694acc0888dcf3a028fc04e89b62ca5",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
limparLinhasEncsFornSelecionadas('rejeitar');
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
function aprovarLinhaEncFornSelecionadas(){
var detalhes = getArrayEncsFornSelecionadasPost('aprovar');
if (!detalhes) { toastr.error("Não foram encontradas linhas para Aprovar"); return false; }
Swal2.fire({
title: "Aprovar Linha(s) Encomenda(s)",
html: 'Tem a certeza que quer aprovar esta(s) linha(s)? ',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#13bfa6",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
var motivo = document.getElementById('swall_observacoes_aprovar').value;
/*if (motivo == '') { $('#swall_observacoes_aprovar').addClass("is-invalid"); return false; }*/
return $.ajax({
url: "/paginas/refresh/handle-linha-enc-forn.php",
data: "&detalhes="+detalhes+'&observacoes='+motivo+"&status=Aprovado&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID004a720d4ee33a6935baa92e9fa3faad",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value==1){
limparLinhasEncsFornSelecionadas('aprovar');
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
$(".qty").keypress(function (e) {
if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});
function changeqt(produtoid,operator,multiplo,unit,peso = 0) {
if (!multiplo) multiplo = 1;
multiplo = parseInt(multiplo);
peso = parseFloat(peso);
var qty = $(".quantity_"+produtoid).val();
if(operator=="+"){
var new_qty = parseInt(qty)+multiplo;
}else if(operator=="-"){
var new_qty = parseInt(qty)-multiplo;
}else{
var new_qty = parseInt($(".quantity_"+produtoid).val());
new_qty = Math.ceil(new_qty/multiplo)*multiplo;
}
if(new_qty < multiplo){
toastr.warning("Não pode encomendar abaixo da quantidade mínima");
new_qty = multiplo;
}
$(".quantity_"+produtoid).val(new_qty+' '+unit);
if (unit != 'KG' && peso>0) {
var kgs = new_qty / multiplo * peso;
$(".kgs_"+produtoid).val(kgs.toFixed(2));
}
}
function changekg(produtoid,operator,multiplo,unit,peso = 0,idCliente='',conversao=0,ischeckout = false,tmpid=false) {
if (!peso) peso = 1;
peso = parseFloat(peso);
multiplo = parseInt(multiplo);
var kgs = $(".kgs_"+produtoid).val();
var new_kgs = parseFloat($(".kgs_"+produtoid).val());
new_kgs = Math.ceil(new_kgs/peso)*peso;
if(new_kgs < peso){
toastr.warning("Não pode encomendar abaixo da quantidade mínima");
new_kgs = peso;
}
$(".kgs_"+produtoid).val(new_kgs.toFixed(2));
var qty = new_kgs / peso * multiplo;
if (ischeckout) {
var subpreco = $("#valorNovo_"+tmpid).val();
var subtotalLinha = parseInt(qty)/parseFloat(conversao)*parseFloat(subpreco);
$('#subtotalLinha'+tmpid).html(mostraMoeda(subtotalLinha));
$(".quantity_"+produtoid).val(qty.toFixed(0)+' '+unit).trigger('change');
} else {
$(".quantity_"+produtoid).val(qty.toFixed(0)+' '+unit);//.trigger('change');
}
if (idCliente != '') { calculaTotaisEnc(idCliente); }
}
function addcart(el,tmpid,produto,remove,oferta,id_cliente = '',tmpCliente='',tmpCart='',lote='',naocompra=0,urgencia=0){
if(produto.length){
var subpreco = $("#valorNovo_"+tmpid).val();
if (subpreco == 0 && oferta != 1) {
toastr.warning("O preço tem de ser superior a 0€ ");
return false;
}
var precoAnt = $("#valorNovo_"+tmpid).attr('data-preco');
var bloqueado = $("#valorNovo_"+tmpid).attr('data-bloqueado');
var dataNovoPreco = ($("#dataVigor_"+tmpid).length) ? $("#dataVigor_"+tmpid).val() : '';
var entregaData = '';
if ($("#dp_"+tmpCliente).length) {
entregaData = $("#dp_"+tmpCliente).val();
} else if ($("#entregaDataAddCart").length) {
entregaData = $("#entregaDataAddCart").val();
}
var padrao = ($("#valorPadrao_"+tmpid).is(":checked")) ? 1 : 0;
/*if (bloqueado == 1 && padrao == 0) {
toastr.warning("Artigo com preço bloqueado! Tem de activar a opção de atualizar o padrão.");
return false;
}*/
var qty = parseInt($(".quantity_"+tmpid).val());
if (!qty) { qty = 1; }
if (remove > 0) {
toastr.warning("Produto removido do carrinho");
$('#linhaCart'+tmpCart).find('[data-bs-toggle="tooltip"]').each(function(){ var t = bootstrap.Tooltip.getInstance(this); if(t) t.dispose(); });
$('#linhaCart'+tmpCart).remove();
if ($('*[data-cardcliente="'+tmpCliente+'"]').find('tr.trLinha').length == 0) {
$('*[data-cardcliente="'+tmpCliente+'"]').remove();
if ($('.linhaCheckoutCliente:visible').length == 0) {
$('.semResultados').show();
} else {
$('.semResultados').hide();
}
} else {
calculaTotaisEnc(tmpCliente);
}
}
if (naocompra == 1) {
Swal2.fire({
title: "Atenção! Este artigo está marcado como \"Não compra\"!",
html: 'Tem a certeza que quer continuar?',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#13bfa6",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
return $.ajax({
url: "https://comercial-laltrait.aplataforma.com/paginas/refresh/add-cart.php",
data: "&produto="+produto+"&oferta="+oferta+"&padrao="+padrao+"&precoant="+precoAnt+"&subpreco="+subpreco+"&data_novo_preco="+encodeURIComponent(dataNovoPreco)+"&entrega_data="+encodeURIComponent(entregaData)+"&qt="+qty+"&remove="+remove+"&id_cliente="+id_cliente+"&lote="+lote+"&urgencia="+urgencia+"&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID6b0d198b0d3e543e61d893ea8fd03dde",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
var ajaxResult = result.value;
if(ajaxResult.indexOf('_') != -1){
var numBadges = ajaxResult.split('_');
if (numBadges[1]>0) {
$('#enc_cart_number').html(' ');
} else {
$('#enc_cart_number').html(' ');
}
if ($('#botaoCheckoutPreco').length) {
var objectivo = $('#valorObjectivo').val();
var totalMaisObjectivo = parseFloat(objectivo);
if (parseFloat(numBadges[2])>0) {
totalMaisObjectivo += parseFloat(numBadges[2]);
$('#botaoCheckoutPreco').html(' '+mostraMoeda(numBadges[2])+' ('+numBadges[1]+')');
} else {
$('#botaoCheckoutPreco').html(' CHECKOUT');
}
$('#botaoObjectivoFalta').html('Objectivo: '+mostraMoeda(totalMaisObjectivo));
if (totalMaisObjectivo >= 0) {
$('#botaoObjectivoFalta').removeClass('btn-outline-danger').addClass('btn-outline-success');
} else {
$('#botaoObjectivoFalta').removeClass('btn-outline-success').addClass('btn-outline-danger');
}
}
if (remove > 0) {
if ($('#btnAddCartProd'+tmpid).length) {
$('#btnAddCartProd'+tmpid).removeClass("btn-success").addClass("btn-primary");
}
if (oferta == 1) {
$('.addCart'+produto.trim()).filter('.addCartOferta.btn-success').removeClass("btn-success").addClass("btn-primary");
} else if (oferta === '' || oferta === undefined) {
$('.addCart'+produto.trim()).filter('.btn-success').removeClass("btn-success").addClass("btn-primary");
} else {
$('.addCart'+produto.trim()).filter('.btn-success:not(.addCartOferta)').removeClass("btn-success").addClass("btn-primary");
}
} else {
$(el).removeClass("btn-primary").addClass("btn-success");
}
}else if(ajaxResult==-1){
toastr.warning("A quantidade tem de ser superior a 0 e inferior a 10 000 ");
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
} else {
$.ajax({
url: "https://comercial-laltrait.aplataforma.com/paginas/refresh/add-cart.php",
data: "&produto="+produto+"&oferta="+oferta+"&padrao="+padrao+"&precoant="+precoAnt+"&subpreco="+subpreco+"&data_novo_preco="+encodeURIComponent(dataNovoPreco)+"&entrega_data="+encodeURIComponent(entregaData)+"&qt="+qty+"&remove="+remove+"&id_cliente="+id_cliente+"&lote="+lote+"&urgencia="+urgencia+"&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=IDfa5f10f0ad6b3df128b988b7991588c6",
type: "POST",
success:function(result){
if(result.indexOf('_') != -1){
var numBadges = result.split('_');
if (numBadges[1]>0) {
$('#enc_cart_number').html(' ');
} else {
$('#enc_cart_number').html(' ');
}
if ($('#botaoCheckoutPreco').length) {
var objectivo = $('#valorObjectivo').val();
var totalMaisObjectivo = parseFloat(objectivo);
if (parseFloat(numBadges[2])>0) {
totalMaisObjectivo += parseFloat(numBadges[2]);
$('#botaoCheckoutPreco').html(' '+mostraMoeda(numBadges[2])+' ('+numBadges[1]+')');
} else {
$('#botaoCheckoutPreco').html(' CHECKOUT');
}
$('#botaoObjectivoFalta').html('Objectivo: '+mostraMoeda(totalMaisObjectivo));
if (totalMaisObjectivo >= 0) {
$('#botaoObjectivoFalta').removeClass('btn-outline-danger').addClass('btn-outline-success');
} else {
$('#botaoObjectivoFalta').removeClass('btn-outline-success').addClass('btn-outline-danger');
}
}
if (remove > 0) {
if ($('#btnAddCartProd'+tmpid).length) {
$('#btnAddCartProd'+tmpid).removeClass("btn-success").addClass("btn-primary");
}
if (oferta == 1) {
$('.addCart'+produto.trim()).filter('.addCartOferta.btn-success').removeClass("btn-success").addClass("btn-primary");
} else if (oferta === '' || oferta === undefined) {
$('.addCart'+produto.trim()).filter('.btn-success').removeClass("btn-success").addClass("btn-primary");
} else {
$('.addCart'+produto.trim()).filter('.btn-success:not(.addCartOferta)').removeClass("btn-success").addClass("btn-primary");
}
} else {
$(el).removeClass("btn-primary").addClass("btn-success");
}
}else if(result==-1){
toastr.warning("A quantidade tem de ser superior a 0 e inferior a 10 000 ");
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
}
return false;
};
};
function handleInfoFav(cliente,artigo,status) {
if (cliente.length && artigo.length && status.length) {
$.ajax({
url: "/paginas/refresh/handle-favorito.php",
data: "&cliente="+cliente+"&artigo="+artigo+"&status="+status+"&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID1432f5e6cc9a1e0de09a43195676ef5d",
type: "POST",
success:function(result){
if(result==1){
if (status == 'Favorito') {
$('.botaoInfo'+artigo).removeClass('btn-primary').removeClass('btn-danger').addClass('btn-success');
$('.iconInfo'+artigo).removeClass('fa fa-info').removeClass('fe fe-slash').addClass('fe fe-heart');
$('.favIcon'+artigo).removeClass('text-primary').addClass('text-success');
$('.naoCompraIcon'+artigo).removeClass('text-success').addClass('text-primary');
$('.checkFav'+artigo).show();
$('.checkNaoCompra'+artigo).hide();
$('.favIcon'+artigo).attr("onclick", "handleInfoFav('"+cliente+"','"+artigo+"','Indefinido')");
$('.naoCompraIcon'+artigo).attr("onclick", "handleInfoFav('"+cliente+"','"+artigo+"','Não Compra')");
} else if (status == 'Não Compra') {
$('.botaoInfo'+artigo).removeClass('btn-primary').removeClass('btn-success').addClass('btn-danger');
$('.iconInfo'+artigo).removeClass('fa fa-info').removeClass('fe fe-heart').addClass('fe fe-slash');
$('.naoCompraIcon'+artigo).removeClass('text-primary').addClass('text-success');
$('.favIcon'+artigo).removeClass('text-success').addClass('text-primary');
$('.checkNaoCompra'+artigo).show();
$('.checkFav'+artigo).hide();
$('.favIcon'+artigo).attr("onclick", "handleInfoFav('"+cliente+"','"+artigo+"','Favorito')");
$('.naoCompraIcon'+artigo).attr("onclick", "handleInfoFav('"+cliente+"','"+artigo+"','Indefinido')");
} else {
$('.botaoInfo'+artigo).removeClass('btn-success').removeClass('btn-danger').addClass('btn-primary');
$('.iconInfo'+artigo).removeClass('fe fe-heart').removeClass('fe fe-slash').addClass('fa fa-info');
$('.favIcon'+artigo+', .naoCompraIcon'+artigo).removeClass('text-success').addClass('text-primary');
$('.checkFav'+artigo+', .checkNaoCompra'+artigo).hide();
$('.favIcon'+artigo).attr("onclick", "handleInfoFav('"+cliente+"','"+artigo+"','Favorito')");
$('.naoCompraIcon'+artigo).attr("onclick", "handleInfoFav('"+cliente+"','"+artigo+"','Não Compra')");
}
toastr.success("Operação realizada com sucesso!");
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
}
}
function changecart(tmpid,cartid,operator,multiplo,unit,peso = 0,conversao=0,idCliente = ''){
if (!multiplo) multiplo = 1;
multiplo = parseInt(multiplo);
peso = parseFloat(peso);
var qty = $(".quantity_"+cartid).val();
if(operator=="+"){
var new_qty = parseInt(qty)+multiplo;
}else if(operator=="-"){
var new_qty = parseInt(qty)-multiplo;
}else{
var new_qty = parseInt($(".quantity_"+cartid).val());
new_qty = Math.ceil(new_qty/multiplo)*multiplo;
}
if(new_qty==0){
toastr.warning("Não pode encomendar abaixo da quantidade mínima");
return false;
}/*else if(new_qty>9999){
toastr.warning("Quantidade máxima ultrapassada");
return false;
};*/
if(cartid>=1){
$('#qtLinha'+tmpid).val(new_qty+' '+unit);
if (unit != 'KG' && peso>0) {
var kgs = new_qty / multiplo * peso;
$(".kgs_"+cartid).val(kgs.toFixed(2));
}
var subpreco = $("#valorNovo_"+tmpid).val();
var padrao = ($("#valorPadrao_"+tmpid).is(":checked")) ? 1 : 0;
var externasManual = ($("#externasManual_"+tmpid).is(":checked")) ? 1 : 0;
var fornecedor = $("#fornecedor_"+tmpid).val();
var subtotalLinha = parseInt(new_qty)/parseFloat(conversao)*parseFloat(subpreco);
$('#subtotalLinha'+tmpid).html(mostraMoeda(subtotalLinha));
if (idCliente != '') { calculaTotaisEnc(idCliente); }
$.ajax({
url: "https://comercial-laltrait.aplataforma.com/paginas/refresh/change-cart.php",
data: "&cartid="+cartid+"&subpreco="+subpreco+"&padrao="+padrao+"&externasManual="+externasManual+"&fornecedor="+fornecedor+"&operator="+operator+"&qt="+new_qty+"&m="+multiplo+"&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID31fbc9762fbf8f040e1258cc2f5fc953",
type: "POST",
success:function(result){
if(result>=1){
//toastr.success("Linha alterada com sucesso");
//location.reload();
}else if(result==0){
toastr.warning("Não foi possível alterar a linha");
}else if(result==-98){
toastr.warning("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
};
function calculaTotaisEnc(idCliente) {
var total = 0;
var subtotal = 0;
var ivas = [];
var strIvas = '';
$('.subtotalLinha'+idCliente).each(function(i, obj) {
var tmp = $(this).html();
var tmpValor = parseFloat(tmp.replace("€","").replace(" ","").replace(",","."));
subtotal = subtotal + tmpValor;
var tmpIva = parseFloat($(this).attr('data-iva'));
var calculoIva = tmpValor * (tmpIva * 0.01 + 1) - tmpValor;
if (!ivas[tmpIva]) { ivas[tmpIva] = 0; }
if(strIvas.indexOf(tmpIva) != -1){ } else {
if (strIvas != '') { strIvas += ','; }
strIvas += tmpIva;
}
ivas[tmpIva] = (parseFloat(ivas[tmpIva]) + parseFloat(calculoIva));
});
$('#subtotal'+idCliente).html(mostraMoeda(subtotal));
var arrayIvas = strIvas.split(',');
var totalIvas = 0;
$.each(arrayIvas, function(i,iva) {
$('#taxas'+iva+idCliente).html('+ '+mostraMoeda(ivas[iva]));
totalIvas += parseFloat(ivas[iva]);
});
total = subtotal + totalIvas;
$('#totalCartTxt'+idCliente).html(mostraMoeda(total));
if (total>750) {
$('#consumidorFinal'+idCliente).hide();
$('#consumidorFinal'+idCliente).prop("checked", false);
} else {
$('#consumidorFinal'+idCliente).show();
}
}
function changecartpadrao(tmpid,cartid){
if(cartid>=1){
var subpreco = $("#valorNovo_"+tmpid).val();
var data_vigor = $("#dataVigor_"+tmpid).val();
setTimeout(function(){
$.ajax({
url: "https://comercial-laltrait.aplataforma.com/paginas/refresh/change-cart-padrao.php",
data: "&cartid="+cartid+"&subpreco="+subpreco+"&data_vigor="+data_vigor+"&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID3f0bbcadfaeae987f1d7af0938a9a9a3",
type: "POST",
success:function(result){
if(result>=1){
location.reload();
}else if(result==0){
toastr.warning("Não foi possível alterar a linha");
}else if(result==-98){
toastr.warning("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
return false;
}, 100);
};
};
var modalQuantidadeArtigo;
function openModalQuantidade(tmpid, id_linha_encomenda, id_encomenda, qtt, multiplos, unidade, kgs, kgsAtual) {
$('#modalQT_tmpID').val(tmpid);
$('#modalQT_id_linha_encomenda').val(id_linha_encomenda);
$('#modalQT_id_encomenda').val(id_encomenda);
$('#modalQT_qtt').val(qtt);
$('#modalQT_qtt').addClass("quantity_"+tmpid);
$('#modalQT_qtt').unbind();
$('#modalQT_qtt').change(function() { changeqt(tmpid,'',multiplos,unidade,kgs); });
$('#modalQT_kgs').val(kgsAtual);
$('#modalQT_kgs').attr('step', kgs.replace(",","."));
$('#modalQT_kgs').addClass("kgs_"+tmpid);
$('#modalQT_kgs').unbind();
$('#modalQT_kgs').change(function() { changekg(tmpid,'',multiplos,unidade,kgs); });
modalQuantidadeArtigo = new bootstrap.Modal(document.getElementById('modalQuantidadeArtigo'), { backdrop: 'static', keyboard: false });
modalQuantidadeArtigo.show();
}
$("#alterarQuantidadeArtEnc").submit(function(event) {
event.preventDefault();
var $this = $(this);
var tmpId = $(this).find("[name='tmpID']").val();
var quantidade = parseInt($('#modalQT_qtt').val());
var serialize = $this.serialize();
savingQuantidade(tmpId,true);
$.ajax({
type: 'POST',
url: '/paginas/refresh/guarda_quantidade_encomenda.php',
data: serialize+'&quantidade='+quantidade,
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if(data==1){
toastr.success("Quantidade atualizada com sucesso!");
$('#textQt'+tmpId).html(mostraMoeda(quantidade,'',2));
$('#modalQuantidadeArtigo'+tmpId).modal('toggle');
}else if(data=="-98"){
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else if(data=="-99"){
toastr.error("Não foi possivel concluir o seu pedido.");
}
savingQuantidade(tmpId,false);
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
savingQuantidade(tmpId,false);
}
});
return false;
});
function savingQuantidade(id,on = true) {
if (on) {
$("#alterarQuantidadeArtEnc_"+id+" input").attr("readonly", true);
$("#alterarQuantidadeArtEnc_"+id+" button").attr("readonly", true);
$("#alterarQuantidadeArtEnc_"+id+" select").attr("disabled", true);
$("#alterarQuantidadeArtEnc_"+id+" textarea").attr("readonly", true);
$("#alterarQuantidadeArtEnc_"+id+" button").addClass("btn-loading");
} else {
$("#alterarQuantidadeArtEnc_"+id+" input").attr("readonly", false);
$("#alterarQuantidadeArtEnc_"+id+" button").attr("readonly", false);
$("#alterarQuantidadeArtEnc_"+id+" select").attr("disabled", false);
$("#alterarQuantidadeArtEnc_"+id+" textarea").attr("readonly", false);
$("#alterarQuantidadeArtEnc_"+id+" button").removeClass("btn-loading");
}
}
var modalDataPreferencia;
function openModalDataPreferencia(id, idCliente, idEncomenda) {
var podeAprovar = true;
$('.btnAprovarEnc_'+id).each(function(i, obj) {
if ($(this).hasClass('disabled')) { podeAprovar = false; }
});
if (!podeAprovar) {
toastr.warning("Atenção: Não pode alterar a data de entrega");
return false;
}
modalDataPreferencia = new bootstrap.Modal(document.getElementById('modalDataPreferencia'+id), { backdrop: 'static', keyboard: false });
modalDataPreferencia.show();
if (idCliente && idEncomenda) {
$('#modalDataPreferenciaBody'+id).html('Loading...
');
$.ajax({
type: 'POST',
url: '/paginas/refresh/get-datas-entrega.php',
data: '&idCliente='+idCliente+'&idEncomenda='+idEncomenda+'&tmpIdEncomenda='+id+'&key=0ce047d694c014e336b247b7b6bb2ada144c53a8',
success: function(data) {
$('#modalDataPreferenciaBody'+id).html(data);
},
error: function() {
$('#modalDataPreferenciaBody'+id).html('Não foi possivel concluir o seu pedido.
');
}
});
}
}
function changeDataEntrega(id, encomenda, data) {
$.ajax({
url: "/paginas/refresh/change-data-encomenda.php",
data: "&encomenda="+encomenda+'&data='+data+"&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID0bfd6b1e72e049c14880bf6a57e9baec",
type: "POST",
success:function(result){
if(result==1){
//$('.dataent_'+id).html(data);
toastr.success("Data de Entrega alterada com sucesso");
//modalDataPreferencia.hide();
window.location.reload();
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
}
var modalSubstituirArtigo;
var datatableSubs;
function openModalSubstituirArtigo(tmpId, id_cliente, id_cliente_precos, data, id_encomenda, id_linha_encomenda) {
$('#modalSubsLoading').show();
$('#modalSubsContent').html('');
modalSubstituirArtigo = new bootstrap.Modal(document.getElementById('modalSubstituirArtigo'), { backdrop: 'static', keyboard: false });
modalSubstituirArtigo.show();
$.ajax({
type: 'POST',
url: '/paginas/refresh/get-artigos-substituir.php',
data: '&tmpId='+tmpId+'&id_cliente='+id_cliente+'&id_cliente_precos='+id_cliente_precos+'&data_entrega='+data+'&id_encomenda='+id_encomenda+'&id_linha_encomenda='+id_linha_encomenda,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
var firstLoadD = true;
$('#modalSubsLoading').hide();
$('#modalSubsContent').html(data);
datatableSubs = $('#listaArtigosDataTable').DataTable({
order: [[1, 'asc']],
columnDefs : [
{ 'visible': false, 'targets': [3] }
],
language: {
"sProcessing": " ",
"sLengthMenu": "Mostrar _MENU_ registos",
"sZeroRecords": "Não foram encontrados resultados",
"sEmptyTable": "Nenhum dado disponível nesta tabela",
"sInfo": "A mostrar de _START_ a _END_ de um total de _TOTAL_ registos",
"sInfoEmpty": "A mostrar 0 de un total de 0 registos",
"sInfoFiltered": "(filtrado de um total de _MAX_ registos)",
"sInfoPostFix": "",
"sSearch": "Procurar:",
"sUrl": "",
"sInfoThousands": ",",
"sLoadingRecords": "A carregar...",
"oPaginate": {
"sFirst": "Primeiro",
"sLast": "Último",
"sNext": "Seguinte",
"sPrevious": "Anterior"
},
"oAria": {
"sSortAscending": ": Ordenar a coluna de forma ascendente",
"sSortDescending": ": Ordenar a coluna de forma descendente"
},
searchPlaceholder: "Procurar...",
sSearch: ""
}, drawCallback: function() {
if (firstLoadD) {
$("#listaArtigosDataTable_length").html('Artigos Negociados Todos Artigos ');
firstLoadD = false;
}
}
});
$.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
var negociados = parseInt($('#apenasNegociadosSubs').val());
var infoNegociado = parseInt(data[3]);
if (negociados == 0) {
return true;
} else {
if (infoNegociado == 1) {
return true;
}
}
});
filtrarArtigosSubstituir();
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
function filtrarArtigosSubstituir() { datatableSubs.draw(); }
function substituirArtigoEncomenda(tmpId, id_linha_encomenda, id_encomenda, id_artigo, data_entrega) {
if(id_linha_encomenda && id_encomenda && id_artigo){
Swal2.fire({
title: "Substituír Artigo",
html: 'Tem a certeza que quer substituir pelo artigo '+id_artigo+' ?',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#13bfa6",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
return $.ajax({
url: "/paginas/refresh/substituir-linha-enc.php",
data: "&id_linha_encomenda="+id_linha_encomenda+"&id_encomenda="+id_encomenda+"&id_artigo="+id_artigo+"&data_entrega="+data_entrega+"&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID13fa5d50f3ebb526b1764e9503ffc0a0",
type: "POST"
});
}
}).then(function(result) {
if (result.isConfirmed) {
if(result.value.indexOf(' ') != -1){
modalSubstituirArtigo.hide();
$('#trLinha'+tmpId).html(result.value);
}else{
toastr.error("Ocorreu um erro executar a operação. Tente de novo");
}
}
});
};
}
var tmpModalFaltasStock;
function mailFaltasStock(idCliente, emailCliente, tmpCliente) {
$('#fstock_mail_cliente_input').prop("checked", false);
$('#fstock_mail_cliente_id').val(idCliente);
var ids='';
var ct=0;
$('input.selLinhaCliente'+tmpCliente+':checkbox:checked').each(function(i, obj) {
var id = $(this).val();
if (ct>0) ids += ',';
ids += id;
ct++;
});
$('#fstock_mail_cliente_artigos').val(ids);
$('.tmpEmail').remove();
if (emailCliente != '') {
var arrayEmails = emailCliente.split(',');
$.each(arrayEmails, function(i,email) {
if (isValidEmailAddress(email)) {
var input = $('Cliente - '+email+' ');
$('#fstock_lista_emails').append(input);
}
});
$('#fstock_mail_cliente_label').show();
$('#fstock_mail_cliente_span').html(emailCliente);
$('#fstock_mail_cliente_input').val(emailCliente);
} else {
$('#fstock_mail_cliente_label').hide();
$('#fstock_mail_cliente_span').html('');
$('#fstock_mail_cliente_input').val('');
}
tmpModalFaltasStock = new bootstrap.Modal(document.getElementById('modalMailFaltasStock'), { backdrop: 'static', keyboard: false });
tmpModalFaltasStock.show();
}
$("#enviarFaltasStock").submit(function(event) {
event.preventDefault();
var $this = $(this);
var serialize = $this.serialize();
sendingForm('enviarFaltasStock', true);
$.ajax({
type: 'POST',
url: '/paginas/mail/mail-faltasstock.php',
data: serialize,
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if(data==1){
toastr.success("E-mail enviado com sucesso");
tmpModalFaltasStock.hide();
$("#enviarFaltasStock")[0].reset();
}else if(data=="-98"){
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else if(data=="-99"){
toastr.error("Não foi possivel concluir o seu pedido.");
}
sendingForm('enviarFaltasStock', false);
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
sendingForm('enviarFaltasStock', false);
}
});
return false;
});
var tmpModalMailPadroes;
$("#importar_csv_padroes").submit(function(e){
e.preventDefault();
$('#importarPrecosPadroes').addClass("btn-loading");
var form = $('#importar_csv_padroes')[0];
var data = new FormData(form);
$.ajax({
type: 'POST',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
url: 'https://comercial-laltrait.aplataforma.com/paginas/refresh/importar-csv-padroes.php',
data:data,
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.href = "https://comercial-laltrait.aplataforma.com/pt/"; }, 500);
} else if(data=="-3"){
toastr.warning("O ficheiro importado não é válido!");
}else if(data=="-2"){
toastr.warning("Extensão inválida");
}else{
$('#importar_csv_padroes').trigger("reset");
var resposta = jQuery.parseJSON(data);
var texto = "";
$.each(resposta.log, function(i,info) {
texto += info+" ";
});
if (resposta.sucesso>0 && resposta.erros==0) {
$("#close_modal_importar").trigger("click");
Swal2.fire({
title: "Todas as linhas foram importadas com sucesso.",
text: "",
icon: "success",
showCancelButton: false,
confirmButtonText: "Fechar"
});
} else if (resposta.sucesso>0 && resposta.erros>0) {
Swal2.fire({
title: resposta.sucesso+" linhas importadas com sucesso e "+resposta.erros+" falhadas!",
html: texto,
icon: "error",
showCancelButton: false,
confirmButtonText: "Fechar"
});
} else if (resposta.sucesso==0 && resposta.erros>0) {
Swal2.fire({
title: ""+resposta.erros+" linhas falharam durante a importação!",
html: texto,
icon: "error",
showCancelButton: false,
confirmButtonText: "Fechar"
});
}
}
$('#importarPrecosPadroes').removeClass("btn-loading");
},
error: function() {
toastr.error("Não foi possivel concluir o seu pedido.");
$('#importarPrecosPadroes').removeClass("btn-loading");
}
});
return false;
});
function abrirModalImportarProposta(idCliente) {
$('#importar_proposta').html('A carregar...... ');
Fancybox.show([{
src: '#modalImportarProposta',
type: 'inline'
}]);
$.ajax({
type: 'POST',
url: '/paginas/refresh/listar-propostas-cliente.php',
data: '&id_cliente='+idCliente,
dataType: 'json',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
var opts = 'Selecione ';
if (data && data.length > 0) {
for (var i = 0; i < data.length; i++) {
opts += ''+data[i].proposta_nome+' ';
}
} else {
opts += 'Não existem registos disponíveis ';
}
$('#importar_proposta').html(opts);
},
error: function() {
$('#importar_proposta').html('Não foi possivel concluir o seu pedido. ');
}
});
}
$("#importar_proposta_padroes").submit(function(event) {
event.preventDefault();
var $this = $(this);
var serialize = $this.serialize();
$('#importarPropostaPadroes').prop('disabled', true).addClass("btn-loading");
$.ajax({
type: 'POST',
url: '/paginas/refresh/importar-proposta-padroes.php',
data: serialize,
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if(data==1){
toastr.success("Proposta importada com sucesso");
Fancybox.close();
$("#importar_proposta_padroes")[0].reset();
}else if(data=="-98"){
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else{
toastr.error("Não foi possivel concluir o seu pedido.");
}
$('#importarPropostaPadroes').prop('disabled', false).removeClass("btn-loading");
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
$('#importarPropostaPadroes').prop('disabled', false).removeClass("btn-loading");
}
});
return false;
});
function modalMailPadroes(idCliente, emailCliente) {
$('#mailP_mail_cliente_input').prop("checked", false);
$('#mailP_mail_cliente_id').val(idCliente);
$('#mailP_anexo').val('').trigger('change');
$('.tmpEmail').remove();
if (emailCliente != '') {
var arrayEmails = emailCliente.split(',');
$.each(arrayEmails, function(i,email) {
if (isValidEmailAddress(email)) {
var input = $('Cliente - '+email+' ');
$('#mailP_lista_emails').append(input);
}
});
$('#mailP_mail_cliente_label').show();
$('#mailP_mail_cliente_span').html(emailCliente);
$('#mailP_mail_cliente_input').val(emailCliente);
} else {
$('#mailP_mail_cliente_label').hide();
$('#mailP_mail_cliente_span').html('');
$('#mailP_mail_cliente_input').val('');
}
tmpModalMailPadroes = Fancybox.show([{
src: '#modalMailPadroes',
type: 'inline'
}]);
}
$("#enviarMailPadroes").submit(function(event) {
event.preventDefault();
var $this = $(this);
var serialize = $this.serialize();
sendingForm('enviarMailPadroes', true);
$.ajax({
type: 'POST',
url: '/paginas/mail/mail-padroes.php',
data: serialize,
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if(data==1){
toastr.success("E-mail enviado com sucesso");
Fancybox.close();
$("#enviarMailPadroes")[0].reset();
}else if(data=="-98"){
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else if(data=="-99"){
toastr.error("Não foi possivel concluir o seu pedido.");
}
sendingForm('enviarMailPadroes', false);
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
sendingForm('enviarMailPadroes', false);
}
});
return false;
});
var tmpModalEncEstabelecimentos;
function encomendarParaEstabelecimentos(artigo, nestle, tmpId) {
var net = $('#valorNovo_'+tmpId).val();
$('#modalEncEstabelecimentosLoading').show();
$('#modalEncEstabelecimentosContent').html('');
tmpModalEncEstabelecimentos = new bootstrap.Modal(document.getElementById('modalEncEstabelecimentos'), { backdrop: 'static', keyboard: false });
tmpModalEncEstabelecimentos.show();
$.ajax({
type: 'POST',
url: '/paginas/refresh/get-enc-estabelecimentos.php',
data: '&artigo='+artigo+'&nestle='+nestle+'&net='+net,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#modalEncEstabelecimentosLoading').hide();
$('#modalEncEstabelecimentosContent').html(data);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
var tmpModalLotesEscoar;
function lotesEscoar(artigo, peso, multiplos, unid_enc, preco_bloqueado, bloqueado_encomendas, tmpId) {
var net = $('#valorNovo_'+tmpId).val();
$('#modalLotesEscoarLoading').show();
$('#modalLotesEscoarContent').html('');
tmpModalLotesEscoar = new bootstrap.Modal(document.getElementById('modalLotesEscoar'), { backdrop: 'static', keyboard: false });
tmpModalLotesEscoar.show();
$.ajax({
type: 'POST',
url: '/paginas/refresh/get-lotes-escoar.php',
data: '&artigo='+artigo+'&peso='+peso+'&multiplos='+multiplos+'&unid_enc='+unid_enc+'&preco_bloqueado='+preco_bloqueado+'&bloqueado_encomendas='+bloqueado_encomendas+'&net='+net,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#modalLotesEscoarLoading').hide();
$('#modalLotesEscoarContent').html(data);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
function isCanvasTransparent(id) {
var canvas1 = document.getElementById(id);
// true if all pixels Alpha equals to zero
var ctx = canvas1.getContext("2d");
var result;
var imageData = ctx.getImageData(0, 0, canvas1.offsetWidth, canvas1.offsetHeight);
for (var i = 0; i < imageData.data.length; i += 4)
if (imageData.data[i + 3] !== 0) return false;
return true;
}
function saveImgcanvas(image64,folder,name,print = true) {
var dataURL = image64;
var output=0;
if(dataURL && folder && name){
$.ajax({
type: 'POST',
url: 'https://comercial-laltrait.aplataforma.com/includes/inserir_image64.php',
async: true,
cache: true,
data: {image: dataURL,folder:folder,name:name},
success: function(resp) {
if (print) {
if(resp==1){
toastr.success('Imagem guardada com sucesso!');
}else if(resp==-1){
toastr.warning('Dados inválidos. Tente novamente!');
}else if(resp==-2){
toastr.warning('Directório inserido não existe!');
};
}
return resp;
}
}).done(function(resp){var output = resp; });
}else{
if (print) { toastr.warning("Ocorreu um erro ao gravar a imagem!"); }
var output = 0;
};
};
function mostra_parcial(id,estado){
if(estado==0){
$('.parcial_'+id).show();
$('#sobe_'+id).hide();
$('#baixa_'+id).show();
} else if(estado==1){
$('.parcial_'+id).hide();
$('#sobe_'+id).show();
$('#baixa_'+id).hide();
}
}
function mostra_varios_estabs(id,estado,idCliente,dataVisita,idArtigo,cor){
if(estado==0){
$('.varios_'+id).show();
$('#sobe_'+id).hide();
$('#baixa_'+id).show();
if ($('#varios_'+id).find('.loader-img').length) {
var filtro_valores = $('#filtropc_valores').val();
var mostra_atual = $('#buttonColAtual').hasClass('activo') ? 1 : 0;
$.ajax({
type: 'POST',
url: '/paginas/produtos/padroes-cliente-variosestabs-load.php',
data: '&idCliente='+idCliente+'&dataVisita='+dataVisita+'&idArtigo='+idArtigo+'&cor='+cor+'&filtro_valores='+filtro_valores+'&mostra_atual='+mostra_atual+'&id='+id,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#varios_'+id).after(data);
$('#varios_'+id).remove();
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
} else if(estado==1){
$('.varios_'+id).hide();
$('#sobe_'+id).show();
$('#baixa_'+id).hide();
}
}
function recalculaMargemPrevista() {
// Padrões-Cliente (mapa de visitas): nova fórmula F = A + Σ(Z*D), G = (F-B)/F.
// Só usa esta lógica se NÃO houver inputs ocultos da lógica antiga (produtos_load.php).
if ($('input.contaMargem2').length === 0 && window.padroesMargemDados && window.padroesMargemDados.artigos) {
var d = window.padroesMargemDados;
var sumE = 0, sumG = 0;
d.artigos.forEach(function(a) {
var X = parseFloat(a.preco_net) || 0;
var Y;
if ($('#valorNovo_'+a.tmpid).length) {
Y = parseFloat($('#valorNovo_'+a.tmpid).val()) || 0;
} else {
Y = parseFloat(a.net_atual) || 0;
}
var Z = Y - X;
sumE += Z * (parseFloat(a.qtd_estab) || 0);
sumG += Z * (parseFloat(a.qtd_grupo) || 0);
});
var Fe = d.A_estab + sumE;
var Fg = d.A_grupo + sumG;
var ge = (Fe > 0) ? ((Fe - d.B_estab) / Fe) * 100 : 0;
var gg = (Fg > 0) ? ((Fg - d.B_grupo) / Fg) * 100 : 0;
$('#campoMargemPrevista').html(ge.toFixed(2));
$('#campoGrupoMargemPrevista').html(gg.toFixed(2));
var margemObj = parseFloat($('#campoMargemObjetivo').text());
$('#campoGrupoMargemPrevista').closest('.btn').removeClass('btn-info btn-success btn-danger').addClass(gg >= margemObj ? 'btn-success' : 'btn-danger');
return;
}
// Fallback (produtos_load.php): lógica antiga via inputs ocultos contaMargem2
var margem1 = 0;
var margem2 = 0;
$('input.contaMargem2').each(function(i, obj) {
margem2 += parseFloat($(this).val());
var tmpID = $(this).attr('data-tmpid');
var vendasArtigo = parseFloat($(this).attr('data-vendas-artigo'));
var precoNetArtigo = parseFloat($(this).attr('data-preco-net-artigo'));
var netAtual = 0;
if ($('#valorNovo_'+tmpID).length) {
netAtual = parseFloat($('#valorNovo_'+tmpID).val());
} else {
netAtual = parseFloat($(this).attr('data-net-atual'));
}
margem1 += (precoNetArtigo>0) ? (vendasArtigo * netAtual / precoNetArtigo) : 0;
});
var margemPrevista = (margem1 > 0) ? (margem1.toFixed(2) - margem2.toFixed(2)) / margem1.toFixed(2) * 100 : 0;
$('#campoMargemPrevista').html(margemPrevista.toFixed(2));
recalculaMargemPrevistaGrupo();
}
function recalculaMargemPrevistaGrupo() {
var margem1 = 0;
var margem2 = 0;
$('input.contaMargemGrupo2').each(function(i, obj) {
margem2 += parseFloat($(this).val());
var tmpID = $(this).attr('data-tmpid');
var vendasArtigo = parseFloat($(this).attr('data-vendas-artigo'));
var precoNetArtigo = parseFloat($(this).attr('data-preco-net-artigo'));
var netAtual = 0;
if ($('#valorNovo_'+tmpID).length) {
netAtual = parseFloat($('#valorNovo_'+tmpID).val());
} else {
netAtual = parseFloat($(this).attr('data-net-atual'));
}
margem1 += (precoNetArtigo>0) ? (vendasArtigo * netAtual / precoNetArtigo) : 0;
});
var margemPrevista = (margem1 > 0) ? (margem1.toFixed(2) - margem2.toFixed(2)) / margem1.toFixed(2) * 100 : 0;
$('#campoGrupoMargemPrevista').html(margemPrevista.toFixed(2));
var margemObj = parseFloat($('#campoMargemObjetivo').text());
$('#campoGrupoMargemPrevista').closest('.btn').removeClass('btn-info btn-success btn-danger').addClass(margemPrevista >= margemObj ? 'btn-success' : 'btn-danger');
}
function fotoMaQualidade(artigo) {
Swal2.fire({
title: "Foto Errada / Má Qualidade",
html: '',
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#e82646",
confirmButtonText: 'Confirmar',
cancelButtonText: 'Cancelar',
showLoaderOnConfirm: true,
allowOutsideClick: function() { return !Swal2.isLoading(); },
preConfirm: function() {
$('#swall_observacoes_qualidade').removeClass("is-invalid");
var observacoes = document.getElementById('swall_observacoes_qualidade').value;
if (observacoes == '') { $('#swall_observacoes_qualidade').addClass("is-invalid"); return false; }
return $.ajax({
type: 'POST',
url: '/paginas/refresh/reportar-problema-foto.php',
data: '&artigo='+artigo+'&observacoes='+observacoes,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
}
});
}
}).then(function(result) {
if (result.isConfirmed) {
var data = result.value;
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if(data==1){
toastr.success("Problema reportado com sucesso");
}else if(data=="-1"){
toastr.warning("Esta imagem já foi reportada");
}else if(data=="-98"){
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else{
toastr.error("Não foi possivel concluir o seu pedido.");
}
}
});
}
function problemaTratado(artigo, id) {
$.ajax({
type: 'POST',
url: '/paginas/refresh/reportar-problema-foto.php',
data: '&tratado=1&id='+id+'&artigo='+artigo,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if(data==1){
toastr.success("Problema concluído com sucesso");
setTimeout(function(){ window.location.reload(); }, 500);
}else if(data=="-98"){
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else{
toastr.error("Não foi possivel concluir o seu pedido.");
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
function openModoCliente(id) {
location.href = "https://comercial-laltrait.aplataforma.com/pt//"+id;
}
$("#gravarPreferenciasAnalise").submit(function(event) {
event.preventDefault();
var $this = $(this);
var serialize = $this.serialize();
var tabs = $('#analise_tab').val();
var niveis = $('#analise_niveis_permissoes').val();
var utilizadores = $('#analise_utilizadores').val();
var utilizadores_neg = $('#analise_utilizadores_neg').val();
sendingForm('gravarAnalise', true);
$.ajax({
type: 'POST',
url: '/paginas/analises/gravar-preferencias-analise.php',
data: serialize+'&tabs='+tabs+'&niveis='+niveis+'&utilizadores='+utilizadores+'&utilizadores_neg='+utilizadores_neg,
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if(data==1){
toastr.success("Análise gravada com sucesso");
setTimeout(function(){
window.location.reload();
}, 500);
}else if(data=="-98"){
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else{
toastr.error("Não foi possivel concluir o seu pedido.");
}
sendingForm('gravarAnalise', false);
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
sendingForm('gravarAnalise', false);
}
});
return false;
});
$("#gravarAnalise").submit(function(event) {
event.preventDefault();
var $this = $(this);
var serialize = $this.serialize();
var analise_query = $('#edit_analise_query').val();
var tipos = $("select[name='campo_tipo\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var nomes = $("input[name='campo_nome\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var varsUtilizador = $("select[name='campo_utilizador\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var varsClientes = $("select[name='campo_cliente\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var valores = $("input[name='campo_valor\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var campos = tipos+'|'+nomes+'|'+valores+'|'+varsUtilizador+'|'+varsClientes;
var posicoes = $("select[name='campo_posicao\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var sumarios = $("select[name='campo_sumario\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var formatos = $("select[name='campo_formato\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var colunas = $("input[name='campo_coluna\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var ordenacao = $("select[name='campo_ordenacao\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var ordemCampo = $("input[name='campo_ordemcampo\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var expandido = $("select[name='campo_expandido\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var filtros = $("input[name='campo_filtros\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var totals = $("select[name='campo_totals\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var formulas = $("input[name='campo_formula\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var camposPivot = posicoes+'|'+sumarios+'|'+formatos+'|'+colunas+'|'+ordenacao+'|'+ordemCampo+'|'+expandido+'|'+filtros+'|'+totals+'|'+formulas;
var camposCampos = $("input[name='campo_campo\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var alinhamentos = $("select[name='campo_alinhamento\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var coresFundo = $("select[name='campo_corfundo\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var coresTexto = $("select[name='campo_cortexto\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var formatoTexto = $("select[name='campo_formatoTexto\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
var camposFormatacao = camposCampos+'|'+alinhamentos+'|'+coresFundo+'|'+coresTexto+'|'+formatoTexto;
sendingForm('gravarAnalise', true);
$.ajax({
type: 'POST',
url: '/paginas/analises/gravar-analise.php',
data: serialize+'&analise_query='+base64_encode(analise_query)+'&analise_campos='+utf8ToBase64(campos)+'&analise_camposPivot='+utf8ToBase64(camposPivot)+'&analise_camposFormatacao='+utf8ToBase64(camposFormatacao),
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if(data==1){
toastr.success("Análise gravada com sucesso");
setTimeout(function(){
window.location.reload();
}, 500);
}else if(data=="-98"){
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else{
toastr.error("Não foi possivel concluir o seu pedido.");
}
sendingForm('gravarAnalise', false);
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
sendingForm('gravarAnalise', false);
}
});
return false;
});
var tmpModalExecAnalise;
function executarAnalise(idAnalise) {
$('#footerExecAnaliseGlobal').hide();
$('#modalExecLoadingGlobal').show();
$('#modalExecContentGlobal').html('');
$('#larguraExecutarAnaliseGlobal').addClass('maxW600');
$('#idAnaliseGlobal').val(idAnalise);
tmpModalExecAnalise = new bootstrap.Modal(document.getElementById('modalExecutarAnaliseGlobal'), { backdrop: 'static', keyboard: false, focus: false });
tmpModalExecAnalise.show();
$.ajax({
type: 'POST',
url: '/paginas/analises/executar-analise.php',
data: '&id='+idAnalise,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if (data=="-1") {
tmpModalExecAnalise.hide();
} else {
$('#modalExecLoadingGlobal').hide();
$('#modalExecContentGlobal').html(data);
if (data.indexOf('Nº Resultados:') != -1) {
$('#larguraExecutarAnaliseGlobal').removeClass('maxW600');
$('#footerExecAnaliseGlobal').hide();
} else if (data.indexOf('semResultados') == -1) {
$('#footerExecAnaliseGlobal').show();
} else {
$('#footerExecAnaliseGlobal').hide();
}
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
$(".executarAnalise").submit(function(event) {
event.preventDefault();
var $this = $(this);
var idAnalise = $(this).find("[name='analise_id']").val();
var tab = $(this).find("[name='analise_tab']").val();
$("input.checkboxAnalise:checkbox").not(':checked').each(function(i, obj) { $(this).val(0); });
$("input.checkboxAnalise:checkbox:checked").each(function(i, obj) { $(this).val(1); });
var variaveis = $("*[name='campo_"+idAnalise+"\\[\\]']").map(function(){return utf8ToBase64($(this).val());}).get();
executandoAnalise('Global',true);
$.ajax({
type: 'POST',
url: '/paginas/analises/executar-analise.php',
data: '&exec=1&id='+idAnalise+'&tab='+tab+'&variaveis='+variaveis,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#modalExecContentGlobal').html(data);
$('#larguraExecutarAnaliseGlobal').removeClass('maxW600');
$('#footerExecAnaliseGlobal').hide();
executandoAnalise('Global',false);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
executandoAnalise('Global',false);
}
});
});
function executandoAnalise(id,on = true) {
if (on) {
$('#modalExecLoading'+id).show();
$('#modalExecContent'+id).hide();
$("#executarAnalise"+id+" input").attr("readonly", true);
$("#executarAnalise"+id+" button").attr("readonly", true);
$("#executarAnalise"+id+" select").attr("disabled", true);
$("#executarAnalise"+id+" textarea").attr("readonly", true);
$("#executarAnalise"+id+" button").addClass("btn-loading");
} else {
$('#modalExecLoading'+id).hide();
$('#modalExecContent'+id).show();
$("#executarAnalise"+id+" input").attr("readonly", false);
$("#executarAnalise"+id+" button").attr("readonly", false);
$("#executarAnalise"+id+" select").attr("disabled", false);
$("#executarAnalise"+id+" textarea").attr("readonly", false);
$("#executarAnalise"+id+" button").removeClass("btn-loading");
}
}
var tmpModalExecUrgencias;
function executarUrgencias() {
$('#modalUrgenciasLoadingGlobal').show();
$('#modalUrgenciasContentGlobal').html('');
tmpModalExecUrgencias = new bootstrap.Modal(document.getElementById('modalUrgencias'), { backdrop: 'static', keyboard: false });
tmpModalExecUrgencias.show();
$.ajax({
type: 'POST',
url: '/paginas/analises/urgencias.php',
data: '&1=1',
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if (data=="-1") {
tmpModalExecUrgencias.hide();
} else {
$('#modalUrgenciasLoadingGlobal').hide();
$('#modalUrgenciasContentGlobal').html(data);
loadToolTips();
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
var tmpModalEditarDadosCliente;
function editarDadosClienteModal(idCliente) {
$('#modalEditarDadosClienteLoadingGlobal').show();
$('#modalEditarDadosClienteContentGlobal').html('');
tmpModalEditarDadosCliente = new bootstrap.Modal(document.getElementById('modalEditarDadosCliente'), { backdrop: 'static', keyboard: false });
tmpModalEditarDadosCliente.show();
$.ajax({
type: 'POST',
url: '/paginas/editar-cliente.php',
data: '&idCliente='+idCliente,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if (data=="-1") {
tmpModalEditarDadosCliente.hide();
} else {
$('#modalEditarDadosClienteLoadingGlobal').hide();
$('#modalEditarDadosClienteContentGlobal').html(data);
loadToolTips();
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
var tmpModalCheckoutCliente;
function checkoutClienteModal(idCliente,reloadPage = false) {
$('#modalCheckoutClienteLoadingGlobal').show();
$('#modalCheckoutClienteContentGlobal').html('');
if (!reloadPage) {
tmpModalCheckoutCliente = Fancybox.show([{
src: '#modalCheckoutCliente',
type: 'inline'
}], {
mainClass: 'fancybox-checkout-fullscreen'
});
}
$.ajax({
type: 'POST',
url: '/paginas/checkout-encomendas.php',
data: '&idCliente='+idCliente,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if (data=="-1") {
Fancybox.close();
} else {
$('#modalCheckoutClienteLoadingGlobal').hide();
$('#modalCheckoutClienteContentGlobal').html(data);
loadToolTips();
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
function handleTipoIncidencia(el) {
$("#motivoReentrega, #motivoDevolucaoTotal").val("").trigger("change");
$("#divMotivoReentrega, #divMotivoDevolucaoTotal, #divMotivoDevolucaoParcial, #divFotoEstabelecimento, #divDocumentoAssinado").hide();
$("#motivoReentrega, #motivoDevolucaoTotal, #fotoEstabelecimento, #fileatt1").attr("required", false);
if ($(el).val() == 0 && $(el).val() != '') {
$("#divTipoIncidencia, #divMotivoReentrega, #divFotoEstabelecimento, #divJustificacaoAdicional").hide();
$("#tipoIncidencia, #motivoReentrega, #fotoEstabelecimento").attr("required", false);
$("#motivoReentrega, #motivoDevolucaoTotal, #fotoEstabelecimento").val("").trigger("change");
$("#divDocumentoAssinado").show();
$("#fileatt1").attr("required", true);
} else if ($(el).val() == 1) {
$("#divMotivoReentrega, #divJustificacaoAdicional").show();
$("#motivoReentrega").attr("required", true);
} else if ($(el).val() == 2) {
$("#divMotivoDevolucaoTotal, #divJustificacaoAdicional").show();
$("#motivoDevolucaoTotal").attr("required", true);
$("#divDocumentoAssinado").show();
$("#fileatt1").attr("required", true);
} else if ($(el).val() == 3) {
$("#divMotivoDevolucaoParcial, #divJustificacaoAdicional").show();
$("#divDocumentoAssinado").show();
$("#fileatt1").attr("required", true);
} else {
$("#divTipoIncidencia, #divMotivoReentrega, #divFotoEstabelecimento").hide();
$("#tipoIncidencia, #motivoReentrega, #fotoEstabelecimento").attr("required", false);
$("#motivoReentrega, #motivoDevolucaoTotal, #fotoEstabelecimento").val("").trigger("change");
$("#divDocumentoAssinado").hide();
$("#fileatt1").attr("required", false);
}
}
function handleMotivoReentrega(el) {
if ($(el).val() == 1) {
$("#divFotoEstabelecimento").show();
$("#fotoEstabelecimento").attr("required", true);
} else {
$("#divFotoEstabelecimento").hide();
$("#fotoEstabelecimento").attr("required", false);
}
}
function handleMotivoPago(el) {
if ($(el).val() == 1) {
$("#divMotivoPago").hide();
$("#motivoPago").val("").trigger("change");
$("#motivoPago").attr("required", false);
} else {
$("#divMotivoPago").show();
$("#motivoPago").focus();
$("#motivoPago").attr("required", true);
}
}
function handleQTParcial(el) {
var tmdId = $(el).attr('data-id');
var valor = $(el).val();
if (valor > 0) {
$("#motivoParcial"+tmdId).attr("required", true);
} else {
$("#motivoParcial"+tmdId).attr("required", false);
}
}
function handleRecolhaGuia(el,idDoc,tipo,fromModal,originalDoc) {
$("#divMotivoNaoRecolha_"+idDoc).hide();
if ($(el).val() == 1) {
initGeolocationAnexarDocumento(idDoc,tipo,fromModal,originalDoc);
} else {
$("#divMotivoNaoRecolha_"+idDoc).show();
}
}
function confirmarNaoRecolha(idDoc,originalDoc) {
var valor = $('#motivoNaoRecolha_'+idDoc).val();
if (valor == '') {
toastr.error("Deve indicar o motivo da não recolha!");
return false;
}
var latitude = $("#tarefa_latitude").val();
var longitude = $("#tarefa_longitude").val();
$.ajax({
type: 'POST',
url: '/paginas/refresh/anexar-documento-assinado.php',
data: 'tipodocumento=BO&id_faturacab='+idDoc+'&latitude='+latitude+'&longitude='+longitude+'&motivoNaoRecolha='+valor,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8&uniqueid=ID88629f2ca7c342c0692d5839d657a455';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.href = "https://comercial-laltrait.aplataforma.com/pt/"; }, 500);
} else if(data==1 || data==2) {
toastr.success("Informação submetida com sucesso!");
initGeolocationAnexarDocumento(originalDoc,'ft',true,'');
} else if(data==3) {
toastr.success("Informação submetida com sucesso!");
var docsIgnorar = $('#todosDocsIgnorar').val();
if (docsIgnorar != '') { docsIgnorar += ','; }
docsIgnorar += idDoc;
initGeolocationAnexarDocumento(originalDoc,'ft',true,'',docsIgnorar);
} else if(data=="-98") {
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
} else {
toastr.error("Não foi possivel concluir o seu pedido.");
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
var tmpModalAnexarDocumento;
function initGeolocationAnexarDocumento(idDoc,tipo='ft',fromModal=false,originalDoc=false,docIgnorar='') {
if (fromModal) {
//tmpModalAnexarDocumento.hide();
$('#original_doc').val(originalDoc);
}
$("#button_anexar_documento button").attr("disabled", true);
$("#modalUploadDocumentoLoading").show();
$("#anexarDocumentoAssinado").html('');
if (fromModal) {
obterDocumentoAssinar(idDoc,tipo,docIgnorar);
} else {
tmpModalAnexarDocumento = new bootstrap.Modal(document.getElementById('modalUploadDocumento'), { backdrop: 'static', keyboard: false });
tmpModalAnexarDocumento.show();
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
$("#tarefa_latitude").val(position.coords.latitude);
$("#tarefa_longitude").val(position.coords.longitude);
obterDocumentoAssinar(idDoc,tipo,docIgnorar);
},
(error) => {
toastr.error('Não foi possível obter a sua geolocalização: '+error.code);
$("#modalUploadDocumentoLoading").hide();
$('#anexarDocumentoAssinado').html('Não foi possível obter a sua geolocalização. Certifique-se que tem a localização ativa no seu browser e boa cobertura GPS.
');
obterDocumentoAssinar(idDoc,tipo,docIgnorar);
},
{ enableHighAccuracy: false, timeout: 10000},
);
} else {
toastr.error('Este browser não suporta serviços de geolocalização');
$("#modalUploadDocumentoLoading").hide();
$('#anexarDocumentoAssinado').html('Este browser não suporta serviços de geolocalização
');
}
}
}
function obterDocumentoAssinar(idDoc,tipo='ft',docIgnorar='') {
$("#button_anexar_documento button").attr("disabled", false);
$.ajax({
type: 'POST',
url: '/paginas/refresh/modal-documento-assinado.php',
data: '&'+tipo+'='+idDoc+'&docIgnorar='+docIgnorar,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$("#modalUploadDocumentoLoading").hide();
$('#anexarDocumentoAssinado').html(data);
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
tmpModalAnexarDocumento.hide();
}
});
}
$("#anexarDocumentoAssinado").submit(function(event) {
event.preventDefault();
var $this = $(this);
var serialize = $this.serialize();
var form_data = new FormData();
var file_data1 = $('#fileatt1').prop('files')[0];
form_data.append('documento1', file_data1);
var file_data2 = $('#fileatt2').prop('files')[0];
form_data.append('documento2', file_data2);
var file_data3 = $('#fileatt3').prop('files')[0];
form_data.append('documento3', file_data3);
var foto_estab;
if ($('#fotoEstabelecimento').length > 0) {
foto_estab = $('#fotoEstabelecimento').prop('files')[0];
form_data.append('fotografia', foto_estab);
}
var id_faturacab = $('input[name=id_faturacab]').val();
form_data.append('id_faturacab', id_faturacab);
var tipodocumento = $('input[name=tipodocumento]').val();
form_data.append('tipodocumento', tipodocumento);
var latitude = $("#tarefa_latitude").val();
form_data.append('latitude', latitude);
var longitude = $("#tarefa_longitude").val();
form_data.append('longitude', longitude);
var pago = $("#pago").val();
form_data.append('pago', pago);
var motivoPago = $("#motivoPago").val();
form_data.append('motivoPago', motivoPago);
var tipo_incidencia = $("#tipo_incidencia").val();
form_data.append('tipo_incidencia', tipo_incidencia);
var motivo_reentrega = $("#motivoReentrega").val();
form_data.append('motivo_reentrega', motivo_reentrega);
var justificacao_adicional = $("#justificacaoAdicional").val();
form_data.append('justificacao_adicional', justificacao_adicional);
var motivoDevolucaoTotal = $("#motivoDevolucaoTotal").val();
form_data.append('motivoDevolucaoTotal', motivoDevolucaoTotal);
if (tipo_incidencia == 3) {
var infoParcial = '';
$('input.inputQTParcial').each(function(i, obj) {
var tmdId = $(this).attr('data-id');
var valor = $(this).val();
var motivo = $('#motivoParcial'+tmdId).val();
if (valor > 0) {
if (infoParcial != '') { infoParcial += '|'; }
infoParcial += tmdId+'@'+valor+'@'+motivo;
}
});
if (infoParcial == '') {
toastr.error("Deve indicar pelo menos um produto para devolução parcial!");
return false;
}
infoParcial = btoa(infoParcial);
form_data.append('infoParcial', infoParcial);
}
form_data.append('key', '0ce047d694c014e336b247b7b6bb2ada144c53a8');
form_data.append('uniqueid', 'ID53eb3f1620c2d70cff8d177c7db169e1');
sendingForm('anexarDocumentoAssinado', true);
$.ajax({
type: 'POST',
url: '/paginas/refresh/anexar-documento-assinado.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.href = "https://comercial-laltrait.aplataforma.com/pt/"; }, 500);
} else if(data==1 || data==2){
toastr.success("Documento anexado com sucesso!");
var originalDoc = $('#original_doc').val();
if (originalDoc != '') {
$('#'+originalDoc).val('');
initGeolocationAnexarDocumento(originalDoc,'ft',true,'');
} else {
tmpModalAnexarDocumento.hide();
}
$("#anexarDocumentoAssinado")[0].reset();
}else if(data=="-98"){
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else{
toastr.error("Não foi possivel concluir o seu pedido.");
}
sendingForm('anexarDocumentoAssinado', false);
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
sendingForm('anexarDocumentoAssinado', false);
}
});
return false;
});
var modalCobranca;
function novaCobranca(id_cliente,tmpID = '') {
$('#id_clienteCobranca').val(id_cliente);
$('#tmpIDCobranca').val(tmpID);
$('.tabsModalCobrancas, .btnsModalCobrancas').removeClass('active');
$('#tab-novacobranca, #btn-novacobranca').addClass('active');
modalCobranca = new bootstrap.Modal(document.getElementById('modalCobranca'), { backdrop: 'static', keyboard: false });
modalCobranca.show();
}
function handleTabHistCobrancas() {
$('#modalHistCobrancasContent').html('');
$('#modalHistCobrancasExecLoading').show();
var idCliente = $('#id_clienteCobranca').val();
$.ajax({
type: 'POST',
url: '/paginas/refresh/historico-cobrancas.php',
data: '&id='+idCliente,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else {
$('#modalHistCobrancasContent').html(data);
$('#modalHistCobrancasExecLoading').hide();
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
$("#criarCobranca").submit(function(event) {
event.preventDefault();
var $this = $(this);
var serialize = $this.serialize();
var observacoes = $('#observacoesCobranca').val();
var dataCobranca = $('#dataCobranca').val();
sendingForm('criarCobranca', true);
$.ajax({
type: 'POST',
url: '/paginas/refresh/cobranca-criar.php',
data: serialize,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.href = "https://comercial-laltrait.aplataforma.com/pt/"; }, 500);
} else if(data > 0){
toastr.success("Operação realizada com sucesso!");
var tmpID = $('#tmpIDCobranca').val();
if (tmpID != '') {
$('#cobrancaCli'+tmpID).html(''+dataCobranca+' '+observacoes);
$('#cobrancaCliBtn'+tmpID).removeClass('btn-gray').addClass('btn-primary');
modalCobranca.hide();
} else {
setTimeout(function(){ window.location.reload(); }, 500);
}
}else if(data=="-98"){
toastr.error("Excedeu o máximo de tentativas permitas. O seu acesso foi limitado durante um tempo. Tente mais tarde");
}else{
toastr.error("Não foi possivel concluir o seu pedido.");
}
sendingForm('criarCobranca', false);
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
sendingForm('criarCobranca', false);
}
});
return false;
});
function bindInfoWindow(marker, map, infowindow, strDescription, id) {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(strDescription);
infowindow.open(map, marker);
});
}
var tmpFancyboxPadroesCliente;
function gerirPadroesClienteModal(idCliente,dataVisita,titulo,filtro = '') {
$('#tituloModalPC').html(base64ToUtf8(titulo));
$('#modalGerirPadroesClienteLoadingGlobal').show();
$('#modalGerirPadroesClienteContentGlobal').html('');
$('#save_cliente_padrao').hide();
$('#del_cliente_padrao').hide();
tmpFancyboxPadroesCliente = Fancybox.show([{
src: '#modalGerirPadroesCliente',
type: 'inline'
}]);
$.ajax({
type: 'POST',
url: '/paginas/produtos/padroes-cliente.php',
data: '&idCliente='+idCliente+'&dataVisita='+dataVisita+'&filtro='+filtro,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if (data=="-1") {
Fancybox.close();
} else {
$('#modalGerirPadroesClienteLoadingGlobal').hide();
$('#modalGerirPadroesClienteContentGlobal').html(data);
loadToolTips();
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
var tmpModalGerirPrecosProduto;
function gerirPrecosProdutoModal(idArtigo,titulo,filtro = '') {
$('#tituloModalPrecosProduto').html(base64ToUtf8(titulo));
$('#modalGerirPrecosProdutoLoadingGlobal').show();
$('#modalGerirPrecosProdutoContentGlobal').html('');
tmpModalGerirPrecosProduto = Fancybox.show([{
src: '#modalGerirPrecosProduto',
type: 'inline'
}]);
$.ajax({
type: 'POST',
url: '/paginas/produtos/gestao_precos_produto.php',
data: '&idArtigo='+idArtigo+'&filtro='+filtro,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if (data=="-1") {
Fancybox.close();
} else {
$('#modalGerirPrecosProdutoLoadingGlobal').hide();
$('#modalGerirPrecosProdutoContentGlobal').html(data);
loadToolTips();
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}
var tmpModalHistoricoAprovacoes;
function historicoAprovacoesModal(idCliente,idArtigo,titulo) {
$('#tituloModalHistoricoAprovacoes').html(base64ToUtf8(titulo));
$('#modalHistoricoAprovacoesLoadingGlobal').show();
$('#modalHistoricoAprovacoesContentGlobal').html('');
tmpModalHistoricoAprovacoes = Fancybox.show([{
src: '#modalHistoricoAprovacoes',
type: 'inline'
}]);
$.ajax({
type: 'POST',
url: '/paginas/produtos/historico_aprovacoes.php',
data: '&idCliente='+idCliente+'&idArtigo='+idArtigo,
beforeSend:function(xhr, settings){
settings.data += '&t=MjAyNi0wNS0wOCAxMw==&key=0ce047d694c014e336b247b7b6bb2ada144c53a8';
},
success:function(data){
if (data=="-99") {
toastr.error("A sua sessão de login terminou!");
setTimeout(function(){ window.location.reload(); }, 500);
} else if (data=="-1") {
Fancybox.close();
} else {
$('#modalHistoricoAprovacoesLoadingGlobal').hide();
$('#modalHistoricoAprovacoesContentGlobal').html(data);
loadToolTips();
}
},
error: function(data) {
toastr.error("Não foi possivel concluir o seu pedido.");
}
});
}