class CESTO {
static cestoDATA;
static etapa = 1;
static phoneInput1;
static phoneInput2;
static altura = $('.cartao1').outerHeight(true) + 400;
static morada_a_eliminar = 0;
static paises = null;
static inicio() {
let phoneInputField1 = document.querySelector("#morada_telefone");
CESTO.phoneInput1 = window.intlTelInput(phoneInputField1, {
initialCountry: "pt",
preferredCountries: ["pt", "es"],
utilsScript: "https://cdn.Pladon.Funcoes.pt/js/intlTelInput/utils.js",
});
let phoneInputField2 = document.querySelector("#entrega_tel");
CESTO.phoneInput2 = window.intlTelInput(phoneInputField2, {
initialCountry: "pt",
preferredCountries: ["pt", "es"],
utilsScript: "https://cdn.Pladon.Funcoes.pt/js/intlTelInput/utils.js",
});
//carrega dados gravados
CESTO.loadData();
CESTO.etapa = parseInt(CESTO.getValueAtIndex(1));
CESTO.passo(CESTO.etapa);
$('#btcontinuar').on('click', function () {
CESTO.proxpasso();
});
$('#nova-morada').on('shown.bs.modal', function () {
$('#morada_erro').html('');
FUNC.setInputFilter(document.getElementById("morada_codpostal"), function (value) {
return /^\d*\-?\d*$/.test(value);
});
FUNC.setInputFilter(document.getElementById("morada_telefone"), function (value) {
return /^\d*\+?\d*$/.test(value);
});
$("#morada_telefone").keyup(function () {
if ($(this).val() == '00') {
$(this).val('+');
}
});
if ($('#morada_id').val() == '0') {
$('#morada_titulo').html('Nova Morada');
$('#bt_grava_morada').html('Inserir');
}
else {
$('#morada_titulo').html('Alterar Morada');
$('#bt_grava_morada').html('Alterar');
}
$('#morada_codpostal').keyup(function () {
if ($('#morada_pais').val() == 'Portugal') {
let _cod = $('#morada_codpostal').val();
let _final = '';
for (var i = 0; i < _cod.length; i++) {
let _char = _cod.charAt(i);
if (i == 4) {
_final += '-';
if (!isNaN(_char)) {
_final += _char;
}
}
else {
if (!isNaN(_char)) {
_final += _char;
}
}
}
$('#morada_codpostal').val(_final);
}
});
});
$('#bt_grava_morada').on('click', function () {
CESTO.gravamorada();
});
$('#modal-aderir').on('shown.bs.modal', function () {
fetch(config.apiUrl + '/condicoespontos')
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.text();
})
.then(res => {
$('#textocondicoes').html(res);
});
});
CESTO.loadpaises();
}
static saveData() {
localStorage.setItem('cestoDATA', JSON.stringify(CESTO.cestoDATA));
}
static loadData() {
let _data = localStorage.getItem('cestoDATA');
if (_data) {
CESTO.cestoDATA = JSON.parse(_data);
}
else {
CESTO.cestoDATA = {
faturacao: {
id: -1
},
entrega: {
id: -1,
tel: ''
},
formaentrega: -1,
cesto: null,
listamoradas: [],
listaformasentrega: []
};
}
if (!CESTO.cestoDATA.entrega.tel) {
CESTO.cestoDATA.entrega = {
id: -1,
tel: ''
};
}
}
static loadpaises() {
fetch(config.apiUrl + '/paises')
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(res => {
CESTO.paises = res;
res.todos.forEach((el) => {
$('.paises').append('');
});
});
}
static validacaoinicio() {
$('#load1').addClass('active');
$('#btcontinuar').prop('disabled', true);
}
static validacaoconcluida() {
$('#load1').removeClass('active');
$('#btcontinuar').prop('disabled', false);
}
static proxpasso() {
CESTO.validacaoinicio();
switch (CESTO.etapa) {
case 1:
if ($('#dadosfaturacao .op.active').length) {
CESTO.passo(2);
}
else {
CESTO.erroContinuar('Selecione ou crie os dados de faturação.');
CESTO.validacaoconcluida();
}
break;
case 2:
if ($('#dadosentrega .op.active').length) {
if (CESTO.cestoDATA.entrega.id == 0) {
if (CESTO.paises.matecamen == true) {
CESTO.passo(3);
}
else {
CESTO.erroContinuar('Lamentamos, mas neste momento não é possível a entrega no nosso parceiro do Porto!
Qualquer dúvida ou questão entre em contacto com o apoio ao cliente.');
CESTO.validacaoconcluida();
}
}
else {
let _entrega = CESTO.cestoDATA.listamoradas.find(x => x.id == CESTO.cestoDATA.entrega.id);
let _pais_entrega = _entrega.pais;
if (CESTO.paises.ativos.includes(_pais_entrega)) {
if (_pais_entrega.toLowerCase == 'portugal' && _entrega.codpostal.startsWith(9) && CESTO.paises.ilhas == false) {
CESTO.erroContinuar('Lamentamos, mas neste momento não é possível a entrega nas Ilhas!
Qualquer dúvida ou questão entre em contacto com o apoio ao cliente.');
CESTO.validacaoconcluida();
}
else {
CESTO.passo(3);
}
}
else {
CESTO.erroContinuar('Lamentamos, mas neste momento não é possível a entrega em ' + _pais_entrega + '!
Qualquer dúvida ou questão entre em contacto com o apoio ao cliente.');
CESTO.validacaoconcluida();
}
}
}
else {
CESTO.erroContinuar('Selecione ou crie os dados de entrega.');
CESTO.validacaoconcluida();
}
break;
case 3:
if ($('#formas_de_entrega .op.active').length) {
if (!CESTO.phoneInput2.isValidNumber()) {
CESTO.erroContinuar('Por favor introduza o seu número de telemóvel.');
$('#entrega_tel').focus();
CESTO.validacaoconcluida();
}
else {
let entrega_tel = FUNC.replaceAll(CESTO.phoneInput2.getNumber(), '+351', '');
CESTO.cestoDATA.entrega.tel = entrega_tel;
CESTO.saveData();
CESTO.passo(4);
}
}
else {
CESTO.erroContinuar('Selecione uma forma de entrega.');
CESTO.validacaoconcluida();
}
break;
case 4:
CESTO.preorder();
break;
case 5:
break;
}
}
static erroContinuar(texto) {
$('#msg-erro').html(texto);
$('#modal-erro').modal('show');
}
static passo(i) {
$('.caixaresumo').addClass('hide');
$('#btcontinuar span').html('Continuar');
CESTO.etapa = i;
let _url = window.location.href;
_url = FUNC.replaceAll(_url, 'step-' + CESTO.getValueAtIndex(1), 'step-' + CESTO.etapa);
history.pushState({}, "", _url);
$('#cartoes').removeClass('passo1');
$('#cartoes').removeClass('passo2');
$('#cartoes').removeClass('passo3');
$('#cartoes').removeClass('passo4');
$('#cartoes').removeClass('passo5');
$('#cartoes').addClass('passo' + i);
CESTO.altura = $('.cartao' + CESTO.etapa).outerHeight(true) + 300;
let t;
for (t = 1; t < CESTO.etapa; t++) {
$('#passo' + t).removeClass('current');
$('#passo' + t).addClass('visited');
}
for (t = CESTO.etapa; t < 6; t++) {
$('#passo' + t).removeClass('visited');
$('#passo' + t).removeClass('current');
}
$('#passo' + CESTO.etapa).addClass('current');
$("html, body").animate({ scrollTop: 0 }, "slow");
$('#areacentral').css("min-height", CESTO.altura);
switch (CESTO.etapa) {
case 1:
$('.caixaresumo').removeClass('hide');
CESTO.getMoradasFaturacao();
break;
case 2:
$('.caixaresumo').removeClass('hide');
CESTO.getMoradasEntrega();
break;
case 3:
$('.caixaresumo').removeClass('hide');
if (CESTO.cestoDATA.entrega.id == 0) {
$("#entrega_tel_caixa").removeClass('hide');
if (CESTO.cestoDATA.entrega.tel == '') {
if (CESTO.cestoDATA.faturacao.id == 0) {
//consultar tel na ficha do cliente
fetch(config.apiUrl + '/cli')
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(res => {
CESTO.cestoDATA.entrega.tel = res.telefone;
if (CESTO.cestoDATA.entrega.tel.length == 9) {
CESTO.phoneInput2.setNumber('+351' + CESTO.cestoDATA.entrega.tel);
}
else {
CESTO.phoneInput2.setNumber(CESTO.cestoDATA.entrega.tel);
}
});
}
else {
//obter tel na morada selecionada
let add = CESTO.cestoDATA.listamoradas.find(o => o.id == CESTO.cestoDATA.faturacao.id);
CESTO.cestoDATA.entrega.tel = add.tel;
if (CESTO.cestoDATA.entrega.tel.length == 9) {
CESTO.phoneInput2.setNumber('+351' + CESTO.cestoDATA.entrega.tel);
}
else {
CESTO.phoneInput2.setNumber(CESTO.cestoDATA.entrega.tel);
}
}
}
else {
if (CESTO.cestoDATA.entrega.tel.length == 9) {
CESTO.phoneInput2.setNumber('+351' + CESTO.cestoDATA.entrega.tel);
}
else {
CESTO.phoneInput2.setNumber(CESTO.cestoDATA.entrega.tel);
}
}
}
else {
//obter tel na morada selecionada
let add = CESTO.cestoDATA.listamoradas.find(o => o.id == CESTO.cestoDATA.entrega.id);
CESTO.cestoDATA.entrega.tel = add.tel;
if (CESTO.cestoDATA.entrega.tel.length == 9) {
CESTO.phoneInput2.setNumber('+351' + CESTO.cestoDATA.entrega.tel);
}
else {
CESTO.phoneInput2.setNumber(CESTO.cestoDATA.entrega.tel);
}
//esconde tel
$("#entrega_tel_caixa").addClass('hide');
}
CESTO.getOpcoesEntrega();
break;
case 4:
CESTO.getOpcoesEntrega();
CESTO.getResumo();
break;
case 5:
break;
}
CESTO.loadCestoItens();
}
static preorder() {
fetch(config.apiUrl + '/encomendasopen')
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(res => {
if (res == 1) {
$('#encomendasopen').modal('show');
CESTO.validacaoconcluida();
}
else {
CESTO.order();
}
});
}
static confirmorder() {
$('#encomendasopen').modal('hide');
CESTO.order();
}
static order() {
CESTO.validacaoinicio();
let encomenda = {
faturacao: CESTO.cestoDATA.faturacao.id,
entrega: CESTO.cestoDATA.entrega.id,
telefone: CESTO.cestoDATA.entrega.tel,
formaentrega: CESTO.cestoDATA.formaentrega,
obs: $("#observacoes").val()
};
$.ajax({
url: config.apiUrl + "/encomendar",
data: {
encomenda: JSON.stringify(encomenda)
},
dataType: "json",
type: "POST",
success: function (result) {
if (result.erro == false) {
window.location.href = '/cesto/encomenda-finalizada/' + result.id;
}
else {
CESTO.erroContinuar(result.msg);
CESTO.validacaoconcluida();
}
},
error: function (xhr, status, error) {
alert('Ocorreu um erro!\nCódigo:' + xhr.status);
}
});
}
//cesto itens
static loadCestoItens() {
fetch(config.apiUrl + '/bas')
.then(response => {
if (!response.ok) {
window.location.href = '/cesto';
}
return response.json();
})
.then(bas => {
CESTO.cestoDATA.cesto = bas;
CESTO.saveData();
CESTO.showCestoItens();
});
}
static showCestoItens() {
let res = '';
CESTO.cestoDATA.cesto.ProductList.forEach((prod) => {
res += CESTO.makeProdHtml(prod);
});
//cupao
if (CESTO.cestoDATA.cesto.Total_descontos != 0 && CESTO.cestoDATA.cesto.cupao != null) {
let _html = `
[` + CESTO.cestoDATA.cesto.cupao.codigo + `] Remover
Ref. CUPAO
€ -` + FUNC.FormatEuro(CESTO.cestoDATA.cesto.Total_descontos) + ` / un.
' + CESTO.cestoDATA.cesto.cupao_msg + '
'; $('#cupaoMSG').html(_html); } //pontos if (CESTO.cestoDATA.cesto.Total_descontos != 0 && CESTO.cestoDATA.cesto.pontos != null) { let _html = `DESCONTO DE PONTOS Remover
Ref. PONTOS
€` + FUNC.FormatEuro(CESTO.cestoDATA.cesto.pontos.pontos_valor) + ` / un.
` + prod.info.name_pt + `
Ref. ` + prod.sku + `
` + promo + `€ ` + prod.price.atual + ` / un.
' + custo + '
Ainda não aderiu aos Pontos Printflow?
Adira já e ganhe {pontos_novos} pontos com esta encomenda. |
|---|
Pontos PrintflowCom esta encomenda irá ganhar +{pontos_novos} pontos. |
|---|
| {destaque} |
Pontos PrintflowCom esta encomenda irá ganhar +{pontos_novos} pontos.
Irá descontar:
{pontos_usados} pontos |
|---|
| {destaque} |
Ultrapassou o limite de pontos que pode descontar .
"); } else { $("#pontosMSG").html("Ocorreu um erro!
Por favor tente novamente.
Se o problema persistir contacte o apoio ao cliente.
Ocorreu um erro. Por favor verifique o estado da sua conta.
Caso o problema persista contacte o apoio ao cliente.
Para aderir ao Programa de Pontos tem de aceitar os Termos e Condições!
"); } } //cupoes static validarCupao() { $("#cupaoMSG").html(""); $.ajax({ url: config.apiUrl + "/validacupao", type: "POST", data: { 'cupao': $("#cupao").val(), 'total_artigos': CESTO.cestoDATA.cesto.Total_artigos, 'total': CESTO.cestoDATA.cesto.Total + CESTO.cestoDATA.cesto.Total_descontos }, dataType: 'text', success: function (result) { if (result == "OK") { CESTO.cestoDATA.cupao = result; CESTO.saveData(); CESTO.passo(4); } else { $("#cupaoMSG").html("" + result + "
"); } } }); } static removeCupao() { fetch(config.apiUrl + '/removecupao') .then(response => { if (!response.ok) { throw new Error("HTTP error " + response.status); } return response.text(); }) .then(res => { CESTO.passo(4); }); } static subscrevernewsletter() { $("#newsletter_results").html(''); if ($("#newssubscribe-check").is(':checked')) { CESTO.subscrevernewsletter1(); } else { $("#newsletter_results").html('Para subscrever tem de dar consentimento ao tratamento de dados.
'); } } static subscrevernewsletter1() { fetch(config.apiUrl + '/subscrevernewsletter') .then(response => { if (!response.ok) { throw new Error("HTTP error " + response.status); } return response.text(); }) .then(res => { FUNC.fechaModal(); CESTO.passo(4); }); } static sharebuttons() { let link = $('#referralLink').val(); let msg = $('#msg_convite').val(); let _url = 'https://www.facebook.com/sharer.php?s=100&p[title]=Printflow&p[summary]={text}&p[url]={url}&p[images][0]=https://www.printflow.pthttps://www.printflow.pt/images/logo-printflow.png'; _url = FUNC.replaceAll(_url, '{url}', link); _url = FUNC.replaceAll(_url, '{text}', msg); $('.s_facebook').attr('href', _url); _url = 'https://twitter.com/intent/tweet?url={url}&text={text}'; _url = FUNC.replaceAll(_url, '{url}', link); _url = FUNC.replaceAll(_url, '{text}', FUNC.replaceAll(msg, link, '')); $('.s_twitter').attr('href', _url); _url = 'https://api.whatsapp.com/send?phone=&text={text}'; _url = FUNC.replaceAll(_url, '{text}', msg); $('.s_whatsapp').attr('href', _url); _url = 'fb-messenger://share/?link={url}'; _url = FUNC.replaceAll(_url, '{url}', link); $('.s_messenger').attr('href', _url); _url = 'mailto:?subject=&body={text}'; _url = FUNC.replaceAll(_url, '{text}', msg); $('.s_email').attr('href', _url); $('.socialIcon a').click(function () { var b = screen.width , d = screen.height , e = c.width ? c.width : b - .2 * b , f = c.height ? c.height : d - .2 * d , g = b / 2 - e / 2 , h = d / 2 - f / 2 , i = "toolbar=0,status=0,width=" + e + ",height=" + f + ",top=" + h + ",left=" + g; return window.open($(this).attr("href"), "", i) && !1; }); } static copiarCodigo() { $('#referralLink').select(); var copiar = document.execCommand('copy'); if (copiar) { alert('Copiado'); } else { alert('Erro ao copiar, seu navegador pode não ter suporte a essa função.'); } return false; } /*common functions*/ static validaContribuinte(contribuinte) { var temErro = 0; if ( contribuinte.substr(0, 1) != '1' && contribuinte.substr(0, 1) != '2' && contribuinte.substr(0, 1) != '3' && contribuinte.substr(0, 2) != '45' && contribuinte.substr(0, 1) != '5' && contribuinte.substr(0, 1) != '6' && contribuinte.substr(0, 2) != '70' && contribuinte.substr(0, 2) != '71' && contribuinte.substr(0, 2) != '72' && contribuinte.substr(0, 2) != '77' && contribuinte.substr(0, 2) != '79' && contribuinte.substr(0, 1) != '8' && contribuinte.substr(0, 2) != '90' && contribuinte.substr(0, 2) != '91' && contribuinte.substr(0, 2) != '98' && contribuinte.substr(0, 2) != '99' ) { temErro = 1; } var check1 = contribuinte.substr(0, 1) * 9; var check2 = contribuinte.substr(1, 1) * 8; var check3 = contribuinte.substr(2, 1) * 7; var check4 = contribuinte.substr(3, 1) * 6; var check5 = contribuinte.substr(4, 1) * 5; var check6 = contribuinte.substr(5, 1) * 4; var check7 = contribuinte.substr(6, 1) * 3; var check8 = contribuinte.substr(7, 1) * 2; var total = check1 + check2 + check3 + check4 + check5 + check6 + check7 + check8; var divisao = total / 11; var modulo11 = total - parseInt(divisao) * 11; if (modulo11 == 1 || modulo11 == 0) { comparador = 0; } else { comparador = 11 - modulo11; } var ultimoDigito = contribuinte.substr(8, 1) * 1; if (ultimoDigito != comparador) { temErro = 1; } if (temErro == 1) { return false; } else { return true; } } static getValueAtIndex(index) { var str = window.location.href; return str.split("-")[index]; } static stringContainsNumber(_string) { return /\d/.test(_string); } static eventos_checkout() { let itens = []; $('#linhasCesto .CartProduct').each(function () { let price = parseFloat($(this).parent().find('.item_price').html()); price = FUNC.FormatEuro(price, 2); let item = { item_id: $(this).parent().find('.item_id').html(), item_name: $(this).parent().find('.item_name').html(), price: price, currency: 'EUR', quantity: parseInt($(this).parent().find('.item_qde').html()) }; itens.push(item); }); if (CESTO.etapa == 1) { try { GA4.event.begin_checkout(itens); } catch (error) { console.error(error); } } if (CESTO.etapa == 4) { try { let forma_entrega_nome = $('#entrega_descricao' + CESTO.cestoDATA.formaentrega).html(); GA4.event.add_shipping_info(itens, CESTO.cestoDATA.cesto.Total_portes, forma_entrega_nome); } catch (err) { console.log(err); } } } } if (document.getElementsByTagName) { let inputElements = document.getElementsByTagName("input"); for (i = 0; inputElements[i]; i++) { inputElements[i].setAttribute("autocomplete", "xyz"); } } class JSpage { static EXEMPLO = class { static ConfigInicial() { } static Config() { } static filtraTabela() { } static afterLoadTabela() { } static NovoItem() { } static AfterGetData() { } static ValidaForm(continua) { continua(); } static ClickItem() { } static AfterSave(res) { } } static CHECKOUT = class { static ConfigInicial() { console.log('checkout'); } static Config() { CESTO.inicio(); } } static CHECKOUTEXPRESS = class { static ConfigInicial() { console.log('checkout-EXPRESS'); } static Config() { } } } $(document).ready(function () { LOADPAGES.LoadInicial(config.anonimo); }); function next() { LOADPAGES.LoadInicial(config.anonimo); }