var agco = agco || {}; console.log('valtra js'); agco.global = function () { var self = { token: '', site: 'valtra', notificationPage: 1, readNotificationID: '', endpoint: { // notification: "v1/notification/list?post_per_page=5&page=", notification: "v1/notification/list", notificationRead: 'v1/notification/update', minMaxPoint: 'product/price/min-max', postLike: 'v1/post/emoji', }, notificationElementID: '', notificationElementLink: '', selectedpost: '', ready: function () { self.load(); }, load: function () { self.eventHandler(); self.updateToken(); self.checkFirstLogin(); self.highlightNav(); self.getMinMaxPoints(); if (jQuery('.notification-content').length) { self.getNotification(); self.getInfiniteScroll(); } if (jQuery('#notification-chck1').length) { self.notificationToggle(); } if (jQuery('.card-light-gray').length) { self.checkCanLikePost(); } }, checkCanLikePost: function () { if (!jQuery('.product-like-container').length) { return false; } jQuery(document).on('click', '.card-light-gray .product-like-container', self.postLike); }, postLike: function () { var selectedPost = jQuery(this).data('post_id'); let endpoint = self.endpoint.postLike; let emojiData = { "emoji_id": '1', "post_id": selectedPost.toString(), "cpf": agco.helper.getCpf() } self.selectedPost = this; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', emojiData, true, self.successCallBackAddReaction, self.errorCallBackAddReaction); }, successCallBackAddReaction: function (success) { agco.helper.loader('hide'); if (!success || !success.data) { jQuery(self.selectedPost).removeClass('active'); } else { jQuery(self.selectedPost).addClass('active'); } }, errorCallBackAddReaction: function (error) { agco.helper.loader('hide'); }, notificationToggle: function () { if (jQuery('.page-template-page-ecom-orders').length || jQuery('.single-product').length || jQuery('body.archive').length || jQuery('.page-template-page-ecom-pagemento').length || jQuery('.page-template-page-cart').length || jQuery('.page-template-page-extrato').length || jQuery('.page-template-page-ecom-my-vouchers').length || jQuery('.page-template-page-checkout').length) { if (location.href.includes('/selos') || location.href.includes('/mission') || location.href.includes('/news') || location.href.includes('/skytv')) { self.applyBasicSubMenuFunction(); return false; } self.applyBasicSubMenuFunction(); return false; jQuery(document).on('click', '#notification-chck1', self.setActiveNotification); jQuery(document).on('click', '#gallery-chck1', self.setActiveGalleryList); self.cartCardShow(); self.galleryCardHide(); self.notificationCardHide(); jQuery(document).click(function (event) { var $target = jQuery(event.target); if ('notification-id' == jQuery($target).attr('id')) { self.galleryCardHide(); self.cartCardShow(); } else if ('cart-id' == jQuery($target).attr('id')) { self.notificationCardHide(); self.galleryCardHide(); } else if ('gallery-id' == jQuery($target).attr('id')) { self.notificationCardHide(); self.cartCardShow(); } else if (!$target.closest('#notification-chck1').length && jQuery('.notification-content').hasClass('active')) { event.stopPropagation(); self.notificationCardHide(); self.cartCardShow(); } else if (!$target.closest('#gallery-chck1').length && jQuery('.gallery-contents').hasClass('active')) { self.galleryCardHide(); self.cartCardShow(); } }); } else { self.applyBasicSubMenuFunction(); } }, applyBasicSubMenuFunction: function () { jQuery(document).on('click', '#notification-chck1', self.setActiveNotification); jQuery(document).on('click', '#cart-chck1', self.setActiveCartList); // jQuery(document).on('click', '#gallery-chck1', self.setActiveGalleryList); jQuery(document).click(function (event) { var $target = jQuery(event.target); if ('notification-id' == jQuery($target).attr('id')) { self.cartCardHide(); self.galleryCardHide(); } else if ('cart-id' == jQuery($target).attr('id')) { self.notificationCardHide(); self.galleryCardHide(); } else if ('gallery-id' == jQuery($target).attr('id')) { self.notificationCardHide(); self.cartCardHide(); } else if (!$target.closest('#notification-chck1').length && jQuery('.notification-content').hasClass('active')) { event.stopPropagation(); self.notificationCardHide(); } else if (!$target.closest('#cart-chck1').length && jQuery('.card-content').hasClass('active')) { self.cartCardHide(); } else if (!$target.closest('#gallery-chck1').length && jQuery('.gallery-contents').hasClass('active')) { self.galleryCardHide(); } }); }, setActiveNotification: function (event) { event.stopPropagation(); if (!jQuery('.notification-content').hasClass('active')) { self.notificationCardShow(); self.cartCardHide(); self.galleryCardHide(); } else { self.notificationCardHide(); } }, setActiveCartList: function (event) { event.stopPropagation(); if (!jQuery('.card-content').hasClass('active')) { self.cartCardShow(); self.galleryCardHide(); self.notificationCardHide(); } else { self.cartCardHide(); } }, setActiveGalleryList: function (event) { event.stopPropagation(); if (!jQuery('.gallery-contents').hasClass('active')) { self.galleryCardShow(); self.notificationCardHide(); self.cartCardHide(); } else { self.galleryCardHide(); } }, notificationCardShow: function () { jQuery('#notification-id').addClass('active'); jQuery('.notification-content').addClass('active'); jQuery('.notification-content').show(); }, notificationCardHide: function () { jQuery('#notification-id').removeClass('active'); jQuery('.notification-content').removeClass('active'); jQuery('.notification-content').hide(); }, cartCardShow: function () { jQuery('#cart-id').addClass('active'); jQuery('.card-content').addClass('active'); jQuery('.card-content').show(); }, cartCardHide: function () { jQuery('#cart-id').removeClass('active'); jQuery('.card-content').removeClass('active'); jQuery('.card-content').hide(); }, galleryCardShow: function () { jQuery('#gallery-id').addClass('active'); jQuery('.gallery-contents').addClass('active'); jQuery('.gallery-contents').show(); }, galleryCardHide: function () { jQuery('#gallery-id').removeClass('active'); jQuery('.gallery-contents').removeClass('active'); jQuery('.gallery-contents').hide(); }, eventHandler: function () { jQuery(document).on('click', '.notification-content li.unread', self.markAsReadNotification); jQuery(document).on('click', '.notification-content li a', self.preventPageLoad); }, preventPageLoad: function (e) { e.preventDefault(); var parentId = jQuery(this).parents('li.notification-list').attr('id'); var link = jQuery(this).attr('href'); if (!link) { return false; } if (jQuery(this).parents('li.notification-list').hasClass('unread')) { self.notificationElementID = parentId; self.notificationElementLink = link; self.markAsRead(); } else { if (link.includes(window.location.hostname)) { window.location.href = link; } else { window.open(link, "_blank"); } } }, markAsReadNotification: function () { var parentId = jQuery(this).attr('id'); self.notificationElementID = parentId; self.markAsRead(); }, getMinMaxPoints: function () { if (!self.token) { return false; } if (document.cookie.split(';').filter(function (item) { return item.trim().indexOf('minMax=') == 0 }).length) { } else { var endpoint = self.endpoint.minMaxPoint; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'GET', '', true, agco.global.minMaxSuccess, agco.global.minMaxError); } }, minMaxSuccess: function (success) { agco.helper.loader('hide'); if (success && success.code != 'get_product_min_max_price_success') { return false; } var data = JSON.stringify(success.data); var date = new Date(); var expireDate = new Date(date.setDate(date.getDate() + 7)); expireDate = expireDate.toUTCString(); document.cookie = "minMax=" + data + "; expires=" + expireDate + "; secure=true"; agco.shop.loadRangeSlider(); }, minMaxError: function (error) { agco.helper.loader('hide'); }, highlightNav: function () { var locationHref = location.href; if (locationHref.indexOf('/program/') > 0) { jQuery('a[href="' + location.origin + '/program/"').addClass('highlighted'); } else if (locationHref.indexOf('/minha-conta/') > 0) { jQuery('a[href="/minha-conta"]').addClass('highlighted'); } else if (locationHref.indexOf('/extrato/') > 0) { jQuery('a[href="/extrato"]').addClass('highlighted'); } else if (locationHref.indexOf('/mission/') > 0) { jQuery('a[href="/mission"]').addClass('highlighted'); } else if (locationHref.indexOf('/skytv/') > 0) { jQuery('a[href="/skytv"]').addClass('highlighted'); } else if (locationHref.indexOf('/news/') > 0 || locationHref.indexOf('/photos/') > 0 || locationHref.indexOf('/calendar/') > 0 || locationHref.indexOf('/aprenda/') > 0) { jQuery('a[href="/news"]').addClass('highlighted'); } else if (locationHref.indexOf('/fale-conosco/') > 0) { jQuery('a[href="/fale-conosco"]').addClass('highlighted'); } else if (locationHref.indexOf('/arrancada-regulamento/') > 0) { jQuery('a[href="/arrancada-regulamento"]').addClass('highlighted'); } else { if (jQuery('.mega-menu-container').length) { jQuery('nav.navbar a[href="/shop/?featured=true"]').addClass('highlighted'); } } }, markAsRead: function () { if (!self.notificationElementID) { return false; } var endpoint = self.endpoint.notificationRead; var elementId = self.notificationElementID; self.notificationElementID = ''; var data = { 'notification_id': elementId, 'viewed': true, }; self.readNotificationID = elementId; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', data, true, agco.global.notificationMarkAsReadSuccess, agco.global.notificationMarkAsReadError); }, notificationMarkAsReadSuccess: function (success) { // console.log(success); var link = self.notificationElementLink; self.notificationElementLink = ''; if (jQuery('.notification-content .count').length) { var notificationLength = jQuery('.notification-content .count').html(); jQuery('.notification-content .count').html(notificationLength - 1); } if (self.readNotificationID) { jQuery('#' + self.readNotificationID).removeClass('unread'); jQuery('#' + self.readNotificationID).addClass('read'); self.readNotificationID = ''; } agco.helper.loader('hide'); if (link.includes(window.location.hostname)) { window.location.href = link; } else { window.open(link, "_blank"); } }, notificationMarkAsReadError: function (error) { // console.log(error); self.notificationElementLink = ''; self.readNotificationID = ''; agco.helper.loader('hide'); }, getInfiniteScroll: function () { jQuery('.notification-content ul').on('scroll', function () { if (jQuery(this).scrollTop() === 0) { self.notificationPage = 1; self.getNotification(); } // Condition to call the function when scroll end is reached // if (jQuery(this).scrollTop() + jQuery(this).innerHeight() >= jQuery(this)[0].scrollHeight) { // self.getNotification(); // } }); }, getNotification: function () { if (!globalJsData.token) { return false; } // var endpoint = self.endpoint.notification + self.notificationPage; var endpoint = self.endpoint.notification; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'GET', {}, true, agco.global.getNotificationSuccess, agco.global.getNotificationError); }, getNotificationSuccess: function (success) { // console.log(success); agco.helper.loader('hide'); if (success.data.notification_count == 0) { jQuery('.notification-item-count').css("display", "none"); } if (success.code !== "get_notification_success" || !success.data.notification.length) { return false; } if (self.notificationPage == 1) { jQuery('.notification-content ul li').remove(); } self.notificationPage++; if (parseInt(success.data.notification_count) >= 0) { jQuery('.notification-content .count').html(success.data.notification_count); } success.data.notification.forEach(function (element) { if (jQuery('#' + element.ID).length) { } else { var notificationClass = 'notification-list'; if (element.viewed) { notificationClass = notificationClass + ' read'; jQuery('.notification-item-count').css("display", "none"); } else { notificationClass = notificationClass + ' unread'; } var notificationImage = jQuery('', { src: 'https://i2.wp.com/betterinternet.law.stanford.edu/wp-content/uploads/2016/11/Legal-Icons-Navocado-task-badges-follow-a-checklist.png?resize=150%2C150' }); var notificationChildImageContainer = jQuery('
', { class: 'img', }); var notificationcontent = jQuery('
', { html: element.heading }); // var notificationReadcontent = jQuery('
', { // }); var notificationlink = jQuery('', { href: element.link, html: element.link_text, }); moment.locale('pt'); // var momentDate = moment(element.post_date); // var postDateWithFormat = momentDate.format("DD") + " de " + momentDate.format("MMM") + " às " + momentDate.format("hh:mm"); // var momentDate = moment(element.post_date); // var postDateWithFormat = momentDate.fromNow(true); var notificationChildTimeContainer = jQuery('', { html: element.time_difference_string }); var notificationChildTextContainer = jQuery('
', { class: 'content', }); var notificationChildContainer = jQuery('
', { class: 'flex notification', }); var notificationHolder = jQuery('
  • ', { class: notificationClass, id: element.ID, }); jQuery(notificationcontent).appendTo(notificationChildTextContainer); jQuery(notificationlink).appendTo(notificationChildTextContainer); jQuery(notificationChildTimeContainer).appendTo(notificationChildTextContainer); jQuery(notificationChildTextContainer).appendTo(notificationChildContainer); jQuery(notificationImage).appendTo(notificationChildImageContainer); jQuery(notificationChildImageContainer).appendTo(notificationChildContainer); jQuery(notificationChildContainer).appendTo(notificationHolder); jQuery(notificationHolder).appendTo('.notification-content ul'); } }); }, getNotificationError: function (error) { // console.log(error); agco.helper.loader('hide'); }, checkFirstLogin: function () { if (typeof (globalJsData) == "undefined") { return false; } self.updateToken(); // if (globalJsData.user.data.user_login === "88602771169") { // globalJsData.first_time_login = 1 // } if (globalJsData && globalJsData.is_profile_complete == true) { if (location.href.indexOf('/minha-conta/') > 0) { // self.toggleToPasswordReset(); return false; } var navigateURL = window.location.protocol + "//" + document.location.host + "/minha-conta/"; window.open(navigateURL, "_self"); } }, updateToken: function () { if (globalJsData && globalJsData.token) { self.token = globalJsData.token; } }, toggleToPasswordReset: function () { if (jQuery() && jQuery().steps) { setTimeout(function () { jQuery('[href="#next"]').click(); }, 400); setTimeout(function () { jQuery('[href="#next"]').click(); }, 700); } else { setTimeout(function () { self.toggleToPasswordReset(); }, 200); } }, }; return self; }(); jQuery(document).ready(function () { agco.global.ready(); }); agco.Dashboard = function () { var self = { vendasList: '56', endpoint: { 'performance': 'v1/reports/dash/selinga', 'selos': 'v1/reports/dash/selos_count', 'courseCount': 'v1/reports/dash/course_count', }, ready: function () { if (jQuery('.home').length) { self.load(); } if (jQuery('.page-template-page-home').length) { self.loadBannerSlick(); } if (jQuery('.home-post-slider').length) { self.loadPostSlick(); } if (jQuery('.user-point-details').length) { self.getSeloesCount(); self.getCourseCount(); } if (jQuery('.monthly-sales-bar-details').length) { self.loadDetailsForChart(); } if (jQuery('.category-detail .your-category-icon').length) { self.highlightBadges(); } else if (jQuery('.your-category-icon').length) { self.highlightBadgesShop(); } }, loadDetailsForChart: function () { jQuery('.monthly-sales-bar-details').html(''); self.printchart(); }, highlightBadges: function () { var role; jQuery('.category-name').html(''); if (typeof globalJsData.user.roles == "object") { role = globalJsData.user.roles[1]; } else if (typeof globalJsData.user.roles == "array") { role = globalJsData.user.roles[0]; } else { return false; } if (role == "customer") { jQuery('.badge-icon').addClass('active'); jQuery('.category-name').html('PRATA'); } else { } }, highlightBadgesShop: function () { var role; if (typeof globalJsData.user.roles == "object") { role = globalJsData.user.roles[1]; } else if (typeof globalJsData.user.roles == "array") { role = globalJsData.user.roles[0]; } else { return false; } if (role == "customer") { jQuery('.badge-icon').attr('hidden', false); } else { } }, printchart: function () { jQuery('.user-performance-detail').attr('hidden', true); return false; if (typeof Chart !== 'undefined') { var ctx = document.getElementById('myChart').getContext('2d'); var valueList = [1458, 4568, 2641, 2759, 3458, 1615]; var largest = valueList[0]; var backgroundColor; var borderColor; if (agco.global.site == 'massey') { borderColor = 'rgba(239, 9, 34, 1)'; backgroundColor = 'rgba(196, 18, 48, 1)'; } else { borderColor = 'rgb(255,194,24,1)'; backgroundColor = 'rgb(251,186,0,1)'; } for (var i = 0; i < valueList.length; i++) { if (largest < valueList[i]) { largest = valueList[i]; } } var maxValue = largest + 1000; var backgroundElementColor = []; for (var i = 0; i < valueList.length; i++) { backgroundElementColor.push(backgroundColor); } var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["JAN", "FEV", "MAR", "ABR", "MAI", "JUN", "JUL", "AGO", "SET"], datasets: [{ label: '# of Votes', data: valueList, backgroundColor: backgroundElementColor, borderColor: backgroundElementColor, borderWidth: 1, hoverBackgroundColor: borderColor, hoverBorderColor: borderColor, }] }, options: { legend: { display: false }, scales: { yAxes: [{ ticks: { beginAtZero: true, max: maxValue } }], xAxes: [{ gridLines: { display: false, }, }], }, tooltips: { yAlign: 'bottom', titleFontSize: 25, bodyFontSize: 15, custom: function (tooltip) { if (!tooltip) return; // disable displaying the color box; tooltip.displayColors = false; }, callbacks: { label: function (tooltipItem, chart) { var dum = []; dum.push(agco.Dashboard.vendasList + " vendas ") dum.push(agco.helper.ptBrNumberFormat(tooltipItem.value, false) + ' pts') return dum }, title: function (tooltipItem, data) { // console.log(data); return agco.helper.shortMonthToFullMoths[tooltipItem[0].label]; } }, backgroundColor: borderColor, cornerRadius: 0 } } }); } else { setTimeout(() => { self.printchart(); }, 250); } }, load: function () { // console.log(agco.helper.shortMonthToFullMoths[tooltipItem.label] + ' ' + agco.Dashboard.vendasList + " vendas " + agco.helper.ptBrNumberFormat(tooltipItem.value, false) + ' pts'); // return agco.helper.shortMonthToFullMoths[tooltipItem.label] + ' ' + agco.Dashboard.vendasList + " vendas " + agco.helper.ptBrNumberFormat(tooltipItem.value, false) + ' pts'; self.eventHandler(); self.loadPostSlick(); self.loadBannerSlick(); self.getPerformanceDetais(); }, getSeloesCount: function () { var endpoint = self.endpoint.selos; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'GET', {}, true, agco.Dashboard.getSeloesCountSuccess, agco.Dashboard.getSeloesCountError); }, getSeloesCountSuccess: function (success) { if (!success) { return false; } jQuery('h3.selos-points').html(success); }, getSeloesCountError: function (error) { }, getCourseCount: function () { var endpoint = self.endpoint.courseCount; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'GET', {}, true, agco.Dashboard.getCourseCountSuccess, agco.Dashboard.getCourseCountError); }, getCourseCountSuccess: function (success) { if (!success) { return false; } jQuery('h3.training-points').html(success); }, getCourseCountError: function (error) { }, eventHandler: function () { }, loadPostSlick: function () { if (jQuery() && jQuery().slick && jQuery('.home-post-slider').length) { jQuery('.home-post-slider').slick({ infinite: true, slidesToShow: 3, slidesToScroll: 1, swipeToSlide: true, swipe: true, arrows: true, responsive: [ { breakpoint: 1500, settings: { slidesToShow: 3, slidesToScroll: 1 } }, { breakpoint: 1180, settings: { slidesToShow: 2, slidesToScroll: 1 } }, { breakpoint: 730, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] }); } else { setTimeout(function () { self.loadPostSlick(); }, 200); } }, loadBannerSlick: function () { if (jQuery() && jQuery().slick && jQuery('.slider-item').length) { jQuery('.slider-item').slick({ dots: true, arrows: true, infinite: true, slidesToShow: 1, slidesToScroll: 1, autoplay: true, autoplaySpeed: 4000, }); } else { setTimeout(function () { self.loadBannerSlick(); }, 200); } }, getPerformanceDetais: function () { var endpoint = self.endpoint.performance; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'GET', {}, true, agco.Dashboard.performanceDetailsSuccess, agco.Dashboard.performanceDetailsError); }, performanceDetailsSuccess: function (success) { agco.helper.loader('hide'); // console.log(success) if (!success || success.code != 'get_dash_selinga_success') { return false; } var userDashboardData = success.data; self.dashBoardChartControl(userDashboardData); }, dashBoardChartControl: function (userDashboardData) { self.resetBarChartAll(); var monthly = userDashboardData.vw_sky_dashboard_m_seliga ? userDashboardData.vw_sky_dashboard_m_seliga : ''; var weekly = userDashboardData.vw_sky_dashboard_w_seliga ? userDashboardData.vw_sky_dashboard_w_seliga[0] : ''; self.renderMonthData(monthly); self.renderWeekData(weekly); }, resetMonthBarChart: function () { jQuery('.goal-result-details .bar-chart li').remove(); jQuery('.result-details .bar-chart li').remove(); }, renderMonthData: function (monthly) { self.resetMonthBarChart(); if (!monthly) { return false; } var highestPoint = 0; monthly.forEach(function (element) { if (highestPoint < parseInt(element.Pontos)) { highestPoint = parseInt(element.Pontos); } }); monthly.forEach(function (element) { var pointPercent = (element.Pontos / highestPoint) * 100; var pointList = jQuery('
  • ', { title: element.mes_tiny, html: '' }); var metaPercentage = '0%'; if (parseInt(element.PercMeta) > 100) { metaPercentage = '100%'; } else { metaPercentage = element.PercMeta + '%'; } var PercMetaValue = element.PercMeta + '%'; var metaList = jQuery('
  • ', { title: element.mes_tiny, html: '' }); var metaHolder = jQuery('.goal-result-details .bar-chart')[0]; var pointHolder = jQuery('.result-details .bar-chart')[0]; jQuery(metaList).appendTo(jQuery(metaHolder)); jQuery(pointList).appendTo(jQuery(pointHolder)); }); }, renderWeekData: function (weekly) { if (!weekly) { return false; } jQuery('.user-performance-detail h3.user-name').html(weekly.Nome); jQuery('.user-performance-detail h3.update-date').html(weekly.Data_Atualizacao); jQuery('.user-performance-detail h3.month-name').html(weekly.Mes); jQuery('.user-performance-detail h3.goal-points').html(weekly.Meta + '%'); jQuery('.user-performance-detail .condition-details h3').html(weekly.Condicao); jQuery('.user-performance-detail .indicator-details h3').html(weekly.Indicador); jQuery('.user-performance-detail .result-details h3').html(weekly.Resultado_Indicador + '%'); jQuery('.user-performance-detail .result-goal-details h3').html(weekly.Resultado_Indicador + '%'); jQuery('.user-performance-detail .services-policy .services-status').removeClass('active'); if (weekly.Condicao_Atingida == "SIM") { var sim = jQuery('.user-performance-detail .services-policy .services-status')[0]; jQuery(sim).addClass('active'); } else if (weekly.Condicao_Atingida == "NÃO") { var nao = jQuery('.user-performance-detail .services-policy .services-status')[1]; jQuery(nao).addClass('active'); } else { } var pointKeys = ['Pontos_Range1', 'Pontos_Range2', 'Pontos_Range3']; var faixaInfKeys = ['Range1_Faixa_Inf', 'Range2_Faixa_Inf', 'Range3_Faixa_Inf']; var faixaSupKeys = ['Range1_Faixa_Sup', 'Range2_Faixa_Sup', 'Range3_Faixa_Sup']; for (let index = 0; index < 3; index++) { var element = jQuery('.user-performance-detail .banner-points-content')[index]; var Inf = jQuery(element).find('.banner-points')[0]; var Sup = jQuery(element).find('.banner-points')[1]; var point = jQuery(element).find('.banner-points')[2]; jQuery(Inf).find('h3').html(weekly[faixaInfKeys[index]]); jQuery(Sup).find('h3').html(weekly[faixaSupKeys[index]]); jQuery(point).find('h3').html(weekly[pointKeys[index]]); } var position = weekly.range_highlight ? parseInt(weekly.range_highlight) : 0; if (position) { var element = jQuery('.user-performance-detail .banner-points-content')[position - 1]; jQuery(element).addClass('active'); } }, resetBarChartAll: function () { }, performanceDetailsError: function (error) { agco.helper.loader('hide'); // console.log(error) }, }; return self; }(); jQuery(document).ready(function () { agco.Dashboard.ready(); }); agco.Register = function () { var self = { profilePic: '', activeTab: 0, accessdUserData: {}, preventToBack: false, endpoint: { 'registerUser': 'v1/user/client', 'updateUser': 'v1/user/update', 'accessPageStep1': 'v1/validate/user', 'cnpjList': 'v1/user/service-station/', 'admCreateUser': 'v1/adm/user', 'checkUserPresent': 'v1/validate/user', 'createVendedor': 'v1/adm/user', 'validateCell': 'v1/validate/cell', //'managerList': 'v1/adm/user/list' 'managerList': 'v1/adm/manager/list' }, accessPageData: {}, disabledFieldsData: [], stepformOne: [ { id: 'nomecompleto', errorMessage: 'nombre inválido', isValid: false, mandatory: true, }, { id: 'nomesobrenome', errorMessage: 'Apellido inválido', isValid: false, mandatory: true, }, { id: 'cpf', errorMessage: 'D.N.I inválido', isValid: false, mandatory: true, }, { id: 'id', errorMessage: 'ID inválido', isValid: true, mandatory: false, }, { id: 'dob', errorMessage: 'Fecha de nacimiento invalida', isValid: false, mandatory: true, }, { id: 'foto', errorMessage: 'foto inválido', isValid: false }, { id: 'reg_email', errorMessage: 'E-mail inválido', isValid: false, mandatory: true, }, { id: 'telefone', errorMessage: 'Teléfono inválido', isValid: false, mandatory: true, }, // { // id: 'tamanhodacamiso', // errorMessage: 'Tamanho da camisa inválido', // isValid: false // }, // { // id: 'tamanhodacalca', // errorMessage: 'Tamanho da calca inválido', // isValid: false // }, // { // id: 'tamanhodasapato', // errorMessage: 'Tamanho da sapato inválido', // isValid: false // }, { id: 'genero', errorMessage: 'Genero inválido', isValid: false }, ], stepformTwo: [ /*{ id: 'cep', errorMessage: 'Código postal no válido', isValid: false, mandatory: true, },*/ { id: 'rua', errorMessage: 'Rua inválido', isValid: false }, { id: 'numero', errorMessage: 'Número inválido', isValid: false, mandatory: true, }, { id: 'complemento', errorMessage: 'Complemento inválido', isValid: false }, { id: 'bairro', errorMessage: 'Bairro inválido', isValid: false }, { id: 'cidade', errorMessage: 'Cidade inválido', isValid: false }, { id: 'estado', errorMessage: 'Provincia inválido', isValid: false, mandatory: true, }, { id: 'referencia', errorMessage: 'Ponto de referência inválido', isValid: false, mandatory: false, }, ], stepformThree: [ { id: 'password', errorMessage: 'Senha atual inválido', isValid: false }, { id: 'newpassword', errorMessage: 'Nova senha inválida', isValid: false, mandatory: false, }, { id: 'conpassword', errorMessage: 'Confirmar nova senha inválida', isValid: false, mandatory: false, }, ], stepformFour: [ { id: 'customControlValidation1', errorMessage: 'Para continuar navegando e confirmar as alterações, você deve aceitar o regulamento.', isValid: false, mandatory: true, }, { id: 'customControlValidation2', errorMessage: 'Para continuar navegando e confirmar as alterações, você deve aceitar o regulamento.', isValid: false, mandatory: true, }, { id: 'customControlValidation3', errorMessage: 'Para continuar navegando e confirmar as alterações, você deve aceitar o regulamento.', isValid: false, mandatory: true, }, ], accessPageStepformOne: [ { id: 'cpf', errorMessage: 'cpf inválido', isValid: false, mandatory: true, }, { id: 'id', errorMessage: 'ID inválido', isValid: false, mandatory: true, }, ], accessPageStepformTwo: [ { id: 'nomecompleto', errorMessage: 'Nome inválido', isValid: false, mandatory: true, }, { id: 'reg_email', errorMessage: 'E-mail inválido', isValid: false, mandatory: true, }, { id: 'telefone', errorMessage: 'Telefone inválido', isValid: false, mandatory: false, }, ], currentBarCodeMask: '', ready: function () { var pageURL = location.href; var allowedPage = ['/register/', '/minha-conta/', '/primeiro-acesso/', '/cadastro-cliente/', '/area-do-vendedor/']; allowedPage.forEach(function (element) { if (pageURL.indexOf(element) > 0) { self.load(); } }); }, load: function () { self.eventHandler(); self.loadStepForm(); self.applyMask(); if (location.href.indexOf('/minha-conta/') > 0) { self.preLoadAdjustProfile(); // For SB purpose if (globalJsData && globalJsData.user.data.user_login == "teamsb") { jQuery('#cpf').unmask(); self.stepformOne[1]['mandatory'] = false; } self.setActiveStepMenu(0); // self.LoadCNPJList(); } else if (location.href.indexOf('/primeiro-acesso/') > 0) { jQuery('.primeiro-acesso-title').hide(); } else if (location.href.indexOf('/cadastro-cliente/') > 0) { self.removeAutoComplete(); self.setActiveStepMenu(0); //self.LoadCNPJList(); self.stepformThree[1].mandatory = true; self.stepformThree[2].mandatory = true; } else if (location.href.indexOf('/area-do-vendedor/') > 0) { self.removeAutoComplete(); self.setActiveStepMenu(0); // self.LoadCNPJList(); //self.stepformThree[1].mandatory = true; //self.stepformThree[2].mandatory = true; if (location.href.indexOf('/area-do-vendedor/?listDo=true') > 0) { self.stepformThree[1].mandatory = false; self.stepformThree[2].mandatory = false; self.stepformThree[1].isValid = true; self.stepformThree[2].isValid = true; } var perfil = { id: 'perfil', errorMessage: 'Perfil inválido', isValid: false }; self.stepformOne.push(perfil); self.getManagerList(); } else { self.removeAutoComplete(); self.validateForm(); self.isFromAccessPage(); // self.LoadCNPJList(); self.stepformThree[1].mandatory = true; self.stepformThree[2].mandatory = true; } self.preLoadAdjustStepForm(); // Used to unbind keyup event from stepform vendor jQuery('#stepform').unbind('keyup'); }, getManagerList: function () { var endpoint = self.endpoint.managerList; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', {}, true, self.getManagerListSuccess, self.getManagerListError); }, getManagerListSuccess: function (success) { agco.helper.loader('hide'); try { var data = success.data; if (data && data.length) { data.forEach(element => { jQuery('

    ', { html: 'Pontos insuficientes', class: 'red' }).prependTo(jQuery('.recharge-step-1').parent()); jQuery('.recharge-step-1').hide(); jQuery('.single-recharge-button-block .button-right .buttonNext').hide(); } }, pointsRequired: function () { var rechargeValue = jQuery(this).find('option:selected').attr('data-valor'); if (!rechargeValue) { jQuery('#points-required').html('0,00'); jQuery('#points-required-step-two').html('0,00'); return false; } rechargeValue *= agco.recharge.pointsConversionFactor; jQuery('#points-required').html(agco.helper.ptBrNumberFormat(parseFloat(rechargeValue), true)); jQuery('#points-required-step-two').html(agco.helper.ptBrNumberFormat(parseFloat(rechargeValue), true)); }, toOpenMyOrderPage: function () { window.location.href = window.location.protocol + "//" + document.location.host + '/seus-pedidos/'; }, toRechargeFormBack: function () { jQuery('.product-content').prop('hidden', false); jQuery('#ErrorModel').prop('hidden', true); jQuery('#successModel').prop('hidden', true); jQuery('.product-title').prop('hidden', false); self.goToBack(); }, validatePhoneNumber: function () { var cellularValue = jQuery('#mobile_number').val(); if (cellularValue.length == 15) { agco.helper.formValidationLabelRemove('mobile_number'); jQuery('#mobile_number').css('border-color', "black"); jQuery('#mobile_number').removeClass('error-field'); return true; } else { agco.helper.formValidationLabelCreate('mobile_number', "Campo Obrigatório"); jQuery('#mobile_number').css('border-color', "red"); jQuery('#mobile_number').addClass('error-field'); return false; } }, toOpenMyOrderPage: function () { window.location.href = window.location.protocol + "//" + document.location.host + '/seus-pedidos/'; }, toRechargeFormBack: function () { jQuery('.product-content').prop('hidden', false); jQuery('#ErrorModel').prop('hidden', true); jQuery('#successModel').prop('hidden', true); self.goToBack(); }, updatePhoneNumber: function () { var cellularValue = jQuery('#selectedNumber').val(); if (cellularValue.length == 15) { jQuery("#mobile_number").val(cellularValue); agco.helper.formValidationLabelRemove('selectedNumber'); jQuery('#selectedNumber').css('border-color', "black"); jQuery('#selectedNumber').removeClass('error-field'); return true; } else { agco.helper.formValidationLabelCreate('selectedNumber', "Campo Obrigatório"); jQuery('#selectedNumber').css('border-color', "red"); jQuery('#selectedNumber').addClass('error-field'); return false; } }, addToCart: function (event) { if (!self.updatePhoneNumber()) { return false; } agco.helper.loader('show'); var mobile_number = jQuery("#mobile_number").val().replace('-', ''); mobile_number = mobile_number.replace(' ', '-'); var operater = jQuery("#productDetail").data('title'); var productId = jQuery("#paValor").find(':selected').val(); var valor = jQuery("#paValor").find(':selected').data('valor'); //var productId = jQuery("#productDetail").data('productid'); var data = { "ope": operater, "val": valor, "cell": mobile_number, "product_id": productId }; var pontos = valor; var currentUserPoints = globalJsData.points; if (pontos > currentUserPoints) { agco.helper.popUp('Error', 'Pontos de usuário insuficientes', self.closeModelPopup); agco.helper.loader('hide'); return false; } var endPoint = self.endpoint.recharge; agco.helper.appApiRequest(endPoint, 'POST', data, true, self.successCallBackAddToCart, self.errorCallBackAddToCart); }, successCallBackAddToCart: function (response) { agco.helper.loader('hide'); // console.log("Success", response); if (response.code && (response.code == 'error_status_error' || response.code == 'not_available_error')) { self.showErrorModel(response.message); return false; } if (response.error) { // agco.helper.popUp('Error', response.error, self.closeModelPopup); self.showErrorModel(response.error); return false; } if (response.data.success === "EFETIVADA") { // agco.helper.popUp('Éxito', response.data.success, self.redirectToHistoryPage); self.showSuccessModel(response.data.success); return false; } // agco.helper.popUp('Éxito', response.data.success, self.closeModelPopup); self.showSuccessModel(response.data.success); }, /** * redirect to order page * * @returns {undefined} */ redirectToHistoryPage: function () { window.location.href = location.host + "/shop/order-history/"; }, closeModelPopup: function () { self.goToBack(); }, showErrorModel: function (message) { if (message) { jQuery('#ErrorModel .message').html(message); } jQuery('.product-content').prop('hidden', true); jQuery('#ErrorModel').prop('hidden', false); jQuery('#successModel').prop('hidden', true); jQuery('.product-title').prop('hidden', true); }, showSuccessModel: function (message) { if (message) { jQuery('#successModel .message').html(message); } jQuery('.product-content').prop('hidden', true); jQuery('#successModel').prop('hidden', false); jQuery('#ErrorModel').prop('hidden', true); jQuery('.product-title').prop('hidden', true); }, errorCallBackAddToCart: function (error) { agco.helper.loader('hide'); // console.log("Error", error); // agco.helper.popUp("Erro", (error.error || error.statusText), self.closeModelPopup); self.showErrorModel((error.error || error.statusText)); }, singleRechargeForm: function () { self.buttonNext = jQuery(".buttonNext"); self.buttonBack = jQuery("#voltar2"); self.addToCart = jQuery(".addToCart"); jQuery(".recharge-step-2").hide(); self.buttonNext.on('click', self.goToNext); self.buttonBack.on('click', self.goToBack); }, goToNext: function () { var rechargeField = [ 'mobile_number', 'paValor' ]; var i = 0; jQuery.each(rechargeField, function (index, value) { if (value == 'paValor') { if (jQuery('#' + value).val() == 'Escolha uma opção' || !jQuery('#' + value).val()) { jQuery('#' + value).focus(); jQuery('#' + value).css('border-color', "red"); event.preventDefault(); return false; } } else { if (jQuery('#' + value).val() === '' || jQuery('#' + value).val().length < 15) { jQuery('#' + value).focus(); jQuery('#' + value).css('border-color', "red"); agco.helper.formValidationLabelCreate(value, "Campo Obrigatório"); event.preventDefault(); return false; } else { agco.helper.formValidationLabelRemove(value); } } i++; }); if (i >= 2) { var selectedNumber = jQuery("#mobile_number").val().replace('-', ''); selectedNumber = selectedNumber.replace(' ', '-'); var valor = jQuery("#paValor").find(':selected').data('valor'); jQuery('#selectedValor').html("R$ " + self.numberformat(parseFloat(valor / self.pointsConversionFactor), 2, 3, '.', ',')); jQuery('#selectedNumber').val(jQuery("#mobile_number").val()); var points = parseFloat(valor); points = points * globalJsData.conversion_factor; points = self.pointsNumberFormat(points); jQuery('#totalPoints').html(points + " PTS"); jQuery(".recharge-step-1").hide(); jQuery(".recharge-step-2").show(); jQuery(".addToCart").show(); jQuery(".buttonNext").hide(); jQuery("#voltar1").hide(); jQuery("#voltar2").show(); } }, goToBack: function () { jQuery(".recharge-step-2").hide(); jQuery(".recharge-step-1").show(); jQuery(".buttonNext").show(); jQuery(".addToCart").hide(); jQuery("#voltar2").hide(); jQuery("#voltar1").show(); }, numberformat: function (a, n, x, s, c) { var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')', num = a.toFixed(Math.max(0, ~~n)); return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ',')); }, decimalNumberFormat: function (points) { points = points.toString().replace('.', ''); points = points.replace(',', '.'); return points; }, pointsNumberFormat: function (currency) { currency = currency.toString().replace(',', ''); currency = currency.replace('.', ','); return currency; } }; return self; }(); jQuery(document).ready(function () { agco.recharge.load(); }); agco.extrato = function () { var self = { isValidDate: false, endpoint: { 'extrato': 'v1/extrato' }, columns: [ { "data": "data", "title": "FECHA" }, { "data": "tipo", "title": "ESCRIBE" }, { "data": "description", "title": "DESCRIPCIÓN" }, { "data": "expiracao", "title": "VALOR EN PUNTOS", render: function (data, type, rowObject, metat) { return rowObject.expiracao ? rowObject.expiracao : ''; } }, // { // "data": "pontos", // "title": "VALOR EM PONTOS", // render: function (data, type, rowObject, metat) { // var points; // try { // points = parseFloat(rowObject.pontos); // points = agco.helper.ptBrNumberFormat(points, true); // } catch (e) { // points = rowObject.pontos; // } // return points; // } // }, { "data": "saldo", "title": "SALDO", render: function (data, type, rowObject, metat) { var points; try { points = parseFloat(rowObject.saldo); points = agco.helper.ptBrNumberFormat(points, true); } catch (e) { points = rowObject.saldo; } return points; } }, { "data": "invoice", "title": "INVOICE", render: function (data, type, rowObject, metat) { return rowObject.invoice ? rowObject.invoice : ''; } }, ], ready: function () { var pageURL = location.href; if (pageURL.indexOf('/extrato/') > 0) { self.load(); } }, load: function () { self.eventHandler(); self.loadDataTable(); }, eventHandler: function () { jQuery(document).on('click', '.extrato-page-period button', self.searchExtrado); jQuery(document).on('change', '#start-date', self.validateDate); jQuery(document).on('change', '#ending-date', self.validateDate); }, loadDataTable: function (data) { var endPoint = self.endpoint.extrato; var url = agco.helper.baseUrl + endPoint; agco.helper.loadDataTable('extrato-page-table-with-search', url, '.extrato-page-period-detail', self.columns, data); jQuery('[name="extrato-page-table_length"]').hide(); }, searchExtrado: function () { if (!self.isValidDate) { agco.helper.formValidationLabelCreate('filter', 'Escolha as datas para o fazer o filtro.', 'title-red'); return false; } var startDate = jQuery("#start-date").val(); var endDate = jQuery("#ending-date").val(); var data = { start_date: startDate, end_date: endDate }; self.loadDataTable(data); }, validateDate: function () { if (jQuery("#start-date").val() && jQuery("#ending-date").val()) { agco.helper.formValidationLabelRemove('filter'); if (moment(jQuery("#ending-date").val()).diff(jQuery("#start-date").val()) <= 0) { self.isValidDate = false; agco.helper.formValidationLabelCreate('filter', 'A data atual não pode ser menor que a data.', 'title-red'); } else { self.isValidDate = true; agco.helper.formValidationLabelRemove('filter'); } } else { self.isValidDate = false; agco.helper.formValidationLabelCreate('filter', 'Escolha as datas para o fazer o filtro.', 'title-red'); } }, }; return self; }(); jQuery(document).ready(function () { agco.extrato.ready(); }); agco.forgetPassword = function () { var self = { selectedForm: '', isApplyForm: false, forgetPasswordFormFields: [ { id: 'password_1', errorMessage: 'Dica: A sua senha deverá ter pelo menos 8 (oito) caracteres, contendo pelo menos um número, uma letra maiúscula e um caractere especial.', isValid: false, mandatory: true, }, { id: 'password_2', errorMessage: 'Dica: A sua senha deverá ter pelo menos 8 (oito) caracteres, contendo pelo menos um número, uma letra maiúscula e um caractere especial.', isValid: false, mandatory: true, }, ], forgetPasswordApplyFormFields: [ { id: 'user_login', errorMessage: 'Informe seu CPF.', isValid: false, mandatory: true, }, ], ready: function () { if (jQuery('.woocommerce-lost-password').length) { self.load(); } }, load: function () { self.eventHandler(); if (jQuery('#user_login').length) { self.applyMask(); self.selectedForm = 'forgetPasswordApplyFormFields'; isApplyForm = true; } else { self.selectedForm = 'forgetPasswordFormFields'; isApplyForm = false; } }, eventHandler: function () { jQuery(document).on('change', '#user_login', self.userIDValidation); jQuery(document).on('change', '#password_1', self.passwordValidation); jQuery(document).on('change', '#password_2', self.passwordValidation); jQuery(document).on('click', '.lost_reset_password button[type="submit"]', self.submitForm); jQuery(document).on('change', '#user_login_masked', self.updateUserID); }, updateUserID: function () { var data = jQuery('#user_login_masked').val(); jQuery('#user_login').val(data.replace(/\D/g, '')); jQuery('#user_login').change(); }, userIdMaskOptions: { onKeyPress: function (val, e, field, options) { field.mask(agco.helper.CNPJ_CPF_MaskBehavior.apply({}, arguments), options); } }, updateValidatedStatus: function (elementID, status) { var selectedForm = self.selectedForm; self[selectedForm].forEach(function (element) { if (element.id === elementID) { if (!jQuery('#' + elementID).val() && !element.mandatory) { element.isValid = true; agco.helper.formValidationLabelRemove(element.id); return false; } element.isValid = status; if (!status) { agco.helper.formValidationLabelCreate(element.id, element.errorMessage); } else { agco.helper.formValidationLabelRemove(element.id); } } }); // console.log(self[selectedForm]); }, userIDValidation: function () { var userID = jQuery(this).val(); if (userID) { self.updateValidatedStatus('user_login', true); } else { self.updateValidatedStatus('user_login', false); } }, passwordValidation: function () { var password = jQuery(this).val(); if (password && agco.helper.passwordRegex.test(password)) { self.updateValidatedStatus(jQuery(this).attr('id'), true); } else { self.updateValidatedStatus(jQuery(this).attr('id'), false); } }, submitForm: function (e) { var errorFlag = false; var selectedForm = self.selectedForm; self[selectedForm].forEach(function (element) { if (!jQuery('#' + element.id).length) { element.isValid = true; } else if (!element.isValid && element.mandatory) { errorFlag = true; agco.helper.formValidationLabelCreate(element.id, element.errorMessage); } else if (element.isValid) { agco.helper.formValidationLabelRemove(element.id); } else { } }); if (errorFlag) { e.preventDefault(); } else { if (isApplyForm) { } else { if (jQuery('#password_1').val() != jQuery('#password_2').val()) { agco.helper.formValidationLabelCreate('password_2', '“A nova senha não confere.'); e.preventDefault(); setTimeout(function () { agco.helper.formValidationLabelRemove('password_2'); }, 5000); } } } } }; return self; }(); jQuery(document).ready(function () { agco.forgetPassword.ready(); }); agco.woocommerce = function () { var self = { formId: '', endpoints: { 'userAvailability': "v1/check/product/availability", }, pointsSlider: '', pointsConversionFactor: '', minimumPointsPercentage: '', init: function () { jQuery('[name="woocommerce_checkout_place_order"]').click(function () { jQuery(this).prop('disabled', true); }); if (!jQuery('.mega-menu-container').length) { // return false; } agco.helper.applySelect2(); self.pointsConversionFactor = globalJsData.conversion_factor; self.minimumPointsPercentage = globalJsData.minimum_points_percentage; self.loadMask(); jQuery(document.body).on('wc_fragments_refreshed', self.afterCartTotalUpdated); if (jQuery("form.variations_form").length > 0) { self.formId = "form.variations_form"; } else { self.formId = "#signle-product-form"; } if (jQuery('form.cart').length) { jQuery('#quantityform').hide(); } if (jQuery('.product-range-slider').length > 0) { if (jQuery('form.variations_form').length === 0) { jQuery(".product-range-slider").hide(); jQuery("#single-add-to-cart-btn").hide(); if (!jQuery(".product_cat-loja-ferrari").length >= 1) { self.checkUserAvailability(); } else { jQuery("#product-loader").fadeOut('slow'); jQuery(".product-range-slider").show(); var price; price = jQuery("#product_sub_total").val(); self.productPrice = parseFloat(price * self.pointsConversionFactor); self.loadDefaultValues(); self.eventHandler(); self.initializeRangeSlider(); } // self.initializeImageSlider(); } else { self.variantProduct = "pa_valecombustivel"; self.variantProduct = true; self.variantProductId = jQuery(".woocommerce .variations").find('select').attr("id"); self.loadDefaultValues(); self.eventHandler(); self.initializeRangeSlider(); // self.initializeImageSlider(); // self.removeSelectBox(); } self.shippingRate = 0; } }, /** * Add the jQuery mask for input field DOB,NUMBER,CPF * * @returns {undefined} */ loadMask: function () { if (jQuery() && jQuery().mask) { if (jQuery("#billing_postcode").length > 0) { jQuery("#billing_postcode").mask("00000-000"); } } else { setTimeout(self.loadMask, 50); } }, /** * Destroy the select2 * * @returns {undefined} */ removeSelectBox: function () { if (jQuery("#" + self.variantProductId).hasClass("select2-hidden-accessible")) { jQuery("#" + self.variantProductId).select2('destroy').val('').trigger('change'); //self.onChangeValor(); } else { setTimeout(self.removeSelectBox, 30); } }, /** * Check the user availability * * @returns {undefined} */ checkUserAvailability: function () { jQuery("#product-loader").fadeIn('slow'); jQuery(".product-range-slider").hide(); var endPoint = self.endpoints.userAvailability; var productId = jQuery('[name=add-to-cart]').val(); var data = { product_id: productId }; agco.helper.loader('show'); agco.helper.appApiRequest(endPoint, 'POST', data, true, self.successCallBackOnUserAvailability, self.errorCallBackOnUserAvailability); }, /** * Success callback for user availability * * @param {type} response * @returns {Boolean} */ successCallBackOnUserAvailability: function (response) { agco.helper.loader('hide'); if (response.code !== "check_product_availability_success") { jQuery("#product-loader").fadeOut('slow'); jQuery(".product-range-slider").remove(); jQuery(".single_add_to_cart_button").remove(); jQuery(".single-product-description").remove(); self.loadDefaultValues(); self.eventHandler(); self.initializeRangeSlider(); if (response.message == '') { response.message = 'PRODUTO INDISPONÍVEL NO MOMENTO'; } agco.helper.popUp("Erro", response.message, self.closeModelPopup); // agco.helper.showModelPopup('error-msg', "Erro", response.message, self.closeModelPopup); return false; } // if (response.data.shipping_rate) { jQuery("#product-loader").fadeOut('slow'); jQuery(".product-range-slider").show(); var shippintRate = response.data.shipping_rate; var shippingMoney = shippintRate * self.pointsConversionFactor; jQuery("#ferete").html("" + shippingMoney + " PTS"); self.shippingRate = 0; var price; price = jQuery("#product_sub_total").val(); self.productPrice = parseFloat(price * self.pointsConversionFactor); self.loadDefaultValues(); self.eventHandler(); self.initializeRangeSlider(); //} // console.log("userAvailability", response); }, /** * Error callback for user availability * * @param {type} error * @returns {undefined} */ errorCallBackOnUserAvailability: function (error) { agco.helper.loader('hide'); // console.log("userAvailability", error); // jQuery(".product-range-slider").remove(); // jQuery("#single-add-to-cart-btn").remove(); self.loadDefaultValues(); self.eventHandler(); self.initializeRangeSlider(); jQuery("#product-loader").fadeOut('slow'); jQuery(".product-range-slider").show(); }, /** * close the modal popup * * @returns {undefined} */ closeModelPopup: function () { jQuery(this).dialog("close"); }, /** * create instance for all global variable and load initialy * * @returns {undefined} */ popupAlreadShow: false, loadDefaultValues: function () { var showFerrariPopup = false; if (typeof SBSingleProduct !== 'undefined') { jQuery.each(SBSingleProduct.categories, function (i, v) { if (v.slug === 'loja-ferrari') { showFerrariPopup = true; } }); } if (showFerrariPopup) { /*agco.helper.showModelPopup( 'error-msg', 'Aviso', 'Este produto sofreu uma atualização de valor em pontos por conta do recente reajuste de preço de frete do Correios.', self.closeModelPopup );*/ } self.output = jQuery('#in-points'); self.inCurrency = jQuery('#in-currency'); self.pointsToRedeemField = jQuery("[name=points_to_redeem]"); self.pointsSlider = jQuery('input[type="range"]'); //self.pointsAvailable = parseInt(self.pointsSlider.data("points-available")); if (self.variantProduct) { self.variantInitSlider(); if ((self.variantProductId === 'pa_valecombustivel' || self.variantProductId === 'pa_pao-de-acucar' || self.variantProductId === 'pa_vale-presente-recarga') && !self.popupAlreadShow) { self.popupAlreadShow = true; /*var msg; switch (self.variantProductId) { case 'pa_valecombustivel': msg = 'Desde o dia 16/01/2018 o prazo de liberação do crédito de combustível foi alterado para até 10 dias úteis, conforme exigência do parceiro.'; break; case 'pa_pao-de-acucar': msg = 'Este produto sofreu uma atualização de valor em pontos por conta do recente reajuste de preço de frete do Correios.'; break; case 'pa_vale-presente-recarga': msg = 'Desde o dia 26/03/2018 o prazo de liberação das recargas de vale presente foi alterado para até 20 dias corridos, conforme exigência do parceiro.'; break; } agco.helper.showModelPopup( 'error-msg', 'Aviso', msg, self.closeModelPopup );*/ } } if (self.variantProductId === 'pa_grupo') { var intialGroupoShipping = Math.round(self.pointsConversionFactor * 13.446).toFixed(2); var multiCashFormatted = self.numberformat(parseFloat(intialGroupoShipping), 2, 3, '.', ','); jQuery('#ferete').html(multiCashFormatted); jQuery('#ferete').append(' PTS'); jQuery('[name=cash_to_pay_in_points]').val(parseFloat(intialGroupoShipping)); } }, variantInitSlider: function () { var variationPrice; if (jQuery('#' + self.variantProductId).length > 0) { variationPrice = jQuery('#' + self.variantProductId).val(); } var variationId = jQuery(".variation_id").val(); if (variationId) { var variantProducts = jQuery(".variations_form").data('product_variations'); jQuery.each(variantProducts, function (index, value) { if (value.variation_id === parseInt(variationId)) { var variationPrice = value.display_price; self.productPrice = parseFloat(variationPrice); self.initializePointsSlider(jQuery('[name=quantity]').val()); } }); } }, /** * initalize Range slider * * @returns {undefined} */ initializeRangeSlider: function () { if (jQuery() && jQuery().rangeslider) { self.pointsSlider.rangeslider({ polyfill: false, // Callback function onSlide: function (position, value) { // console.log("Position0", position, "Value", value); if (position > 595) { jQuery('output#in-currency').css('color', 'white'); jQuery('output#in-points').css('color', 'white'); } else if (position < 120) { jQuery('output#in-currency').css('color', 'black'); jQuery('output#in-points').css('color', 'black'); } else { jQuery('output#in-currency').css('color', 'black'); jQuery('output#in-points').css('color', 'white'); } } }); self.initializePointsSlider(jQuery('[name=quantity]').val()); } else { setTimeout(self.initializeRangeSlider, 30); } }, /** * Initailize image slider * * @returns {undefined} */ initializeImageSlider: function () { if (jQuery() && jQuery().slick && jQuery('.thumbnails').find('a img').length > 1) { jQuery('.thumbnails').slick({ infinite: true, slidesToShow: 2, slidesToScroll: 3, adaptiveHeight: true, prevArrow: '', nextArrow: '' }); } else { setTimeout(self.initializeImageSlider, 30); } }, /** * Listen the all evnent * * @returns {undefined} */ eventHandler: function () { self.variantProductId = jQuery(".woocommerce .variations").find('select').attr("id"); if (self.variantProductId) { jQuery('#' + self.variantProductId).on('change', self.onChangeValor); self.checkValeCombustivel(); } else { var price; price = jQuery("#product_sub_total").val(); self.productPrice = parseFloat(price); self.initializePointsSlider(jQuery('[name=quantity]').val()); } jQuery('.variation_id').on('change', self.loadDefaultValues); jQuery('[name=points-increment]').on('click', self.pointsIncrement); jQuery('[name=points-decrement]').on('click', self.pointsDecrement); jQuery(".quantity-right-plus").on('click', self.incrementQuantity); jQuery(".quantity-left-minus").on('click', self.decrementQuantity); jQuery('[name=quantity]').on('change', self.onChangeQuantity); jQuery('input[type="range"]').on('input change', self.onChangeSlider); jQuery('#single-add-to-cart-btn').on('click', self.successCallBackAddToCart); jQuery('body').on('click', '#back', self.goBackToPreviousPage); jQuery(document).on('click', '.buttonBack', self.toBack); // jQuery('#points_range').on('input', function (e) { // /*if (jQuery('input[type="range"]').val() !== jQuery(this).val()) { // // jQuery('input[type="range"]').val(jQuery(this).val()).change(); // }*/ // }); }, toBack: function () { window.history.back(); }, checkValeCombustivel: function () { if (self.variantProductId.indexOf('valecombustivel') > 0) { jQuery('.quantity input').prop('disabled', true); jQuery('.quantity-left-minus').prop('disabled', true); jQuery('.quantity-right-plus').prop('disabled', true); } }, goBackToPreviousPage: function (e) { window.history.back(); }, afterCartTotalUpdated: function () { if (jQuery("#cart-items-count-details").length) { jQuery("#cart-items-count-details").html(''); jQuery("#cart-items-count-details").html('Carregando...'); var data = jQuery.parseJSON(window.sessionStorage.getItem('wc_fragments')); jQuery("#cart-items-count-details").html(''); jQuery("#cart-items-count-details").html(data['cart-items-count-details']); } }, /** * onchange valor to change the slider values * * @returns {undefined} */ onChangeValor: function (e) { self.variantProduct = false; // if (jQuery('#' + self.variantProductId).val()) { // var variationPrice; // if (jQuery('#' + self.variantProductId).val().match("r-")) { // variationPrice = jQuery('#' + self.variantProductId).val().split('-')[1]; // } else { // variationPrice = jQuery('#' + self.variantProductId).val(); // } // self.productPrice = parseFloat(variationPrice); // self.variantProduct = true; // self.initializePointsSlider(jQuery('[name=quantity]').val()); // // } else { // var variationPrice = 0; // self.productPrice = parseFloat(variationPrice); // self.initializePointsSlider(jQuery('[name=quantity]').val()); // } // console.log(e); var attributeName = jQuery(".product-variation").data("attribute_name"); var variantPrice = e.currentTarget.value; if (variantPrice) { var variationPrice = 0; var variantProducts = jQuery(".variations_form").data('product_variations'); jQuery.each(variantProducts, function (index, value) { jQuery.each(value.attributes, function (ind, val) { if (variantPrice === val) { variationPrice = value.display_price; self.productPrice = parseFloat(variationPrice); self.variantProduct = true; if (jQuery(".product_cat-loja-ferrari").length > 0) { setTimeout(function () { var woocommerceVariant = self.numberformat(parseFloat(variationPrice), 2, 3, '.', ','); jQuery(".woocommerce-variation-price").append(' PTS ' + woocommerceVariant + ''); }, 300); } else { // setTimeout(function () { // jQuery('.woocommerce-Price-currencySymbol').html('POR'); // jQuery('.woocommerce-Price-amount').append('PONTOS'); // }, 300); } self.initializePointsSlider(jQuery('[name=quantity]').val()); } }); // if (value.attributes.attribute_pa_tamanhos === attributeName) { // variationPrice = value.display_price; //// if (value.attributes.attribute_pa_valecombustivel.match("r-")) { //// variationPrice = value.attributes.attribute_pa_valecombustivel.split('-')[1]; //// //// } else { //// variationPrice = value.attributes.attribute_pa_valecombustivel; //// //// } // self.productPrice = parseInt(variationPrice); // self.variantProduct = true; // self.initializePointsSlider(jQuery('[name=quantity]').val()); // } }); } else { var variationPrice = 0; self.productPrice = parseInt(variationPrice); self.initializePointsSlider(jQuery('[name=quantity]').val()); } }, /** * Form submit for add to cart product * * @returns {undefined} */ successCallBackAddToCart: function () { setTimeout(function () { jQuery('#signle-product-form').submit(); jQuery('form.variations_form').submit(); }, 10); }, /** * Increment points on points slider * * @param {type} e * @returns {undefined} */ pointsIncrement: function (e) { jQuery('input[type="range"]').val(parseInt(jQuery('input[type="range"]').val()) + 1).change(); }, /** * Decrement points on points slider * * @param {type} e * @returns {undefined} */ pointsDecrement: function (e) { jQuery('input[type="range"]').val(parseInt(jQuery('input[type="range"]').val()) - 1).change(); }, /** * Increment quantity on points slider * * @returns {undefined} */ incrementQuantity: function () { jQuery('[name=quantity]').val(parseInt(jQuery('[name=quantity]').val()) + 1).change(); }, /** * Decrement quantity on points slider * * @returns {undefined} */ decrementQuantity: function () { if (parseInt(jQuery('[name=quantity]').val()) > 1) { jQuery('[name=quantity]').val(parseInt(jQuery('[name=quantity]').val()) - 1).change(); } }, /** * onchange event for quantity field * * @param {type} e * @returns {undefined} */ onChangeQuantity: function (e) { self.initializePointsSlider(jQuery(this).val(), e); if (self.variantProductId == 'pa_grupo') { var multiCashQuanity = jQuery('[name=quantity]').val(); var multiCashShippingAmount = 0; switch (multiCashQuanity) { case "1": multiCashShippingAmount = 13.446; break; case "2": multiCashShippingAmount = 7.479; break; case "3": multiCashShippingAmount = 5.436; break; case "4": multiCashShippingAmount = 4.401; break; case "5": multiCashShippingAmount = 3.78; break; default: multiCashShippingAmount = 3.384; } var multiCashConversionFactor = multiCashShippingAmount * self.pointsConversionFactor; var multiCashRound = Math.round(multiCashConversionFactor).toFixed(2); var multiCashFormatted = self.numberformat(parseFloat(multiCashRound), 2, 3, '.', ','); jQuery('[name=cash_to_pay_in_points]').val(parseFloat(multiCashRound)); jQuery('#ferete').html(multiCashFormatted); jQuery('#ferete').append(' PTS'); } }, /** * Onchange the slider event * * @param {type} e * @returns {undefined} */ onChangeSlider: function (e) { if (!self.pointsSlider.length) { setTimeout(function () { self.onChangeSlider(e); }, 200); return false; } self.pointsToRedeemField.val(e.currentTarget.value); //self.output.text(parseFloat(e.currentTarget.value).toFixed('2') + " PTS"); var currentValue = parseFloat(e.currentTarget.value).toFixed('2') self.output.html(agco.helper.ptBrNumberFormat(currentValue, true) + " PTS"); self.pointsSlider.rangeslider('update', true); var maximumPointsRedeemable = jQuery('input[type="range"]').attr("max"); var currency = (maximumPointsRedeemable - e.currentTarget.value) / self.pointsConversionFactor; if (globalJsData.gateway_tax) { currency = currency * parseFloat(globalJsData.gateway_tax); } if (currency !== 0) { self.inCurrency.html("R$ " + self.numberformat(parseFloat(currency), 2, 3, '.', ',')); } else { self.inCurrency.html("R$ 0"); } //jQuery("#points_range").val(e.currentTarget.value).change(); }, /** * * load slider values on onchange quantity * * @param {number} quantity * @param {object} eventArgs * @returns {Boolean} */ initializePointsSlider: function (quantity, eventArgs) { var quantity = parseInt(quantity); if (isNaN(quantity)) { quantity = 1; } if (!self.productPrice) { self.productPrice = 0; } // console.log("quantity : " + quantity); // console.log("productPrice : " + self.productPrice); var minimumPointsToUse = (quantity * self.productPrice) * (self.minimumPointsPercentage / 100); minimumPointsToUse = minimumPointsToUse.toFixed(2); var maximumPointsRedeemable = (quantity * self.productPrice); maximumPointsRedeemable = maximumPointsRedeemable.toFixed(2); // console.log("minimumPointsToUse : " + minimumPointsToUse); // console.log("maximumPointsRedeemable : " + maximumPointsRedeemable); // if (minimumPointsToUse > self.pointsAvailable) { // if (typeof eventArgs !== "undefined") { // jQuery(eventArgs.currentTarget).val(quantity - 1); // agco.helper.showModelPopup("error-msg", "Erro", "Você não tem pontos suficientes para este resgate", self.closeModelPopup); // //jQuery("#warning_poinst_not_enough").html("Você não tem pontos suficientes para este resgate"); // jQuery(".single_add_to_cart_button").hide(); // eventArgs.preventDefault(); // } else { // agco.helper.showModelPopup("error-msg", "Erro", "Você não tem pontos suficientes para este resgate", self.closeModelPopup); // //jQuery("#warning_poinst_not_enough").html("Você não tem pontos suficientes para este resgate"); // jQuery(".single_add_to_cart_button").hide(); // } // return false; // } else { // jQuery("#single_add_to_cart_button").show(); self.pointsToRedeemField.val(maximumPointsRedeemable); // if (maximumPointsRedeemable > self.pointsAvailable) { // if (!self.variantProduct) { // // maximumPointsRedeemable = self.pointsAvailable; // agco.helper.showModelPopup("error-msg", "Erro", "Você não tem pontos suficientes para este resgate, complemente com dinheiro", self.closeModelPopup); // // return false; // // jQuery("#warning_poinst_not_enough").html("Você não tem pontos suficientes para este resgate, complemente com dinheiro"); // } // } else { // jQuery("#warning_poinst_not_enough").html(""); // } jQuery('#points_range').attr("min", minimumPointsToUse); jQuery('#points_range').attr("max", maximumPointsRedeemable); jQuery('input[type="range"]').attr("min", minimumPointsToUse); jQuery('input[type="range"]').attr("max", maximumPointsRedeemable); jQuery('input[type="range"]').val(maximumPointsRedeemable).change(); jQuery(".product-range-slider").show(); jQuery("#single-add-to-cart-btn").show(); // } }, /** * craete a global function for number format * * @param {type} a * @param {type} n * @param {type} x * @param {type} s * @param {type} c * @returns {self.numberformat.num} */ numberformat: function (a, n, x, s, c) { var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')', num = a.toFixed(Math.max(0, ~~n)); return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ',')); }, /** * create * * @param {type} data * @returns {undefined} */ decimalNumberFormat: function (points) { points = points.toString().replace('.', ''); points = points.replace(',', '.'); return points; }, pointsNumberFormat: function (currency) { currency = currency.toString().replace(',', ''); currency = currency.replace('.', ','); return currency; }, ptBrNumberFormat: function (number) { number = parseFloat(number); return number.toLocaleString('pt-br'); } }; return self; }(); jQuery(document).ready(function () { agco.woocommerce.init(); }); agco.programPage = function () { var self = { ready: function () { if (jQuery('.page-template-page-program').length) { self.load(); } }, load: function () { self.eventHandler(); self.loadPostSlick(); }, eventHandler: function () { }, loadPostSlick: function () { if (!jQuery('.home-post-slider').length) { return false; } if (jQuery() && jQuery().slick) { jQuery('.home-post-slider').slick({ infinite: true, slidesToShow: 3, slidesToScroll: 1, swipeToSlide: true, swipe: true, arrows: true, responsive: [ { breakpoint: 1500, settings: { slidesToShow: 3, slidesToScroll: 1 } }, { breakpoint: 1180, settings: { slidesToShow: 2, slidesToScroll: 1 } }, { breakpoint: 730, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] }); } else { setTimeout(function () { self.loadPostSlick(); }, 200); } }, }; return self; }(); jQuery(document).ready(function () { agco.programPage.ready(); }); agco.cartPage = function () { var self = { ready: function () { if (jQuery('.page-template-page-cart-php').length) { self.load(); } }, load: function () { self.eventHandler(); self.listenAjaxCall(); }, eventHandler: function () { jQuery(document).on('click', '.quantity-left-minus', self.decrementQuantity); jQuery(document).on('click', '.quantity-right-plus', self.incrementQuantity); jQuery(document).on('change', '.quantity input', self.updateQuantityDetails); // jQuery(document).on('click', 'button[name="update_cart"]', self.preventPageReload); }, listenAjaxCall: function () { jQuery(document).ajaxComplete(function (event, request, settings) { if (settings && settings.url.indexOf('get_refreshed_fragments') <= 0) { return false; } if (request && request.status === 200) { if (request.responseJSON && request.responseJSON['fragments']) { agco.helper.loader('hide'); var countString = request.responseJSON.fragments['cart-items-count-details']; var count = countString ? countString.split(' ')[0] : 0; var cartElement = jQuery('#cart-id').siblings('.card-content').find('.count')[0]; jQuery(cartElement).html(count); } else { agco.helper.loader('hide'); } } }); }, preventPageReload: function (e) { }, incrementQuantity: function () { var previousQuantity = parseInt(jQuery(this).parent().siblings('input').val()); if (previousQuantity >= 0) { previousQuantity++; jQuery(this).parent().siblings('input').val(previousQuantity).change(); } }, decrementQuantity: function () { var previousQuantity = parseInt(jQuery(this).parent().siblings('input').val()); if (previousQuantity >= 1) { previousQuantity--; jQuery(this).parent().siblings('input').val(previousQuantity).change(); } }, updateQuantityDetails: function () { // console.log('updated'); setTimeout(function () { jQuery("button[name='update_cart']").click(); }, 10); }, }; return self; }(); jQuery(document).ready(function () { agco.cartPage.ready(); }); agco.contaPage = function () { var self = { endpoints: { 'checkBarcode': 'v1/site/check/barcode', 'create': 'v1/site/account/create', 'receipts': 'v1/site/user/receipts', }, pageMentoFields: [ "pagBarcode", "pagVencimento", "pagCellular", "pagValue", "pagPontos", "tipoConta", ], fieldsToValidate: [ { id: 'tipoConta', errorMessage: 'Tipo de Conta inválido', isValid: false, mandatory: true, }, { id: 'pagBarcode', errorMessage: 'Campo Obrigatório', isValid: false, mandatory: true, }, { id: 'pagVencimento', errorMessage: 'Campo Obrigatório', isValid: false, mandatory: true, }, { id: 'pagCellular', errorMessage: 'Celular inválido', isValid: false, mandatory: true, }, { id: 'pagPontos', errorMessage: 'Quantidade de pontos inválido', isValid: false, mandatory: true, }, { id: 'pagValue', errorMessage: 'Valor da Conta inválido', isValid: false, mandatory: true, }, { id: 'pagTotal', errorMessage: 'Valor Total inválido', isValid: false, mandatory: true, }, ], currentBarCodeMask: '', ready: function () { if (jQuery('.page-template-page-ecom-pagemento-php').length) { self.load(); } }, load: function () { self.eventHandler(); self.preLoadAdjust(); }, preLoadAdjust: function () { if (jQuery("#tipoConta").hasClass("select2-hidden-accessible")) { jQuery("#tipoConta").select2('destroy'); } jQuery('#pagValue, #pagDesconto').mask("#.##0,00", {reverse: true}); jQuery('#remainingPoints').mask("#.##0,00", {reverse: true}); jQuery('#userPoints').mask("#.##0,00", {reverse: true}); jQuery('#pagCellular').mask("(00) 00000-0000"); // jQuery("#pagCPF").mask('9999999999'); jQuery("#pagVencimento, #pagPagamento").mask('99/99/9999'); }, eventHandler: function () { jQuery(document).on('keyup', '#pagBarcode', self.barCodeMaskUpdate); jQuery(document).on('change', '#pagBarcode', self.checkBarcode); jQuery(document).on('keyup', '#pagCellular', self.telefoneValidation); jQuery(document).on('change', '#pagVencimento', self.validateDate); jQuery(document).on('keyup', '#pagValue, #pagDesconto', self.calcConta); jQuery(document).on('click', '#calculatePoint', self.calculateWithUserPoints); jQuery(document).on('click', '#myProofs', self.openExtratoTable); jQuery(document).on('click', '#billPay', self.toggleContaForm); jQuery(document).on('click', '#previous', self.openComoFunctionTable); jQuery(document).on('click', '.failure #next', self.openExtratoTable); jQuery(document).on('click', '.pagemento-account-form #next', self.send); jQuery(document).on('click', '.btnComprovante', self.openExtratoTable); jQuery(document).on('click', '.toback', self.toggleContaForm); jQuery(document).on('click', '.openPedido', self.openPedido); jQuery(document).on('change', '#userPoints', self.addDecimalUserPoints); jQuery(document).on('change', '#tipoConta, #pagValue, #pagPontos, #pagTotal', self.checkFields); }, openPedido: function (e) { e.preventDefault(); window.location.href = window.location.protocol + "//" + document.location.host + "/seus-pedidos/"; }, addDecimalUserPoints: function () { var givenValue = jQuery(this).val(); if (givenValue && givenValue.length <= 2) { jQuery(this).val(givenValue + ',00'); } }, openExtratoTable: function () { window.location.href = window.location.protocol + "//" + document.location.host + "/seus-comprovantes/"; }, validateDate: function () { if (moment(jQuery('#pagVencimento').val(), 'DD/MM/YYYY').isValid()) { self.updateFieldValiation('pagVencimento', true); } else { self.updateFieldValiation('pagVencimento', false); } }, checkFields() { var data = jQuery(this).val(); if (data) { self.updateFieldValiation(jQuery(this).attr('id'), true); } else { self.updateFieldValiation(jQuery(this).attr('id'), false); } self.mandatoryFieldCheck(); }, mandatoryFieldCheck: function (printErrorMessage) { var isFormValid = true; self.fieldsToValidate.forEach(function (element) { if (element.isValid || jQuery('#' + element.id).val()) { } else { isFormValid = false; if (printErrorMessage) { agco.helper.formValidationLabelCreate(element.id, element.errorMessage); jQuery('#' + element.id).parent('div').addClass('error-field'); } } }); if (isFormValid) { jQuery('#next').removeClass('btn-gray'); jQuery('#next').addClass('btn-green'); } else { jQuery('#next').addClass('btn-gray'); jQuery('#next').removeClass('btn-green'); } }, loadReceipts: function () { var endPoint = self.endpoints.receipts; var from = jQuery("#from").val(); var to = jQuery("#to").val(); var data = { from_date: moment(from, 'DD/MM/YYYY').format("YYYY-MM-DD"), to_date: moment(to, 'DD/MM/YYYY').format("YYYY-MM-DD") }; agco.helper.appApiRequest(endPoint, 'POST', data, true, self.populateReceiptTable, self.errorCreate); }, populateReceiptTable: function (data) { jQuery(".voucher-details").show(); var tbody = jQuery("#voucher-content").html(''); jQuery.each(data, function (i, value) { var line = jQuery(""); var data = new Date(value.entrydate); line.append(jQuery('').html( data.getDate() + '/' + (data.getMonth() + 1) + '/' + data.getFullYear() )); //amount var points = parseFloat(value.points); line.append(jQuery('').html(points.toFixed(2))); line.append(jQuery('').html(value.valordaconta)); line.append(jQuery('').html(value.receiptid)); line.append(jQuery('').html(value.orderid)); line.append(jQuery('').html( value.status === 'completo' ? "Baixar" : value.status.toUpperCase() )); tbody.append(line); }); }, toggleContaForm: function (e) { e.preventDefault(); if (jQuery('.customBreadCrum').length) { jQuery('.customBreadCrum').remove(); } var customBreadCrum = jQuery('', { class: 'customBreadCrum', href: '#', html: 'PAGUE CONTAS' }); var customText = jQuery('', { class: 'customBreadCrum', html: ' > ' }); jQuery('.woocommerce-breadcrumb').append(customText); jQuery('.woocommerce-breadcrumb').append(customBreadCrum); jQuery('#pagementoContasModal').prop('hidden', false); jQuery('.pagemento-container').prop('hidden', true); jQuery('.btn-group').prop('hidden', true); jQuery('.single-recharge-content>.pagemento-title').hide(); jQuery('.pagemento-rules').prop('hidden', true); jQuery('#contaModal .success').prop('hidden', true); jQuery('#contaModal .failure').prop('hidden', true); }, openComoFunctionTable: function (e) { e.preventDefault(); if (jQuery('.customBreadCrum').length) { jQuery('.customBreadCrum').remove(); } jQuery('#pagementoContasModal').prop('hidden', true); jQuery('.pagemento-container').prop('hidden', false); jQuery('.btn-group').prop('hidden', false); jQuery('.single-recharge-content>.pagemento-title').show(); jQuery('.pagemento-rules').prop('hidden', false); jQuery('#contaModal .failure').prop('hidden', true); }, telefoneValidation: function () { var cellular = jQuery(this).val(); if (cellular.replace(/\D/g, '').length >= 11) { self.updateFieldValiation('pagCellular', true); self.mandatoryFieldCheck(); } else { self.updateFieldValiation('pagCellular', false); self.mandatoryFieldCheck(); jQuery('#next').addClass('btn-gray'); jQuery('#next').removeClass('btn-green'); } }, updateFieldValiation: function (elementID, status) { self.fieldsToValidate.forEach(function (element) { if (element.id === elementID) { if (!jQuery('#' + elementID).val() && !element.mandatory) { element.isValid = true; agco.helper.formValidationLabelRemove(element.id); jQuery('#' + element.id).parent('div').removeClass('error-field'); return false; } element.isValid = status; if (!status) { agco.helper.formValidationLabelCreate(element.id, element.errorMessage); jQuery('#' + element.id).parent('div').addClass('error-field'); } else { agco.helper.formValidationLabelRemove(element.id); jQuery('#' + element.id).parent('div').removeClass('error-field'); } } }); }, barCodeMaskUpdate: function () { var barCodeValue = jQuery("#pagBarcode").val(); var that = this; //var toUpdateMask = barCodeValue.replace(/\D/g, '').length <= 12 ? '9999999999999' : '999999999999-999999999999-999999999999-999999999999'; var toUpdateMask = '999999999999-999999999999-999999999999-999999999999'; if (self.currentBarCodeMask != toUpdateMask) { setTimeout(function () { that.selectionStart = that.selectionEnd = 10000; }, 0); } self.currentBarCodeMask = toUpdateMask jQuery("#pagBarcode").mask(toUpdateMask); if (barCodeValue.replace(/\D/g, '').length >= 12) { self.updateFieldValiation('pagBarcode', true); } else { self.updateFieldValiation('pagBarcode', false); } }, calculateWithUserPoints: function () { var userMentionedPoints = jQuery("#userPoints").val().replace(/\./g, ''); var unMaskedValue = userMentionedPoints.replace(',', '.'); if (!parseInt(userMentionedPoints)) { return false; } jQuery("#payPoints").val(unMaskedValue); var remainingPoint = self.calculatePoints(parseFloat(unMaskedValue)); var formatedRemainingPoint = agco.helper.ptBrNumberFormat(remainingPoint, true); jQuery("#availPoints").val(formatedRemainingPoint + ' pts'); }, calculatePoints: function (value) { var updatedValue = value * globalJsData.conversion_factor / 0.88; return isNaN(updatedValue) ? 0 : updatedValue.toFixed(2); }, calcConta: function () { var descento = jQuery("#pagDesconto").val(); var valor = jQuery("#pagValue").val(); jQuery('#pagPontos').change(); if (!descento) { descento = '0'; } if (!valor) { return false; } var tempDecento = parseFloat(descento.replace('.', '').replace(',', '.')); var tempValor = parseFloat(valor.replace('.', '').replace(',', '.')); if (!tempDecento) { tempDecento = 0; } if (!tempValor) { tempValor = 0; } var valorTotal = tempValor - tempDecento; jQuery("#pagTotal").val(agco.helper.ptBrNumberFormat(parseFloat(valorTotal), true)); jQuery("#pagPontos").val(agco.helper.ptBrNumberFormat(parseFloat(self.calculatePoints(parseFloat(valorTotal))), true)); jQuery("#pagTotal").trigger('change'); jQuery("#pagPontos").trigger('change'); }, checkBarcode: function () { self.mandatoryFieldCheck(); var $this = jQuery(this); var barcode = $this.val(); agco.helper.loader('show'); var endPoint = self.endpoints.checkBarcode; agco.helper.appApiRequest(endPoint, 'GET', {barcode: barcode}, true, function (response) { if (response.status == true) { response.data = JSON.parse(response.data); if (response.data.Valor || response.data.Vencimento) { var valor = parseFloat(response.data.Valor); jQuery("#pagValue").val(agco.helper.ptBrNumberFormat(valor, true)); self.calcConta(); jQuery("#pagVencimento").val(response.data.Vencimento); } } else { agco.helper.popUp('Error', 'Código de barras ou linha digitável inválidos.'); $this.focus(); } agco.helper.loader('hide'); }, function () { agco.helper.loader('hide'); }); }, send: function (e) { e.preventDefault(); if (!jQuery('#next').hasClass('btn-green')) { self.mandatoryFieldCheck(true); return false; } var data = self.validate(); if (data) { var endPoint = self.endpoints.create; agco.helper.appApiRequest(endPoint, 'POST', data, true, self.successCreate, self.errorCreate); } else { agco.helper.loader('hide'); } }, successCreate: function (response) { agco.helper.loader('hide'); try { response = JSON.parse(response); } catch (e) { // console.log('Nao convertei'); } var msg = ''; if (typeof response === 'object') { if (response.data && response.data.Id) { msg = "Conta registrado com sucesso."; location.hash = 'close'; self.showSuccessMessage(msg); return; } else if (typeof response.data === 'string') { msg = response.data; } else { for (var i in response.data) { if (response.data[i]) { msg += response.data[i] + "
    "; } else { msg += "Não foi possível realizar o pagamento no momento, tente mais tarde.
    " + "Verifique na tela 'Seus Pedidos' se a transação não foi mesmo realizada antes de tentar novamente. "; self.showErrorContent(msg); } } } } else { msg = response.data ? response.data : response; } if (!msg) { msg = "NÃO FOI POSSÍVEL COMPLETAR A TRANSAÇÃO, TENTE MAIS TARDE.
    " + "Verifique na tela 'Seus Pedidos' se a transação não foi mesmo realizada antes de tentar novamente"; } self.showErrorContent(msg); // agco.helper.popUp('Info', msg); }, errorCreate: function (jqXHR, textStatus, errorString) { agco.helper.loader('hide'); agco.helper.popUp('Error', errorString); self.showErrorContent(''); }, showErrorContent: function (message) { jQuery('#pagementoContasModal').prop('hidden', true); jQuery('#contaModal .success').prop('hidden', true); jQuery('#contaModal .failure').prop('hidden', false); jQuery('#contaModal').prop('hidden', false); if (message) { jQuery('#contaModal .failure h1').html(message); } }, showSuccessMessage: function (message) { jQuery('#pagementoContasModal').prop('hidden', true); jQuery('#contaModal .success').prop('hidden', false); jQuery('#contaModal .failure').prop('hidden', true); jQuery('#contaModal').prop('hidden', false); if (message) { jQuery('#contaModal .success h1').html(message); } }, validate: function () { var barcode = jQuery("#pagBarcode").val().replace('-', ''); var valor = jQuery("#pagValue").val(); var vencimento = jQuery("#pagVencimento").val(); var points = jQuery('#pagPontos').val(); var desconto = jQuery('#pagDesconto').val(); valor = parseFloat(valor.replace('.', '').replace(',', '.')); points = parseFloat(points.replace('.', '').replace(',', '.')); barcode = barcode.replace('-', ''); agco.helper.loader('show'); var i = 0; jQuery.each(self.pageMentoFields, function (index, value) { if (jQuery('#' + value).val() === '') { jQuery('#' + value).focus(); event.preventDefault(); return false; } i++; }); if ((i < 5 || barcode.length < 40 || !(valor > 0 && valor < 250000))) { agco.helper.loader('hide'); self.updateFieldValiation('pagBarcode', false); return false; } return { expiration: vencimento, barcode: barcode, value: valor, points: points, discount: desconto }; }, }; return self; }(); jQuery(document).ready(function () { agco.contaPage.ready(); }); agco.contactPage = function () { var self = { endPoints: { 'history': 'v1/contact/history', }, contactForm: [ { id: 'name', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'email', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'telephone', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'subject', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'message', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, ], ready: function () { if (jQuery('.page-template-page-contact-us').length) { self.load(); } }, load: function () { self.eventHandler(); self.preLoadAdjust(); self.listenAjaxCall(); }, eventHandler: function () { jQuery(document).on('change', '#name', self.nameValidation); jQuery(document).on('change', '#email', self.emailValidation); jQuery(document).on('keyup', '#telephone', self.telefoneValidation); jQuery(document).on('change', '#subject', self.subjectValidation); jQuery(document).on('change', '#message', self.messageValidation); jQuery(document).on('click', '#btn_submit', self.submitForm); jQuery(document).on('click', '#history-tab', self.getHistoryList); jQuery(document).on('click', '.buttonBack', self.toBack); }, toBack: function (e) { e.preventDefault(); history.back() }, getHistoryList: function () { var endpoint = self.endPoints.history; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'GET', {}, true, self.getHistoryListSuccess, self.getHistoryListError); }, getHistoryListSuccess: function (success) { agco.helper.loader('hide'); jQuery('.history-holder').html(''); if (!success || !success.length) { agco.helper.popUp('Error', "Nenhuma lista encontrada."); return false; } success.forEach(element => { var holder = jQuery('
    ', { }); var heading = jQuery('

    ', { html: element['your-subject'] }); var content = jQuery('

    ', { html: element['your-message'] }); jQuery(heading).appendTo(holder); jQuery(content).appendTo(holder); jQuery(holder).appendTo('.history-holder'); }); }, getHistoryListError: function (error) { agco.helper.loader('hide'); jQuery('.history-holder').html(''); agco.helper.popUp('Error', "Nenhuma lista encontrada."); }, emailValidation: function () { var email = jQuery(this).val(); if (email && agco.helper.emailRegex.test(email)) { self.updateValidatedStatus('email', true); } else { self.updateValidatedStatus('email', false); } }, subjectValidation: function () { var subject = jQuery(this).val(); if (subject && subject.trim()) { self.updateValidatedStatus('subject', true); } else { self.updateValidatedStatus('subject', false); } }, messageValidation: function () { var message = jQuery(this).val(); if (message && message.trim()) { self.updateValidatedStatus('message', true); } else { self.updateValidatedStatus('message', false); } }, nameValidation: function () { var name = jQuery(this).val(); if (name) { self.updateValidatedStatus('name', true); } else { self.updateValidatedStatus('name', false); } }, submitForm: function (e) { var preventLoopFlag = false; self.contactForm.forEach(function (element) { if (!element.isValid && element.mandatory) { preventLoopFlag = true; agco.helper.formValidationLabelCreate(element.id, element.errorMessage); jQuery('#' + element.id).parents('label').addClass('error-field'); } else if (element.isValid) { agco.helper.formValidationLabelRemove(element.id); jQuery('#' + element.id).parents('label').removeClass('error-field'); } else { } }); if (preventLoopFlag) { e.preventDefault(); } else { agco.helper.loader('show'); return true; } }, telefoneValidation: function () { var cellular = jQuery(this).val(), cellularField = jQuery(this); if (!cellular || cellular.replace(/\D/g, '').length < 11) { cellularField.mask("(00) 0000-00000"); } else { cellularField.mask("(00) 00000-0000"); } if (cellular.length > 13) { self.updateValidatedStatus('telephone', true); } else { self.updateValidatedStatus('telephone', false); } }, updateValidatedStatus: function (elementID, status) { self.contactForm.forEach(function (element) { if (element.id === elementID) { if (!jQuery('#' + elementID).val() && !element.mandatory) { element.isValid = true; self.formValidationLabelRemove(element.id); jQuery('#' + element.id).parents('label').removeClass('error-field'); return false; } element.isValid = status; if (!status) { self.formValidationLabelCreate(element.id, element.errorMessage); jQuery('#' + element.id).parents('label').addClass('error-field'); } else { self.formValidationLabelRemove(element.id); jQuery('#' + element.id).parents('label').removeClass('error-field'); } } }); // console.log(self.contactForm); }, formValidationLabelRemove: function (element) { if (jQuery('#' + element).parent().find('.error').length) { jQuery('#' + element).parent().find('label.error').remove(); jQuery('#' + element).removeClass('error'); } }, formValidationLabelCreate: function (element, errorMessage) { var errorClassName = 'error'; var errorLabel = jQuery('Baixar"; } else { text = rowObject.status.toUpperCase(); } return text; } }, ], ready: function () { if (jQuery('.page-template-page-ecom-my-vouchers').length) { self.load(); } }, load: function () { // self.eventHandler(); self.loadDataTable(); }, eventHandler: function () { jQuery(document).on('click', '.extrato-page-period button', self.searchExtrado); jQuery(document).on('change', '#start-date', self.validateDate); jQuery(document).on('change', '#ending-date', self.validateDate); }, loadDataTable: function (data) { var endPoint = self.endpoint.receipt; var url = agco.helper.baseUrl + endPoint; agco.helper.loadDataTable('extrato-period-page-table', url, '.extrato-page-period-detail', self.columns, data); jQuery('[name="extrato-period-page-table_length"]').hide(); jQuery('#extrato-period-page-table_info').hide(); }, searchExtrado: function () { if (!self.isValidDate) { agco.helper.formValidationLabelCreate('filter', 'Selecione entre a data e a data.', 'title-red'); return false; } var startDate = jQuery("#start-date").val(); var endDate = jQuery("#ending-date").val(); var data = { start_date: startDate, end_date: endDate }; self.loadDataTable(data); }, validateDate: function () { if (jQuery("#start-date").val() && jQuery("#ending-date").val()) { agco.helper.formValidationLabelRemove('filter'); if (moment(jQuery("#ending-date").val()).diff(jQuery("#start-date").val()) <= 0) { self.isValidDate = false; agco.helper.formValidationLabelCreate('filter', 'A data atual não pode ser menor que a data.', 'title-red'); } else { self.isValidDate = true; agco.helper.formValidationLabelRemove('filter'); } } else { self.isValidDate = false; agco.helper.formValidationLabelCreate('filter', 'Selecione entre a data e a data.', 'title-red'); } }, }; return self; }(); jQuery(document).ready(function () { agco.voucherPage.ready(); }); agco.aprenda = function () { var self = { ready: function () { if (jQuery('.learndash-cpt').length) { self.load(); } }, load: function () { if (window.parent.frames[0] == window.self) { jQuery('.video-date').hide(); // console.log('loaded in iframe'); jQuery('body').addClass('iframe-mobile-app'); jQuery('header').hide(); jQuery('footer').hide(); jQuery('.container.header-accordion').hide(); jQuery('.wpProQuiz_sending').insertAfter(jQuery('.wpProQuiz_quiz')); jQuery(".sfwd-courses .learndash-course-complete-message .course-success .justify-center").hide() // jQuery('.title-block').hide(); self.listenAjaxCall(); } else { self.eventHandler(); // self.preventRedirect(); } }, eventHandler: function () { }, listenAjaxCall: function () { jQuery(document).ajaxComplete(function (event, request, settings) { if (settings && settings.url.indexOf('/admin-ajax.php') <= 0) { return false; } if (request && request.status === 200) { if (request.responseJSON) { var data = request.responseJSON; var keys = Object.keys(data); if (!keys.length) { return false; } if (!data[keys[0]]) { return false; } var innerKeys = Object.keys(data[keys[0]]); if (innerKeys[0] == "quiz_result_settings") { // jQuery('figure').hide(); // jQuery('.title-block').hide(); // jQuery('.glow').hide(); // jQuery('.ld-tabs-content div.ld-tab-content p').hide(); // jQuery('.wpProQuiz_button_restartQuiz').show(); } } else { } } }); }, preventRedirect: function () { window.onbeforeunload = function () { return false; }; }, }; return self; }(); jQuery(document).ready(function () { agco.aprenda.ready(); }); agco.timeLine = function () { var self = { endPoint: { achievement: "v1/post/achievement", achievementAdmin: "v1/post/achievement/admin", comment: "v1/post/comment", emoji: "v1/post/emoji", commentLike: "v1/post/comment/emoji", }, monthArray: ["", "JAN", "FEV", "MAR", "ABR", "MAI", "JUN", "JUL", "AGO", "SET", "OUT", "NOV", "DEZ"], monthNameFullName: ["", "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"], currentPage: 1, postsPerPage: 10, postID: '', thisHolder: '', emojiToken: '', previousLikeCount: '', replyCommentData: {}, deleteReplyData: {}, firsttLoad: true, postCallFlag: true, deletePostId: "", newPublishedPostId: "", allowedUser: ['13109429780'], preventMultiComment: false, load: function () { jQuery(document).ready(function () { self.ready(); jQuery('body').on('click', 'button#scroll-top', self.focusTop); }); }, ready: function () { self.eventHandlers(); if (jQuery('.page-template-page-my-timeline').length || jQuery('.page-template-page-my-timeline_test').length) { jQuery('.add-post').attr('hidden', true); self.makeScrollable(); self.getPosts(); self.addRefreshPost(); self.getInfiniteScroll(); self.setPlaceholderInDescription(); } }, setPlaceholderInDescription: function (params) { var userName; try { userName = globalJsData.user.data.display_name; } catch (error) { userName = ''; } if (userName) { jQuery('#description').attr('placeholder', 'Ei, ' + userName + '! Deixe aqui sua mensagem!'); } }, focusTop: function () { jQuery('html, body').animate({ scrollTop: jQuery('body').offset().top }, 500); }, eventHandlers: function () { jQuery('button#add-new-post').on('click', self.addNewPost); jQuery('body').on('click', '.reaction-content a', self.addReaction); jQuery('body').on('click', '.add-new-comment', self.addNewComment); jQuery('body').on('click', '.delete-comment', self.deleteComment); jQuery('body').on('change', 'input#post-media', self.checkPostFile); jQuery('body').on('change', 'textarea.textarea', self.checkTitle); jQuery('body').on('click', 'button.replyComment', self.replyComment); jQuery('body').on('click', 'button.remove-reply', self.removeReply); jQuery('body').on('click', '.comment-reactions-count a', self.likeComment); jQuery("body").on("click", '.show-more-comments', self.showMoreComments); jQuery("body").on("click", '.show-more-replies', self.showMoreReplies); jQuery("body").on("click", '.refresh-post', self.refreshPost); jQuery("body").on("click", '.delete-post-button', self.getDeletePostID); jQuery("body").on("click", '#delete-post', self.deleteUserPost); jQuery("body").on("click", '.replyToggle', self.toggleReplyField); // jQuery("body").on("click", '.toggleComment', self.toggleCommentField); // jQuery("body").on("click", '.faceBookShare', self.shareOnFB); // jQuery("body").on("click", '#skyPost', self.toggleBetweenPostList); // jQuery("body").on("click", '#myPost', self.toggleBetweenPostList); jQuery("body").on("click", '.load-more', self.getPosts); }, timeLineLoader: function (action) { if (action == 'show') { agco.helper.loader('show'); jQuery('.timeline-loader').css('display', 'block'); } else { agco.helper.loader('hide'); jQuery('.timeline-loader').css('display', 'none'); } }, toggleBetweenPostList: function () { var selectedId = jQuery(this).attr('id'); if (selectedId == 'skyPost') { jQuery('#skyPost').addClass('active'); jQuery('#myPost').removeClass('active'); jQuery('.add-post').attr('hidden', true); } else { jQuery('.add-post').attr('hidden', false); jQuery('#myPost').addClass('active'); jQuery('#skyPost').removeClass('active'); } self.currentPage = 1; jQuery(".post-list").empty(); self.getPosts(); }, shareOnFB: function () { var text = jQuery(this).parents('.reaction-content').siblings('.single-post-content').find('p p').html(); var imgLink = jQuery(this).parents('.reaction-content').siblings('.post-image').find('img').attr('src'); if (!imgLink) { imgLink = ''; } if (!text) { text = ''; } // // // // // jQuery('', { property: 'og:url', content: location.origin }).appendTo(jQuery('head')); jQuery('', { property: 'og:type', content: 'article' }).appendTo(jQuery('head')); jQuery('', { property: 'og:title', content: 'location.origin' }).appendTo(jQuery('head')); jQuery('', { property: 'og:description', content: text }).appendTo(jQuery('head')); jQuery('', { property: 'og:image', content: imgLink }).appendTo(jQuery('head')); // window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(location.origin)); return false; window.open('https://www.facebook.com/sharer.php?u=' + encodeURIComponent('https://jddev2.scit.pt/'), 'sharer', 'toolbar=0,status=0,width=626,height=436'); return false; }, toggleCommentField: function () { if (jQuery(this).siblings('.new-comment').hasClass('hide')) { jQuery(this).siblings('.new-comment').removeClass('hide'); jQuery(this).siblings('.new-comment').show(); } else { jQuery(this).siblings('.new-comment').addClass('hide'); jQuery(this).siblings('.new-comment').hide(); } }, toggleReplyField: function () { if (jQuery(this).parents('.comment_holder').find('.new-reply').hasClass('hide')) { jQuery(this).parents('.comment_holder').find('.new-reply').removeClass('hide'); jQuery(this).parents('.comment_holder').find('.new-reply').show(); } else { jQuery(this).parents('.comment_holder').find('.new-reply').addClass('hide'); jQuery(this).parents('.comment_holder').find('.new-reply').hide(); } }, deleteUserPost: function () { if (self.deletePostId) { let endpoint = self.endPoint.achievement + "?cpf=" + agco.helper.getCpf() + "&post_id=" + self.deletePostId; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'DELETE', {}, true, self.successCallBackDeleteUserPost, self.errorCallBackDeleteUserPost); } }, getEmojiParsedString: function (str) { if (!str) { return str; } var rx = /([\uD800-\uDBFF][\uDC00-\uDFFF](?:[\u200D\uFE0F][\uD800-\uDBFF][\uDC00-\uDFFF]){2,}|\uD83D\uDC69(?:\u200D(?:(?:\uD83D\uDC69\u200D)?\uD83D\uDC67|(?:\uD83D\uDC69\u200D)?\uD83D\uDC66)|\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D(?:\uD83D\uDC69\u200D)?\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D(?:\uD83D\uDC69\u200D)?\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]\uFE0F|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC6F\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3C-\uDD3E\uDDD6-\uDDDF])\u200D[\u2640\u2642]\uFE0F|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F\u200D[\u2640\u2642]|(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642])\uFE0F|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\uD83D\uDC69\u200D[\u2695\u2696\u2708]|\uD83D\uDC68(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708]))\uFE0F|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83D\uDC69\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|\uD83D\uDC68(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:(?:\uD83D[\uDC68\uDC69])\u200D)?\uD83D\uDC66\u200D\uD83D\uDC66|(?:(?:\uD83D[\uDC68\uDC69])\u200D)?\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92])|(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]))|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDD1-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\u200D(?:(?:(?:\uD83D[\uDC68\uDC69])\u200D)?\uD83D\uDC67|(?:(?:\uD83D[\uDC68\uDC69])\u200D)?\uD83D\uDC66)|\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC69\uDC6E\uDC70-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD26\uDD30-\uDD39\uDD3D\uDD3E\uDDD1-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])?|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDEEB\uDEEC\uDEF4-\uDEF8]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD4C\uDD50-\uDD6B\uDD80-\uDD97\uDDC0\uDDD0-\uDDE6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267B\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEF8]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD4C\uDD50-\uDD6B\uDD80-\uDD97\uDDC0\uDDD0-\uDDE6])\uFE0F)/; var res = str.split(rx).filter(Boolean); var parsedString = ""; res.forEach(function (word) { if (word.match(rx)) { parsedString = parsedString + "&#" + word.codePointAt() + ";"; } else { parsedString = parsedString + word; } }); return parsedString; }, getDeletePostID: function () { self.deletePostId = jQuery(this).attr("id"); }, successCallBackDeleteUserPost: function (success) { // console.log("Delete user post success ", success); agco.helper.loader('hide'); if (success.code === "delete_achievement_success") { jQuery("#" + self.deletePostId).closest('.single-post').remove(); jQuery("#deletePopup").modal('hide'); } }, errorCallBackDeleteUserPost: function (error) { agco.helper.loader('hide'); // console.log("Delete user post error ", error); }, showMoreReplies: function () { if (!jQuery(this).hasClass('showLess')) { jQuery(this).parent().find('div.replySlice').show(); jQuery(this).addClass('showLess'); jQuery(this).html('Ver menos respostas'); } else { jQuery(this).parent().find('div.replySlice').each(function (index, ele) { if (index > 1) { jQuery(ele).hide(); } }); jQuery(this).removeClass('showLess'); jQuery(this).html('Ver mais respostas'); } }, showMoreComments: function () { if (!jQuery(this).hasClass('showLess')) { jQuery(this).parents('.single-post').find('.comment_holder').show(); jQuery(this).addClass('showLess'); // jQuery(this).html('MENOS COMENTÁRIOS'); } else { jQuery(this).parents('.single-post').find('.comment_holder').each(function (index, ele) { if (index > 2) { jQuery(ele).hide(); } }); jQuery(this).removeClass('showLess'); // jQuery(this).html('MAIS COMENTÁRIOS'); } }, likeComment: function (e) { e.preventDefault(); let endpoint = self.endPoint.commentLike; let emojiIndex = jQuery(this).parent().index() + 1; let commentId = jQuery(this).parents('.comment-reactions-count').siblings('div.like-reply').attr('id').split('like_')[1]; let postId = jQuery(this).parents('.comment-section').siblings('.new-comment').attr('id').split('_')[1]; let data = { 'emoji_id': emojiIndex.toString(), 'comment_id': commentId.toString(), 'post_id': postId.toString(), "cpf": agco.helper.getCpf() } self.timeLineLoader('show'); agco.helper.appApiRequest(endpoint, 'POST', data, true, function (success) { self.timeLineLoader('hide'); if (success['code'] === 'update_comment_emoji_success') { let reactionCount = parseInt(success['data']['emoji_1_count']); reactionCount = reactionCount ? reactionCount : ''; jQuery('div#comment_reaction_' + commentId).find('.icon a p').html(reactionCount); let likeEmoji = jQuery('div#comment_reaction_' + commentId).find(".emoji li").get(0); jQuery(likeEmoji).toggleClass('like'); if (jQuery(likeEmoji).hasClass('like')) { var src = jQuery(likeEmoji).find('img').attr('src'); src = src.replace('like-icon', 'like-icon-red'); jQuery(likeEmoji).find('img').attr('src', src); } else { var src = jQuery(likeEmoji).find('img').attr('src'); src = src.replace('like-icon-red', 'like-icon'); jQuery(likeEmoji).find('img').attr('src', src); } } }, function (error) { self.timeLineLoader('hide'); // console.log(error); }); }, removeReply: function () { jQuery(this).parent().remove(); self.deleteReplyData = { replySection: jQuery(this).parent() }; }, successCallBackRemoveReply: function (success) { self.timeLineLoader('hide'); self.deleteReplyData.replySection.remove() }, errorCallBackRemoveReply: function (error) { self.timeLineLoader('hide'); // console.log('error ReplyComment', error); }, replyComment: function () { let commentId = jQuery(this).attr('id').split('replyBtn_')[1]; let commentContent = jQuery(this).siblings('input').val(); if (!commentContent && !jQuery(this).siblings('input[type="file"]').val()) { return false; } if (commentContent) { commentContent = self.getEmojiParsedString(jQuery(this).siblings('input').val()); } self.replyCommentData = { replySection: jQuery(this).prev(), commentId: commentId, commentContent: commentContent, } let commentField = jQuery(this).parent().parent().parent().parent().closest('.single-post').find('.add-new-comment'); self.postID = jQuery(commentField).attr('id'); self.thisHolder = jQuery(commentField); let endpoint = self.endPoint.comment; let replyData = new FormData(); if (jQuery(this).siblings('input[type="file"]').val()) { replyData.append('file', new Blob(jQuery(this).siblings('input[type="file"]').prop('files'), {type: 'image/jpg'}), jQuery(this).siblings('input[type="file"]').prop('files')[0]['name']); } replyData.append('comment_post_id', self.postID); replyData.append('cpf', agco.helper.getCpf()); replyData.append('comment_content', commentContent); replyData.append('comment_parent_id', commentId); replyData.append('orgin', 'site'); jQuery(this).siblings('input').val(''); self.timeLineLoader('show'); agco.helper.appApiRequest(endpoint, 'POST', replyData, true, self.successReplyComment, self.errorCallBackReplyComment); }, successReplyComment: function (success) { // console.log('success ReplyComment', success); self.timeLineLoader('hide'); self.getExactComment(); }, errorCallBackReplyComment: function (error) { self.timeLineLoader('hide'); // console.log('error ReplyComment', error); }, deleteComment: function () { let commentId = jQuery(this).attr('id'); self.thisHolder = jQuery(this).closest('.single-post').find('button.add-new-comment'); self.postID = jQuery(self.thisHolder).attr('id'); // console.log(self.thisHolder, self.postID); let endpoint = self.endPoint.comment; let commentData = { "comment_id": commentId, "cpf": agco.helper.getCpf() } self.timeLineLoader('show'); agco.helper.appApiRequest(endpoint, 'DELETE', commentData, true, self.successCallBackDeleteComment, self.errorCallBackDeleteComment); }, successCallBackDeleteComment: function (success) { // console.log("successCallBackAddComment ", success); // self.getPosts(); self.timeLineLoader('hide'); self.getExactComment(); }, errorCallBackDeleteComment: function (error) { self.timeLineLoader('hide'); // console.log("errorCallBackAddComment ", error); }, makeScrollable: function () { jQuery('div.post-list').css('overflow-y', 'auto'); var timeLineHeight = '1750px'; setTimeout(() => { if (jQuery('.right-sidebar').css('height')) { timeLineHeight = jQuery('.right-sidebar').css('height'); timeLineHeight = timeLineHeight.replace('px', ''); timeLineHeight -= '150'; timeLineHeight += 'px'; } jQuery('div.post-list').css('height', timeLineHeight); }, 300); jQuery('div.post-list').css('height', timeLineHeight); }, addRefreshPost: function () { return false; jQuery('

    ', { class: 'refresh-post', html: '' }).insertAfter('div.post-list'); }, refreshPost: function () { jQuery('div.post-list').scrollTop(0); jQuery('html, body').animate({ scrollTop: jQuery('div.post-container').offset().top }, 200); }, getInfiniteScroll: function () { jQuery('div.post-list').on('scroll', function () { if (jQuery(this).scrollTop() === 0 && self.postCallFlag) { self.currentPage = 1; jQuery(".post-list").empty(); self.getPosts(); } // if (jQuery(this).scrollTop() + jQuery(this).innerHeight() >= jQuery(this)[0].scrollHeight && self.postCallFlag) { // self.getPosts(); // } }); }, addNewComment: function () { self.timeLineLoader('show'); if (self.preventMultiComment) { // return false; } self.preventMultiComment = true; let commentText = jQuery(this).parent().find('.comment-text').val(); let postId = jQuery(this).attr('id'); if (!commentText && !jQuery("#attachFile_" + postId).val()) { self.preventMultiComment = false; self.timeLineLoader('hide'); return false; } if (commentText) { commentText = self.getEmojiParsedString(commentText); } self.postID = postId; self.thisHolder = this; // console.log("Comment Text ", commentText); let comment = new FormData(); if (jQuery("#attachFile_" + postId).val()) { comment.append('file', new Blob(jQuery("#attachFile_" + postId).prop('files'), {type: 'image/jpg'}), jQuery("#attachFile_" + postId).prop('files')[0]['name']); } comment.append('comment_post_id', postId); comment.append('cpf', agco.helper.getCpf()); comment.append('comment_content', commentText); comment.append('orgin', 'site'); let endpoint = self.endPoint.comment; agco.helper.appApiRequest(endpoint, 'POST', comment, true, self.successCallBackAddComment, self.errorCallBackAddComment); }, successCallBackAddComment: function (success) { // console.log("successCallBackAddComment ", success); self.timeLineLoader('hide'); self.getExactComment(); self.preventMultiComment = false; }, errorCallBackAddComment: function (error) { self.timeLineLoader('hide'); // console.log("errorCallBackAddComment ", error); self.preventMultiComment = false; }, getExactComment: function () { let endpoint = self.endPoint.comment; let commentData = { "post_id": self.postID, "cpf": agco.helper.getCpf() } self.timeLineLoader('show'); agco.helper.appApiRequest(endpoint, 'GET', commentData, true, self.successGetExactComment, self.errorCallBackGetExactComment); }, successGetExactComment: function (success) { let singlePost = jQuery(self.thisHolder).parent().parent(); jQuery(self.thisHolder).parent().siblings('.comment-section').remove(); let reactions = jQuery('.source').find('ol')[0].outerHTML; jQuery('
    ', { class: 'new-comment new-comment_' + self.postID, id: 'new-comment_' + self.postID, }).appendTo(singlePost); let commentSection = jQuery('
    ', { class: 'comment-section' }).appendTo(singlePost); jQuery(self.thisHolder).parent().remove(); let cmtLength = Object.keys(success.data).length; jQuery('div.comment_count_' + self.postID).remove(); jQuery('
    ', { class: 'comment_count_' + self.postID + ' show-more-comments', html: cmtLength + ' Comentários' }).appendTo(jQuery('div.comment_toggle_' + self.postID)); // console.log('--------', self.postID); // jQuery('div.comment_count_' + self.postID).html(cmtLength + ' COMENTÁRIOS') Object.entries(success.data).forEach(function (comment, index) { let reactionCount = parseInt(comment[1][0]['emoji_1_count']); reactionCount = reactionCount ? reactionCount : ''; if (parseInt(comment[1][0]['comment_parent']) != 0) { if (jQuery('.reply_' + comment[1][0]['comment_parent']).length) { if (!jQuery('div#replyHolder_' + comment[1][0]['comment_parent']).length) { jQuery('
    ', { class: 'replyHolder', id: 'replyHolder_' + comment[1][0]['comment_parent'] }).prependTo(jQuery('.reply_' + comment[1][0]['comment_parent'])); } jQuery('
    ', { class: 'replySlice replySlice_' + comment[1][0]['comment_ID'] }).appendTo(jQuery('div#replyHolder_' + comment[1][0]['comment_parent'])); jQuery('', { class: 'reply-avatar', src: comment[1][0]['avatar_url'], }).appendTo(jQuery('div.replySlice_' + comment[1][0]['comment_ID'])); jQuery('
    ', { class: 'like-reply liked', id: 'like_' + comment[1][0]['comment_ID'], }).appendTo(jQuery('div.replySlice_' + comment[1][0]['comment_ID'])); jQuery('
    ', { class: 'comment-reactions-count d-flex', id: 'comment_reaction_' + comment[1][0].comment_ID, }).appendTo(jQuery('div.replySlice_' + comment[1][0]['comment_ID'])); jQuery('div#comment_reaction_' + comment[1][0].comment_ID).append(reactions); if (comment[1][0].current_user_emoji && comment[1][0].current_user_emoji != "0") { let likeEmoji = jQuery('div#comment_reaction_' + comment[1][0].comment_ID).find(".emoji li").get(0); jQuery(likeEmoji).addClass('like'); var src = jQuery(likeEmoji).find('img').attr('src'); src = src.replace('like-icon', 'like-icon-red'); jQuery(likeEmoji).find('img').attr('src', src); } jQuery('

    ', { html: reactionCount }).appendTo(jQuery('div#comment_reaction_' + comment[1][0].comment_ID).find(".icon a")); jQuery('

    ', { class: 'reply-comment', html: comment[1][0].comment_content }).prependTo(jQuery('div#like_' + comment[1][0]['comment_ID'])); jQuery('

    ', { class: 'userName-container', html: comment[1][0].user_name }).prependTo(jQuery('div#like_' + comment[1][0]['comment_ID'])); if (comment[1][0]['can_delete'] == "yes") { jQuery('", render: function (data, type, rowObject, metat) { return " "; } }, ], mechineColumns: [ { "data": "item", "title": "ITEM" }, { "data": "part_number_agco", "title": "PART NUMBER AGCO" }, { "data": "part_number_type", "title": "PART NUMBER CONCESSIONÁRIO" }, { "data": "", "title": "", render: function (data, type, rowObject, metat) { return " "; } }, ], lubform: [ { id: 'description', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'itemList', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'partNumberStationNew', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'partNumberTypeNew', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, } ], machineform: [ { id: 'description', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'itemList', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'partNumberStationNew', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, } ], ready: function () { if (jQuery('.page-template-page-de-para-pecas-e-lubrificantes').length) { this.isMaqunia = false; self.eventHandlers(); self.preLoadAdjust(); self.applySelectPagenation(); } else if (jQuery('.page-template-page-de-maquinas').length) { this.isMaqunia = true; self.eventHandlers(); self.preLoadAdjust(); self.applySelectPagenation(); } }, preLoadAdjust: function () { // jQuery('

    ', { // class: 'page-dePara-detail', // }).appendTo('#main'); self.getlist(); }, applySelectPagenation: function () { if (jQuery() && jQuery().select2) { jQuery("#itemList").select2({ minimumInputLength: 0, language: "pt-BR", ajax: { url: agco.helper.baseUrl + 'v1/adm/product/list/', dataType: 'json', type: 'POST', headers: {'x-auth-sb': globalJsData.token}, delay: 250, data: function (params) { var dataObject = { search_string: params.term ? params.term : '', // search term page: params.page || 1, post_per_page: 100, }; if (self.isMaqunia) { dataObject['product_type'] = 'machines'; } return dataObject; }, processResults: function (data, params) { params.page = params.page || 1; var arr = [] if (data.data) { jQuery.each(data.data, function (index, value) { if (value.code) { arr.push({ id: value.code, text: value.description + ' - ' + value.code }); } }); } return { results: arr, }; }, }, placeholder: 'PART NUMBER AGCO', }); } else { setTimeout(self.applySelectPagenation, 300); } }, eventHandlers: function () { jQuery(document).on('change', '#attach-xml', self.importSampleFile); jQuery(document).on('change', '#lubricants-attach-xml', self.importSampleFileLub); jQuery(document).on('click', '.addNew', self.showAddForm); jQuery(document).on('click', '#close', self.hideAddForm); jQuery(document).on('click', '#addNewPart', self.submitNewProduct); jQuery(document).on('click', '.editAction', self.editParts); jQuery(document).on('click', '.deleteAction', self.getDeleteDetail); jQuery(document).on('click', '#delete-post', self.deleteParts); jQuery(document).on('click', '.download-xl', self.exportBulk); jQuery(document).on('click', '.lubricants-download-xl', self.exportBulk); jQuery(document).on('click', '#machinery-tab', self.getlist); jQuery(document).on('click', '#lubricants-tab', self.getlist); }, exportBulk: function () { var date = new Date(); var minutes = 1; date.setTime(date.getTime() + (minutes * 60 * 1000)); var typeDown = ''; var typeDownLub = ''; var id; if (!jQuery(this).hasClass('lubricants-download-xl')) { if (!typeDown == true) { id = '&tabela=pecas'; var tipo = '&tipo=all' } else { id = ''; tipo = ''; } } else { id = '&tabela=lub'; if (!typeDownLub == true) tipo = '&tipo=all' else tipo = ''; } document.cookie = "x-auth-sb" + "=" + globalJsData.token + "; path=/;"; var endpoint = agco.helper.baseUrl + self.endpoints.downloadExcelSample + "?type=download" + id + tipo; window.open(endpoint, "_blank"); }, getDeleteDetail: function () { self.selectedData = {}; self.selectedData.part_number_type = jQuery(this).data('part_number_type'); self.selectedData.part_number_agco = jQuery(this).data('part_number_agco'); jQuery("#deletePopup").modal('show'); }, showAddForm: function () { self.lubform[1]['isValid'] = false; self.machineform[1]['isValid'] = false; self.backupAGCONum = ''; self.isEdit = false; self.resetForm(); jQuery('.addNewForm').attr('hidden', false); }, hideAddForm: function () { self.isEdit = false; jQuery('.addNewForm').attr('hidden', true); }, importSampleFile: function () { var data = jQuery('#attach-xml').val(); jQuery('.updateIntimation').remove(); if (data) { self.fileFlag = true; var FR = new FileReader(); jQuery('.attached-file-name').html(jQuery('#attach-xml').prop('files')[0]['name']); jQuery('#remove-xml').attr('hidden', false); var baseValue; FR.addEventListener("load", function (e) { if (FR.result.indexOf("data:") < 0) { self.fileFlag = false; // jQuery('.attached-file-name').html(''); jQuery('#attach-xml').val(''); } else { //baseValue = FR.result.split("data:application/pdf;base64,")[1]; if (FR.result.includes("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,")) { baseValue = FR.result.split("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,")[1]; self.getImageFile(baseValue, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then(function (data) { self.post_file = data; self.submitReport(); }, function (error) { jQuery('#attach-xml').val(''); // console.log(error); }); } else if (FR.result.includes("data:application/excel;base64,")) { baseValue = FR.result.split("data:application/excel;base64,")[1]; self.getImageFilePng(baseValue, 'application/excel').then(function (data) { self.post_file = data; self.submitReport(); }, function (error) { jQuery('#attach-xml').val(''); // console.log(error); }); } else if (FR.result.includes('data:application/vnd.ms-excel;base64,')) { baseValue = FR.result.split("data:application/vnd.ms-excel;base64,")[1]; self.getImageFilePng(baseValue, 'application/vnd.ms-excel').then(function (data) { self.post_file = data; self.submitReport(); }, function (error) { jQuery('#attach-xml').val(''); // console.log(error); }); } else { jQuery('#attach-xml').val(''); } } }); FR.readAsDataURL(jQuery('#attach-xml').prop('files')[0]); } else { self.fileFlag = false; // jQuery('.attached-file-name').html(''); } }, getImageFile: function (imageBase64, type) { return new Promise(function (resolve, reject) { var base64Blob = agco.helper.base64toBlob(imageBase64, type); resolve(base64Blob); }); }, getImageFilePng: function (imageBase64) { return new Promise(function (resolve, reject) { var base64Blob = agco.helper.base64toBlob(imageBase64, "application/excel;base64"); resolve(base64Blob); }); }, submitReport: function () { var endpoint = self.endpoints.addImportProduct; agco.helper.loader('show'); var data = new FormData; data.append('file', self.post_file); agco.helper.appApiRequest(endpoint, 'POST', data, true, self.submitReportSuccess, self.submitReportError); }, submitReportSuccess: function (success) { agco.helper.loader('hide'); if (!success) { agco.helper.popUp('Error', 'Erro ao enviar o arquivo. Entre em contato com o suporte'); return false; } else if (success.code == 'ERROR_error') { agco.helper.popUp('Error', success.message); return false; } agco.helper.popUp('Éxito', success.message); self.getlist(); }, submitReportError: function (error) { agco.helper.loader('hide'); agco.helper.popUp('Error', 'Erro ao enviar o arquivo. Entre em contato com o suporte'); }, //lub importSampleFileLub: function () { var data = jQuery('#lubricants-attach-xml').val(); jQuery('.updateIntimation').remove(); if (data) { self.fileFlag = true; var FR = new FileReader(); jQuery('.attached-file-name').html(jQuery('#lubricants-attach-xml').prop('files')[0]['name']); jQuery('#remove-xml').attr('hidden', false); var baseValue; FR.addEventListener("load", function (e) { if (FR.result.indexOf("data:") < 0) { self.fileFlag = false; // jQuery('.attached-file-name').html(''); jQuery('#lubricants-attach-xml').val(''); } else { //baseValue = FR.result.split("data:application/pdf;base64,")[1]; if (FR.result.includes("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,")) { baseValue = FR.result.split("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,")[1]; self.getImageFileLub(baseValue, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then(function (data) { self.post_file = data; self.submitReportLub(); }, function (error) { jQuery('#lubricants-attach-xml').val(''); // console.log(error); }); } else if (FR.result.includes("data:application/excel;base64,")) { baseValue = FR.result.split("data:application/excel;base64,")[1]; self.getImageFilePngLub(baseValue, 'application/excel').then(function (data) { self.post_file = data; self.submitReportLub(); }, function (error) { jQuery('#lubricants-attach-xml').val(''); // console.log(error); }); } else if (FR.result.includes('data:application/vnd.ms-excel;base64,')) { baseValue = FR.result.split("data:application/vnd.ms-excel;base64,")[1]; self.getImageFilePngLub(baseValue, 'application/vnd.ms-excel').then(function (data) { self.post_file = data; self.submitReportLub(); }, function (error) { jQuery('#lubricants-attach-xml').val(''); // console.log(error); }); } else { jQuery('#lubricants-attach-xml').val(''); } } }); FR.readAsDataURL(jQuery('#lubricants-attach-xml').prop('files')[0]); } else { self.fileFlag = false; // jQuery('.attached-file-name').html(''); } }, getImageFileLub: function (imageBase64, type) { return new Promise(function (resolve, reject) { var base64Blob = agco.helper.base64toBlob(imageBase64, type); resolve(base64Blob); }); }, getImageFilePngLub: function (imageBase64) { return new Promise(function (resolve, reject) { var base64Blob = agco.helper.base64toBlob(imageBase64, "application/excel;base64"); resolve(base64Blob); }); }, submitReportLub: function () { var endpoint = self.endpoints.addImportLub; agco.helper.loader('show'); var data = new FormData; data.append('file', self.post_file); agco.helper.appApiRequest(endpoint, 'POST', data, true, self.submitReportSuccess, self.submitReportError); }, submitReportSuccess: function (success) { agco.helper.loader('hide'); if (!success) { agco.helper.popUp('Error', 'Erro ao enviar o arquivo. Entre em contato com o suporte'); return false; } else if (success.code == 'ERROR_error') { agco.helper.popUp('Error', success.message); return false; } agco.helper.popUp('Éxito', success.message); self.getlist(); }, submitReportError: function (error) { agco.helper.loader('hide'); agco.helper.popUp('Error', 'Erro ao enviar o arquivo. Entre em contato com o suporte'); }, getlist: function () { if (jQuery('#lubricants-tab').hasClass('active')) { jQuery('.page-dePara-detail').html(''); return false; } else if (jQuery('#machinery-tab').hasClass('active')) { jQuery('.page-dePara-detail').html(''); return false; } else { } var endPoint = self.endpoints.getLubList; var url = agco.helper.baseUrl + endPoint; var customColumn = self.LubColumns; if (self.isMaqunia) { url = url + '?product_type=machines'; customColumn = self.mechineColumns; } agco.helper.loadDataTable('page-dePara-detail', url, '.page-dePara-detail', customColumn, {}); }, resetForm: function () { var form = 'lubform'; if (self.isMaqunia) { form = 'machineform'; } self[form].forEach(function (element) { jQuery('#' + element.id).val(''); }); jQuery('.select2-selection__placeholder').html('PART NUMBER AGCO'); }, checkValidation: function (e) { var preventLoopFlag = false; var form = 'lubform'; if (self.isMaqunia) { form = 'machineform'; } self[form].forEach(function (element) { if (element.isValid) { agco.helper.formValidationLabelRemove(element.id); jQuery('#' + element.id).parents('label').removeClass('error-field'); } else if (!jQuery('#' + element.id).val() && element.mandatory) { preventLoopFlag = true; agco.helper.formValidationLabelCreate(element.id, element.errorMessage); jQuery('#' + element.id).parents('label').addClass('error-field'); } else { } }); if (preventLoopFlag) { e.preventDefault(); return false; } else { return true; } }, submitNewProduct: function () { if (!self.checkValidation()) { return false; } var method; var endpoint = self.endpoints.addNewLub; var data = { 'item': jQuery('#description').val(), 'part_number_agco': '', 'part_number_service_station': jQuery('#partNumberStationNew').val(), 'part_number_type': jQuery('#partNumberTypeNew').val() }; if (self.isMaqunia) { data.part_number_type = ""; data.product_type = "machines"; } agco.helper.loader('show'); if (self.isEdit) { if (jQuery('#itemList').val()) { data.part_number_agco = jQuery('#itemList').val(); } else { data.part_number_agco = self.backupAGCONum; } method = 'PUT'; } else { data.part_number_agco = jQuery('#itemList').val(); method = 'POST'; } agco.helper.appApiRequest(endpoint, method, data, true, self.getProductListForAddNewSuccess, self.getProductListForAddNewError); }, getProductListForAddNewSuccess: function (success) { agco.helper.loader('hide'); if (!success || success.code !== "insert_single_product_new_success") { agco.helper.popUp('Error', success.message); return false; } self.isEdit = false; agco.helper.popUp('Éxito', success.message); jQuery('.page-dePara-detail table').DataTable().ajax.reload(); }, getProductListForAddNewError: function (error) { agco.helper.loader('hide'); }, editParts: function () { var selectedData = {}; selectedData.item = jQuery(this).data('item'); selectedData.part_number_agco = jQuery(this).data('part_number_agco'); selectedData.part_number_service_station = jQuery(this).data('part_number_service_station'); self.showAddForm(); self.backupAGCONum = selectedData.part_number_agco; self.updateSelect2PartNumber(); self.isEdit = true; self.lubform[1]['isValid'] = true; self.machineform[1]['isValid'] = true; if (self.isMaqunia) { jQuery('#description').val(selectedData.item); jQuery('#itemList').val(selectedData.part_number_agco).trigger('change'); jQuery('#partNumberStationNew').val(selectedData.part_number_service_station); } else { jQuery('#description').val(selectedData.item); jQuery('#itemList').val(selectedData.part_number_agco).trigger('change'); jQuery('#partNumberStationNew').val(selectedData.part_number_service_station); selectedData.part_number_type = jQuery(this).data('part_number_type'); if (selectedData.part_number_type == "LUBRIFICANTES") { jQuery('#partNumberTypeNew').val("2"); } else if (selectedData.part_number_type == "PEÇAS") { jQuery('#partNumberTypeNew').val("1"); } } }, updateSelect2PartNumber: function () { var data = new FormData; data.append('search_string', self.backupAGCONum); data.append('page', 1); data.append('post_per_page', 1); var endpoint = self.endpoints.productListForAddNew; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', data, true, self.updateSelect2PartNumberSuccess, self.updateSelect2PartNumberError); }, updateSelect2PartNumberSuccess: function (success) { agco.helper.loader('hide'); if (!success || success.code != 'get_agco_list_by_agco_success') { jQuery('.select2-selection__placeholder').html('PART NUMBER AGCO'); return false; } if (!success.data) { jQuery('.select2-selection__placeholder').html('PART NUMBER AGCO'); } else { var selected = success.data[0]; jQuery('.select2-selection__placeholder').html(selected.description); } }, updateSelect2PartNumberError: function (error) { agco.helper.loader('hide'); jQuery('.select2-selection__placeholder').html('PART NUMBER AGCO'); }, deleteParts: function () { jQuery("#deletePopup").modal('hide'); var data = { 'part_number_agco': self.selectedData.part_number_agco, 'part_number_type': self.selectedData.part_number_type } if (self.isMaqunia) { data.part_number_type = ""; data.product_type = "machines"; } var endpoint = self.endpoints.delete; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'DELETE', data, true, self.deletePartsSuccess, self.deletePartsError); }, deletePartsSuccess: function (success) { agco.helper.loader('hide'); self.selectedData = {}; jQuery('.page-dePara-detail table').DataTable().ajax.reload(); }, deletePartsError: function (error) { agco.helper.loader('hide'); }, } return self; }(); jQuery(document).ready(function () { agco.dePara.ready(); }); agco.NF = function () { var self = { fileFlag: false, isMaqunia: false, post: '', endpoints: { 'getList': "adm/report/nfe-pendentes-vincular/", }, columns: [ { "data": "data", "title": "ITEM" }, { "data": "tipo", "title": "PART NUMBER AGCO" }, { "data": "description", "title": "PART NUMBER CONCESSIONÁRIA" }, { "data": "expiracao", "title": "", render: function (data, type, rowObject, metat) { return " "; } }, ], lubform: [ { id: 'description', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'itemList', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'partNumberStationNew', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'partNumberTypeNew', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, } ], machineform: [ { id: 'description', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'itemList', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, }, { id: 'partNumberStationNew', errorMessage: 'Campo obrigatório.', isValid: false, mandatory: true, } ], ready: function () { if (jQuery('.page-template-page-vinculacao-de-produtos').length) { self.eventHandlers(); self.getList(); agco.envioNF.applyMechanicSelect2(); } }, eventHandlers: function () { }, getList: function () { if (jQuery().dataTable()) { jQuery('.vincula-page-period-detail table').dataTable(); } else { setTimeout(() => { self.getList(); }, 300); } } } return self; }(); jQuery(document).ready(function () { agco.NF.ready(); }); agco.cadastro = function () { var self = { endpoints: { 'getVendedorList': "v1/adm/employee/ranking", 'getClienteList': "adm/getEmployeeRanking", }, vendedorColumns: [ { "data": "nome_completo", "title": "Nombre del vendedor" }, { "data": "user_login", "title": "DNI" }, { "data": "cnpj", "title": "RUT/RUC" }, { "data": "", "title": "e-mail", render: function (data, type, rowObject, metat) { var email = ''; if (rowObject.email) { email = rowObject.email; } return email; } }, { "data": "celular", "title": "celular" }, { "data": "qtd", "title": "cuantos registrados activos", }, ], ClienteColumns: [ { "data": "nome", "title": "NOMBRE CLIENTE" }, { "data": "user_login", "title": "DNI/RUT/CI" }, { "data": "email", "title": "E-MAIL" }, { "data": "celular", "title": "TELEFONO" }, { "data": "faixa", "title": "PUNTOS" }, { "data": "perfil", "title": "ORIGEN" }, { "data": "user_registered", "title": "FECHA DE REGISTRO" }, { "data": "ativo", "title": "CADASTRO ACTIVO", }, ], ready: function () { if (jQuery('.page-template-page-admin').length) { self.eventHandlers(); self.getVendedorList(); } }, eventHandlers: function () { jQuery(document).on('click', '#customer-tab', self.getVendedorList); jQuery(document).on('click', '#salesperson-tab', self.getClienteList); }, getVendedorList: function () { var endpoint = self.endpoints.getVendedorList; agco.helper.loader('show'); jQuery('.admin-page-customer-detail table').html(''); agco.helper.appApiRequest(endpoint, 'GET', {}, true, self.getVendedorListSuccess, self.getVendedorListError); }, getVendedorListSuccess: function (success) { agco.helper.loader('hide'); // if (!success || success.code != "get_employee_ranking_success") { // return false; // } var list = success.data.employee ? success.data.employee : []; agco.helper.loadDataTableWithdata(list, self.vendedorColumns, '.admin-page-customer-detail table'); }, getVendedorListError: function (error) { agco.helper.loader('hide'); agco.helper.loadDataTableWithdata([], self.vendedorColumns, '.admin-page-customer-detail table'); }, getClienteList: function () { var endpoint = self.endpoints.getVendedorList; agco.helper.loader('show'); jQuery('.admin-page-salesperson-detail table').html(''); agco.helper.appApiRequest(endpoint, 'GET', {}, true, self.getClienteListSuccess, self.getClienteListError); }, getClienteListSuccess: function (success) { agco.helper.loader('hide'); // if (!success || success.code != "get_employee_ranking_success") { // return false; // } var list = success.data.customer ? success.data.customer : []; agco.helper.loadDataTableWithdata(list, self.ClienteColumns, '.admin-page-salesperson-detail table'); }, getClienteListError: function (error) { agco.helper.loader('hide'); agco.helper.loadDataTableWithdata([], self.ClienteColumns, '.admin-page-salesperson-detail table'); }, } return self; }(); jQuery(document).ready(function () { agco.cadastro.ready(); }); agco.adminNF = function () { var self = { endpoints: { 'getInvoiceList': "v1/adm/get/invoices/", }, ClienteColumns: [ { "data": "invoice_id", "title": "Número de la factura" }, { "data": "valor", "title": "VALOR" }, { "data": "emit_CNPJ", "title": "RUT/RUC/DNI/CI DESTINATARIO​N. FACTURA" }, { "data": "cpf", "title": "RUT/DNI/CI CLIENTE" }, { "data": "emissor", "title": "RUT/RUC" }, { "data": "created_date", "title": "fecha", }, ], ready: function () { if (jQuery('.page-template-page-nfs-registradas').length) { self.eventHandlers(); var data = { 'start_date': '', 'end_date': '' }; self.getInvoiceList(data); } }, eventHandlers: function () { // jQuery(document).on('click', '#salesperson-tab', self.getVendedorList); jQuery(document).on('click', '.filter-by-date', self.searchByDate); }, searchByDate: function () { var start = jQuery('#start-date').val(); var end = jQuery('#ending-date').val(); if ((start != end) && (!moment(end).isAfter(moment(start)))) { agco.helper.popUp('Error', 'A data de início deve ser menor ou igual a data final.'); return false; } var data = { 'start_date': start, 'end_date': end }; self.getInvoiceList(data); }, getInvoiceList: function (filter) { var endpoint = self.endpoints.getInvoiceList; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', filter, true, self.getVendedorListSuccess, self.getVendedorListError); return false; var endPoint = self.endpoints.getVendedorList; var url = agco.helper.baseUrl + endPoint; var customColumn = self.vendedorColumns; agco.helper.loadDataTable('page-salesperson-detail', url, '.admin-page-salesperson-detail', customColumn, {}); }, getVendedorListSuccess: function (success) { agco.helper.loader('hide'); var list = success.data ? success.data : []; agco.helper.loadDataTableWithdata(list, self.ClienteColumns, '.admin-page-registered-nf-detail table'); }, getVendedorListError: function (error) { agco.helper.loader('hide'); agco.helper.loadDataTableWithdata([], self.ClienteColumns, '.admin-page-registered-nf-detail table'); }, } return self; }(); jQuery(document).ready(function () { agco.adminNF.ready(); }); agco.CnpjCpf = function () { var self = { endpoints: { 'getCnpjCpf': 'v1/adm/list-cnpj-cpf/', 'editCnpjCpf': 'v1/adm/update-cnpj-cpf/', 'removeCnpjCpf': 'v1/adm/cnpj-cpf-delete/' }, ClienteColumns: [ { "data": "cnpj", "title": "CNPJ/CPF Associado" }, { "data": "cpf", "title": "CPF" }, { "data": 'country', "title": 'PAÍS' }, { "data": "", "title": "", render: function (data, type, rowObject, metat) { return ""; } }, { "data": "", "title": "", render: function (data, type, rowObject, metat) { return ""; } }, ], ready: function () { if (jQuery('.page-template-page-cnpj-cpf').length) { self.eventHandlers(); var data = { 'start_date': '', 'end_date': '' }; self.getCnpjCpf(data); } }, eventHandlers: function () { // jQuery(document).on('click', '#salesperson-tab', self.getVendedorList); jQuery(document).on('click', '.filter-by-date', self.searchByDate); jQuery(document).on('click', '.editAction', self.filterUser); jQuery(document).on('click', '.createNew', self.showCreateVinc); jQuery(document).on('click', '.removeVinc', self.removeVinculo); jQuery(document).on('click', '#addNewPart', self.submitNewUser); jQuery(document).on('click', '#addNewVinc', self.createNewVinc); jQuery(document).on('click', '#close', self.hideAddForm); }, searchByDate: function () { var start = jQuery('#start-date').val(); var end = jQuery('#ending-date').val(); if ((start != end) && (!moment(end).isAfter(moment(start)))) { agco.helper.popUp('Error', 'A data de início deve ser menor ou igual a data final.'); return false; } var data = { 'start_date': start, 'end_date': end }; self.getCnpjCpf(data); }, //Chama formulario para editar showAddForm: function () { jQuery('.addNewForm').attr('hidden', false); }, //close form hideAddForm: function () { self.isEdit = false; jQuery('.addNewForm').attr('hidden', true); jQuery('.createNewForm').attr('hidden', true); }, showCreateVinc: function () { jQuery('.createNewForm').attr('hidden', false); }, createNewVinc: function () { var sky_id = jQuery(this).data('sky_user_id'); var method = 'POST'; var endpoint = self.endpoints.editCnpjCpf; var data = new FormData; data.append('cpf', jQuery('#new_cpf').val()); data.append('cnpj', jQuery('#new_cnpj').val()); data.append('country', jQuery('#new_pais').val()); // console.log(data, endpoint); // console.log(data); agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, method, data, true, self.successSubmitForm, self.errorCallBackSubmitForm); }, //Dados nos campos filterUser: function () { self.showAddForm(); var selectedData = {}; selectedData.cpf = jQuery(this).data('cpf'); selectedData.cnpj = jQuery(this).data('cnpj'); selectedData.country = jQuery(this).data('country'); selectedData.id = jQuery(this).data('id'); jQuery('#cpf').val(selectedData.cpf); jQuery('#cnpj').val(selectedData.cnpj); jQuery('#pais').val(selectedData.country); jQuery('#id').val(selectedData.id); }, //Trazendo dados do banco getCnpjCpf: function (filter) { var endpoint = self.endpoints.getCnpjCpf; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', filter, true, self.getVendedorListSuccess, self.getVendedorListError); return false; var endPoint = self.endpoints.getCnpjCpf; var url = agco.helper.baseUrl + endPoint; var customColumn = self.vendedorColumns; agco.helper.loader('show'); agco.helper.loadDataTable('page-salesperson-detail', url, '.admin-page-salesperson-detail', customColumn, {}); }, getVendedorListSuccess: function (success) { agco.helper.loader('hide'); var list = success.data ? success.data : []; // console.log(success.data); agco.helper.loadDataTableWithdata(list, self.ClienteColumns, '.admin-page-registered-nf-detail table'); }, getVendedorListError: function (error) { agco.helper.loader('hide'); agco.helper.loadDataTableWithdata([], self.ClienteColumns, '.admin-page-registered-nf-detail table'); }, //Atualizando submitNewUser: function () { var sky_id = jQuery(this).data('sky_user_id'); var method = 'POST'; var endpoint = self.endpoints.editCnpjCpf; var data = new FormData; data.append('cpf', jQuery('#cpf').val()); data.append('cnpj', jQuery('#cnpj').val()); data.append('country', jQuery('#edit_pais').val()); data.append('id', jQuery('#id').val()); // console.log(data, endpoint); // console.log(data); agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, method, data, true, self.successSubmitForm, self.errorCallBackSubmitForm); }, successSubmitForm: function (success) { // console.log('success SubmitForm', success); agco.helper.loader('hide'); if (location.href.indexOf('/vincular-cnpj-cpf/') > 0) { if (success && success.code === 'insertCnpjCpf_success') { agco.helper.popUp('Éxito', success.message); agco.helper.popUp('Éxito', success.message, agco.Register.reloadPage); } if (success && success.code !== 'insertCnpjCpf_success') { agco.helper.popUp('Error', success.message); //agco.helper.popUp('Éxito', success.message, agco.Register.reloadPage); return false; } } }, errorCallBackSubmitForm: function (error) { self.accessPageData = ''; // console.log('error SubmitForm', error); if (location.href.indexOf('primeiro-acesso/') > 0) { jQuery('#stepform').steps("previous"); jQuery('#reg_email').prop('disabled', true); jQuery('#telefone').prop('disabled', true); jQuery('#nomecompleto').prop('disabled', true); } agco.helper.loader('hide'); agco.helper.popUp('Error', error.message); }, //remove vinc removeVinculo: function () { var endpoint = self.endpoints.removeCnpjCpf; var data = new FormData; data.append('id', jQuery(this).data('id')); // console.log(data) agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', data, true, self.successDelete, self.errorDelete); }, successDelete: function (success) { // console.log('success SubmitForm', success); agco.helper.loader('hide'); if (location.href.indexOf('/vincular-cnpj-cpf/') > 0) { if (success && success.code === 'deleteCnpjCpf_success') { agco.helper.popUp('Éxito', success.message); agco.helper.popUp('Éxito', success.message, agco.Register.reloadPage); } if (success && success.code !== 'insertCnpjCpf_success') { agco.helper.popUp('Error', success.message); //agco.helper.popUp('Éxito', success.message, agco.Register.reloadPage); return false; } } }, errorDelete: function (error) { agco.helper.loader('hide'); agco.helper.popUp('Error', error.message); }, } return self; }(); jQuery(document).ready(function () { agco.CnpjCpf.ready(); }); agco.EditUserBO = function () { var self = { endpoints: { 'getUserList': 'v1/admin/enrolled/users/list/', 'updateUser': 'v1/user/bo/update', 'validateCell': 'v1/validate/cell' }, currentBarCodeMask: '', ClienteColumns: [ { "data": "Nome", "title": "Nome" }, { "data": "CPF", "title": "CPF" }, { "data": "Perfil", "title": "Perfil" }, { "data": "email", "title": "E-mail" }, { "data": "celular", "title": "Telefone" }, /*{ "data":"Tipo_Credenciado", "title":"Tipo Credenciado" },*/ { "data": "", "title": "", render: function (data, type, rowObject, metat) { return ""; } }, ], ready: function () { if (jQuery('.page-template-page-edit-user-bo').length) { self.eventHandlers(); var data = { 'start_date': '', 'end_date': '' }; self.getUserList(data); self.applyMask(); } }, load: function () { // self.eventHandler(); self.getUserList(); self.applyMask(); }, applyMask: function () { if (jQuery() && jQuery().mask()) { jQuery('#cep').mask('0000000000000000000000000'); jQuery('#telefone').mask('00000000000000000000000'); } else { setTimeout(function () { self.applyMask(); }, 300); } }, applySelectPagenation: function () { if (jQuery() && jQuery().select2) { jQuery("#itemList").select2({ minimumInputLength: 0, language: "pt-BR", ajax: { url: agco.helper.baseUrl + 'v1/admin/enrolled/users/list/', dataType: 'json', type: 'POST', headers: {'x-auth-sb': globalJsData.token}, delay: 250, data: function (params) { var dataObject = { search_string: params.term ? params.term : '', // search term page: params.page || 1, post_per_page: 100, }; if (self.isMaqunia) { dataObject['product_type'] = 'machines'; } return dataObject; }, processResults: function (data, params) { params.page = params.page || 1; var arr = [] if (data.data) { jQuery.each(data.data, function (index, value) { if (value.code) { arr.push({ id: value.code, text: value.description + ' - ' + value.code }); } }); } return { results: arr, }; }, }, placeholder: 'Users', }); } else { setTimeout(self.applySelectPagenation, 300); } }, eventHandlers: function () { // jQuery(document).on('click', '#salesperson-tab', self.getVendedorList); //jQuery(document).on('click', '.filter-by-date', self.searchByDate); jQuery(document).on('click', '.editAction', self.filterUser); jQuery(document).on('click', '#close', self.hideAddForm); jQuery(document).on('click', '#addNewPart', self.submitNewUser); jQuery(document).on('change', '#reg_email', self.emailValidation); jQuery(document).on('change', '#search_perfil', self.listUsersPerfil); jQuery(document).on('change', '#reg_email', self.emailValidation); jQuery(document).on('change', '#perfil', self.showCnpjConcessionaria); jQuery(document).on('change', '#cpf', self.cpfValidation); }, reloadPage: function () { location.reload() }, redirectPage: function () { window.location.href = location.host + "/edit-user-bo/"; }, /*updateValidatedStatus: function (elementID, status) { var currentTab = jQuery('.body.current').attr('id'); var selectedForm; self[selectedForm].forEach(function (element) { // console.log(element); if (element.id === elementID) { if (!jQuery('#' + elementID).val() && !element.mandatory) { element.isValid = true; agco.helper.formValidationLabelRemove(element.id); return false; } element.isValid = status; if (!status) { // agco.helper.popUp('Error', element.errorMessage); agco.helper.formValidationLabelCreate(element.id, element.errorMessage); } else { agco.helper.formValidationLabelRemove(element.id); } } }); // console.log(self[selectedForm]); },*/ cpfValidation: function () { try { if (jQuery('#cpf').val() || (globalJsData && globalJsData.user.data.user_login == "teamsb")) { self.updateValidatedStatus('cpf', true); } else { self.updateValidatedStatus('cpf', false); } } catch (error) { console.warn(error); self.updateValidatedStatus('cpf', false); } }, emailValidation: function () { var email = jQuery(this).val(); if (email && agco.helper.emailRegex.test(email)) { self.updateValidatedStatus('reg_email', true); } else { self.updateValidatedStatus('reg_email', false); } }, showCnpjConcessionaria: function () { var perfil = jQuery(this).val(); //console.log(perfil); if (perfil === 'Atendente' || perfil === 'Atendente Produto' || perfil === 'Cliente' || perfil === 'Mecânico' || perfil === 'Gerente de Peças' || perfil === 'Gerente Produto') { jQuery('.vinc_cnpj_vendedor').css('display', 'block'); } else { jQuery('.vinc_cnpj_vendedor').css('display', 'none'); } if (perfil === 'Cliente') { jQuery('.vinc_client').css('display', 'block'); } else { jQuery('.vinc_client').css('display', 'none'); } }, preventClick: function (e) { e.preventDefault(); }, showAddForm: function () { jQuery('.addNewForm').attr('hidden', false); }, hideAddForm: function () { self.isEdit = false; jQuery('.addNewForm').attr('hidden', true); }, filterUser: function () { self.showAddForm(); var selectedData = {}; selectedData.cpf = jQuery(this).data('cpf'); selectedData.sky_id = jQuery(this).data('sky_user_id'); selectedData.nome = jQuery(this).data('nome'); selectedData.perfil = jQuery(this).data('perfil'); selectedData.email = jQuery(this).data('email'); selectedData.telephone = jQuery(this).data('telephone'); selectedData.Tipo_credenciad = jQuery(this).data('Tipo_credenciad'); selectedData.sobrenome = jQuery(this).data('sobrenome'); selectedData.nascimento = jQuery(this).data('nascimento'); selectedData.celular = jQuery(this).data('celular'); selectedData.genero = jQuery(this).data('genero'); selectedData.cep = jQuery(this).data('cep'); selectedData.rua = jQuery(this).data('rua'); selectedData.numero = jQuery(this).data('numero'); selectedData.complemento = jQuery(this).data('complemento'); selectedData.bairro = jQuery(this).data('bairro'); selectedData.cidade = jQuery(this).data('cidade'); selectedData.estado = jQuery(this).data('estado'); selectedData.referencia = jQuery(this).data('ponto_referencia'); selectedData.accept_regulation = jQuery(this).data('accept_regulation'); selectedData.accept_email = jQuery(this).data('accept_email'); selectedData.accept_sms = jQuery(this).data('accept_sms'); selectedData.status = jQuery(this).data('status'); selectedData.service_station_id = jQuery(this).data('service_station_id'); // selectedData.user_type = jQuery(this).data('user_type'); selectedData.vinc_cnpj_one = jQuery(this).data('vinc_cnpj_one'); selectedData.vinc_cnpj_two = jQuery(this).data('vinc_cnpj_two'); selectedData.vinc_cnpj_three = jQuery(this).data('vinc_cnpj_three'); // jQuery('#cpf').val(selectedData.cpf); jQuery('#nome').val(selectedData.nome); jQuery('#perfil').val(selectedData.perfil); jQuery('#perfil').trigger('change'); jQuery('#email').val(selectedData.email); jQuery('#telefone').val(selectedData.telephone); jQuery('#Tipo_credenciad').val(selectedData.Tipo_credenciad); jQuery('#sobrenome').val(selectedData.sobrenome); jQuery('#nascimento').val(selectedData.nascimento); jQuery('#celular').val(selectedData.celular ? selectedData.celular : selectedData.telephone); jQuery('#genero').val(selectedData.genero); jQuery('#cep').val(selectedData.cep); jQuery('#rua').val(selectedData.rua); jQuery('#numero').val(selectedData.numero); jQuery('#complemento').val(selectedData.complemento); jQuery('#bairro').val(selectedData.bairro); jQuery('#cidade').val(selectedData.cidade); jQuery('#estado').val(selectedData.estado === null || selectedData.estado === undefined ? '' : selectedData.estado); /*jQuery('#vinc_cnpj_one').val(selectedData.vinc_cnpj_one); jQuery('#vinc_cnpj_two').val(selectedData.vinc_cnpj_two); jQuery('#vinc_cnpj_three').val(selectedData.vinc_cnpj_three);**/ //jQuery('#referencia').val(selectedData.referencia ); //jQuery('#accept_regulation').val(selectedData.accept_regulation); //jQuery('#accept_email').val(selectedData.accept_email); //jQuery('#accept_sms').val(selectedData.accept_sms); jQuery('#status').val(selectedData.status); jQuery('#accept_regulation').prop('checked', selectedData.accept_regulation); jQuery('#accept_email').prop('checked', selectedData.accept_email); jQuery('#accept_sms').prop('checked', selectedData.accept_sms); jQuery('#cnpj_vendedor').val(selectedData.service_station_id); jQuery('#vinc_cnpj_one').val(selectedData.vinc_cnpj_one); jQuery('#vinc_cnpj_two').val(selectedData.vinc_cnpj_two); jQuery('#vinc_cnpj_three').val(selectedData.vinc_cnpj_three); jQuery('#pass').val(''); }, submitNewUser: function () { var sky_id = jQuery(this).data('sky_user_id'); var method = 'POST'; var endpoint = self.endpoints.updateUser; var data = new FormData; data.append('cpf', jQuery('#cpf').val()); data.append('sky_user_id', sky_id); data.append('nome_completo', jQuery('#nome').val()); data.append('username', jQuery('#nome').val()); data.append('sobrenome', jQuery('#sobrenome').val()); data.append('data_nascimento', jQuery('#nascimento').val()); data.append('telefone', jQuery('#telefone').val()); data.append('celular', jQuery('#celular').val()); data.append('genero', jQuery('#genero').val()); data.append('cep', jQuery('#cep').val()); data.append('rua', jQuery('#rua').val()); data.append('numero', jQuery('#numero').val()); data.append('email', jQuery('#email').val()); data.append('complemento', jQuery('#complemento').val()); data.append('bairro', jQuery('#bairro').val()); data.append('cidade', jQuery('#cidade').val()); data.append('estado', jQuery('#estado').val()); data.append('vinc_cnpj_one', jQuery('#vinc_cnpj_one').val()); data.append('vinc_cnpj_two', jQuery('#vinc_cnpj_two').val()); data.append('vinc_cnpj_three', jQuery('#vinc_cnpj_three').val()); //data.append('ponto_de_referencia', jQuery('#referencia').val()); data.append('accept_regulation', jQuery('#accept_regulation').prop('checked') == true ? 'on' : false); data.append('accept_email', jQuery('#accept_email').prop('checked') == true ? 'on' : false); data.append('accept_sms', jQuery('#accept_sms').prop('checked') == true ? 'on' : false); data.append('status', jQuery('#status').val()); data.append('perfil', jQuery('#perfil').val()); data.append('service_station_id', jQuery('#cnpj_vendedor').val() ? jQuery('#cnpj_vendedor').val() : ''); data.append('password', jQuery('#pass').val() ? jQuery('#pass').val() : ''); // console.log(data, endpoint); // console.log(data); agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', data, true, self.successSubmitForm, self.errorCallBackSubmitForm); //agco.helper.appApiRequest(endpoint, 'POST', filter, true, self.getVendedorListSuccess, self.getVendedorListError); //agco.helper.appApiRequest(endpoint, method, data, true, self.getProductListForAddNewSuccess, self.getProductListForAddNewError); }, successSubmitForm: function (success) { // console.log('success SubmitForm', success); agco.helper.loader('hide'); if (location.href.indexOf('/edit-user-bo/') > 0) { if (success && success.code === 'profile_update_bo_success') { agco.helper.popUp('Éxito', success.message); agco.helper.popUp('Éxito', success.message, agco.Register.reloadPage); return false } if (success && success.code !== 'profile_update_success') { agco.helper.popUp('Error', success.message); //agco.helper.popUp('Éxito', success.message, agco.Register.reloadPage); return false; } else { if (success && success.code !== 'register_client_user_success') { agco.helper.popUp('Error', success.message); return false; } agco.helper.popUp('Éxito', success.message, agco.Register.submitSuccessregister); } } }, errorCallBackSubmitForm: function (error) { self.accessPageData = ''; // console.log('error SubmitForm', error); if (location.href.indexOf('primeiro-acesso/') > 0) { jQuery('#stepform').steps("previous"); jQuery('#reg_email').prop('disabled', true); jQuery('#telefone').prop('disabled', true); jQuery('#nomecompleto').prop('disabled', true); } agco.helper.loader('hide'); agco.helper.popUp('Error', error.message); }, listUsersPerfil: function () { var perfil = jQuery(this).val(); var filter = {}; filter.filterUsers = perfil; self.getUserList(filter); }, getUserList: function (filter) { agco.helper.loader('show'); var endPoint = self.endpoints.getUserList; var url = agco.helper.baseUrl + endPoint; var customColumn = self.ClienteColumns; agco.helper.loadDataTable('admin-page-table-with-search', url, '.admin-page-registered-nf-detail', customColumn, filter, '', ''); jQuery('[name="admin-page-table_length"]').hide(); agco.helper.loader('hide'); }, /*loadDataTable: function (data) { var endPoint = self.endpoint.extrato; var url = agco.helper.baseUrl + endPoint; agco.helper.loadDataTable('extrato-page-table', url, '.extrato-page-period-detail', self.columns, data); jQuery('[name="extrato-page-table_length"]').hide(); extrato-page-table-with-search },*/ getVendedorListSuccess: function (success) { var list = success.data ? success.data : []; // console.log(success.data); agco.helper.loadDataTableWithdata(list, self.ClienteColumns, '.admin-page-registered-nf-detail table'); agco.helper.loader('hide'); }, getVendedorListError: function (error) { agco.helper.loader('hide'); agco.helper.loadDataTableWithdata([], self.ClienteColumns, '.admin-page-registered-nf-detail table'); }, } return self; }(); jQuery(document).ready(function () { agco.EditUserBO.ready(); }); agco.notasSemPontuar = function () { var self = { endpoints: { 'getPontuarList': "v1/adm/report/nopoints/invoice/", 'partNumber': 'v1/adm/report/nopoints/partnumbers', 'preCadastro': 'v1/adm/report/preregister/pre_cadastro' }, pontuarColumns: [ { "data": "cnf", "title": "factura" }, { "data": "dhemi", "title": "fecha" }, { "data": "Producto", "title": "producto" }, { "data": "Nota", "title": "observación" }, { "data": "cpf", "title": "RUT/DNI/CI CLIENTE" }, { "data": "nome", "title": "nombre cliente", }, { "data": "emit_CNPJ", "title": "RUT/RUC", }, ], noPointsColumn: [ { "data": "CodigoPn", "title": "CÓDIGO" }, { "data": "ProdutoPn", "title": "producto", }, { "data": "NotaPn", "title": "observación", }, ], preCadastroColumn: [ { "data": "user_login", "title": "CPF" }, { "data": "nome", "title": "NOME", }, { "data": "user_email", "title": "E-MAIL", }, { "data": "service_station", "title": "CNPJ", }, ], ready: function () { if (jQuery('.admin-page-link').length) { jQuery(document).on('click', '.excel-download-action', self.downloadExcel); } if (jQuery('.page-template-page-notas-sem-pontuar').length) { self.eventHandlers(); self.getPontuarList(); } else if (jQuery('.page-template-page-part-numbers-sem-pontuar').length) { self.getPartNumbersList(); } else if (jQuery('.page-template-page-pre-cadastro').length) { self.getPreCadastroList(); } else { } }, eventHandlers: function () { // jQuery(document).on('click', '#salesperson-tab', self.getVendedorList); }, downloadExcel: function (e) { e.preventDefault(); jQuery('.buttons-excel').click(); }, getPreCadastroList: function () { var endpoint = self.endpoints.preCadastro; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', {}, true, self.getPreCadastroListSuccess, self.getPreCadastroListError); }, getPreCadastroListSuccess: function (success) { agco.helper.loader('hide'); var list = []; if (!success || success.code != "empty_error") { } else { list = success.data ? success.data : []; } agco.helper.loadDataTableWithdata(list, self.pontuarColumns, '.admin-page-pre-registration-customer-detail table'); }, getPreCadastroListError: function (error) { agco.helper.loader('hide'); agco.helper.loadDataTableWithdata([], self.pontuarColumns, '.admin-page-pre-registration-customer-detail table'); }, getPartNumbersList: function () { var endpoint = self.endpoints.partNumber; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'GET', {}, true, self.getPartNumbersListSuccess, self.getPartNumbersListError); return false; var endPoint = self.endpoints.getInvoiceList; var url = agco.helper.baseUrl + endPoint; var customColumn = self.ClienteColumns; agco.helper.loadDataTable('page-registered-detail', url, '.admin-page-registered-nf-detail', customColumn, {}); }, getPartNumbersListSuccess: function (success) { agco.helper.loader('hide'); var list = []; if (!success || success.code != "report_no_points_pn_success") { } else { list = success.data ? success.data : []; } agco.helper.loadDataTableWithdata(list, self.noPointsColumn, '.admin-page-part-number-sem-pontuar-detail table'); }, getPartNumbersListError: function (error) { agco.helper.loader('hide'); agco.helper.loadDataTableWithdata([], self.noPointsColumn, '.admin-page-part-number-sem-pontuar-detail table'); }, getPontuarList: function () { var endpoint = self.endpoints.getPontuarList; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'GET', {}, true, self.getPontuarListSuccess, self.getPontuarListError); }, getPontuarListSuccess: function (success) { agco.helper.loader('hide'); var list = []; if (!success || success.code != "report_no_points_pn_success") { } else { list = success.data ? success.data : []; } agco.helper.loadDataTableWithdata(list, self.pontuarColumns, '.admin-page-notes-sem-pontuar-detail table'); }, getPontuarListError: function (error) { agco.helper.loader('hide'); agco.helper.loadDataTableWithdata([], self.pontuarColumns, '.admin-page-notes-sem-pontuar-detail table'); }, } return self; }(); jQuery(document).ready(function () { agco.notasSemPontuar.ready(); }); agco.areaDoVendedor = function () { var self = { fileFlag: false, post: '', isEditView: false, userList: {}, endpoints: { 'vendedorGetList': 'v1/adm/user/list', }, userProfileKeymap: { 'ATENDENTE': 'employee', 'GERENTE DE PEÇAS': 'manager', 'MECÂNICO': 'mecanico', 'ATENDENTE PRODUTO': 'employee_produto', 'GERENTE DE PRODUTO': 'manager_produto', }, ready: function () { if (jQuery('.page-template-page-adm-area-do-vendedor').length) { self.eventHandlers(); self.checkIfListView(); } }, eventHandlers: function () { jQuery(document).on('click', '.userListPicker', self.userListPicker); jQuery(document).on('click', '.edit-form', self.findSelectedUser); jQuery(document).on('keyup', '.search-field', self.getVendedorList); }, checkIfListView: function () { var pageURLParam = new URLSearchParams(window.location.search); if (pageURLParam.has('listDo')) { self.isEditView = true; self.openPopup(); self.getVendedorList(); } else { } }, userListPicker: function () { jQuery('.userListPicker').removeClass('active'); jQuery(this).addClass('active'); }, findSelectedUser: function () { var selectedID = jQuery('.vendedor-user-list .active').attr('id'); var selecteduser = self.userList[selectedID]; jQuery('#nomecompleto').val(selecteduser.Nome); jQuery('#nomesobrenome').val(selecteduser.sobrenome); jQuery('#cpf').val(selecteduser.CPF); jQuery('#dob').val(selecteduser.data_nascimento); jQuery('#reg_email').val(selecteduser.email); jQuery('#genero').val(selecteduser.genero); jQuery('#telefone').val(selecteduser.celular); jQuery('#cep').val(selecteduser.cep); jQuery('#rua').val(selecteduser.rua); jQuery('#numero').val(selecteduser.numero); jQuery('#complemento').val(selecteduser.complemento); jQuery('#bairro').val(selecteduser.bairro); jQuery('#cidade').val(selecteduser.cidade); jQuery('#estado').val(selecteduser.estado); jQuery('#referencia').val(selecteduser.ponto_referencia); var mappedRole = self.userProfileKeymap[selecteduser.Perfil.toUpperCase()]; jQuery('#perfil').val(mappedRole ? mappedRole : ''); jQuery('#perfil').trigger('change'); if (selecteduser.prod_manager) { jQuery('#managers-list').val(selecteduser.prod_manager); jQuery('#managers-list').trigger('change'); } if (selecteduser.cnpj_vendedor) { jQuery('#cnpj_vendedor').val(selecteduser.cnpj_vendedor); } jQuery('#customControlValidation1').prop('checked', selecteduser.accept_regulation); jQuery('#customControlValidation2').prop('checked', selecteduser.accept_email); jQuery('#customControlValidation3').prop('checked', selecteduser.accept_telephone); jQuery('#customControlValidation4').prop('checked', selecteduser.accept_sms); jQuery('#customControlValidation5').prop('checked', selecteduser.accept_postal_service); jQuery('.area-do-vendedor-popup').attr('hidden', true); agco.Register.makeFieldsDisabledVendedor(); agco.Register.preLoadAdjustProfile(); }, openPopup: function () { jQuery('.area-do-vendedor-popup').attr('hidden', false); }, getVendedorList: function () { var endpoint = self.endpoints.vendedorGetList; var data = {}; var searchText = jQuery('.search-field').val(); if (!searchText) { } else if (searchText.length < 3) { return false; } else { } data = { "search_string": searchText }; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', data, true, self.getVendedorListSuccess, self.getVendedorListError); }, getVendedorListSuccess: function (success) { agco.helper.loader('hide'); jQuery('.vendedor-user-list').html(''); if (!success.data) { return false; } //retirando concessionaria da lista //removing dealership from the list function notConcessionaria(obj) { return obj.Perfil != 'Concessionaria'; } var list = success.data; var filtered = list.filter(notConcessionaria); list = filtered; list.forEach(function (element) { self.userList[element.CPF] = element; var lastname = element.sobrenome; if (!element.sobrenome || element.sobrenome == null) { lastname = ''; } jQuery('
  • ', { id: element.CPF, class: "userListPicker", html: '' }).appendTo('.vendedor-user-list'); jQuery('
    ', { html: element.Nome + ' ' + lastname }).appendTo('#' + element.CPF); jQuery('
    ', { html: 'Perfil: ' + element.Perfil }).appendTo('#' + element.CPF); }); }, getVendedorListError: function (error) { agco.helper.loader('hide'); }, } return self; }(); jQuery(document).ready(function () { agco.areaDoVendedor.ready(); }); agco.vincularDeNotas = function () { var self = { endpoints: { 'getList': 'v1/adm/report/nfe-pendentes-vincular', 'productList': 'v1/adm/product/list/', 'getCustomer': 'v1/adm/get/getCustomersList', 'enviarNfs': 'v1/adm/venda/registernota/', 'checkInvoice': 'v1/adm/venda/vincular-notas', 'updateLink': 'v1/adm/invoice/link', 'xmlInvoiceUpload': 'v1/adm/register/invoice' }, allCodeIdPairs: {}, productList: [], vendedorColumn: [ { "data": "", "title": "", render: function (data, type, rowObject, metat) { return ""; } }, { "data": "invoice_id", "title": "Número de la factura" }, { "data": "", "title": "Cod Máquina", render: function (data, type, rowObject, metat) { var selectOption = ''; var option = ''; option += ''; self.productList.forEach(element => { option += ''; }); setTimeout(function () { var el = jQuery('#mq' + rowObject.id); if (el.data('select2')) { el.select2('destroy'); } el.select2(); }, 1500); return selectOption + option + endOfSelectOption; } }, { "data": "xProd", "title": "Producto" }, { "data": "cProd", "title": "Cod Producto" }, { "data": "vProd", "title": "Valor" }, { "data": "emit_CNPJ", "title": "Cuit de la concesionaria" }, ], nonVendedorColumn: [ { "data": "", "title": "", render: function (data, type, rowObject, metat) { return ""; } }, { "data": "invoice_id_no_vinc", "title": "Número de la factura" }, { "data": "destinatario", "title": "Cuit de la concesionaria" }, { "data": "nome", "title": "Razón Social" }, { "data": "dhemi", "title": "Fecha de emisión" }, ], tableSelector: '', updatedProductListMap: {}, columnsSelected: {}, ready: function () { if (jQuery('.page-template-page-vinculacao-de-produtos').length) { self.tableSelector = '.vincula-page-period-detail table'; self.eventHandlers(); self.getProductlist(); self.applyMask(); self.columnsSelected = self.nonVendedorColumn; } else if (jQuery('.page-template-page-envio-de-produtos-registro-de-nfs').length) { self.tableSelector = '.page-registero-de-nf-detail table'; self.getCustomerList(); self.getProductlist(); self.columnsSelected = self.vendedorColumn; self.eventHandlers(); } }, eventHandlers: function () { if (jQuery('body').hasClass('page-template-page-vinculacao-de-produtos')) { jQuery(document).on('click', '#xml-submit', self.enviarNfs); // jQuery(document).on('click', '#updateLink', self.enviarNfs); jQuery(document).on('click', '#update-invoice', self.checkInvoice); jQuery(document).on('click', '#toggleAll', self.toggleAlluser); } else { jQuery(document).on('click', '#xml-submit', self.submitInvoiceNF); jQuery(document).on('change', '#attach-xml', self.updateSelected); jQuery(document).on('click', '#update-invoice', self.checkInvoice); jQuery(document).on('click', '#toggleAll', self.toggleAlluser); jQuery(document).on('change', '.product-list-select', self.changeProductList); } }, changeProductList: function () { var selectedUser = jQuery(this).attr('name'); self.updatedProductListMap[selectedUser] = jQuery(this).val(); }, applySelectPagenation: function () { if (jQuery() && jQuery().select2) { jQuery(".product-list-select").select2({ minimumInputLength: 3, language: "pt-BR", ajax: { url: agco.helper.baseUrl + 'v1/adm/product/list/', dataType: 'json', type: 'POST', headers: {'x-auth-sb': globalJsData.token}, delay: 250, data: function (params) { var dataObject = { search_string: params.term, // search term page: params.page || 1, post_per_page: 100, }; return dataObject; }, processResults: function (data, params) { params.page = params.page || 1; var arr = [] if (data.data) { jQuery.each(data.data, function (index, value) { if (value.code) { arr.push({ id: value.code, text: value.description }); } }); } return { results: arr, }; }, }, }); } else { setTimeout(self.applySelectPagenation, 300); } }, updateSelected: function () { var data = jQuery('#attach-xml').val(); jQuery('.updateIntimation').remove(); if (data) { self.fileFlag = true; var FR = new FileReader(); // jQuery('.attached-file-name').html(form.find('input#file-attached').prop('files')[0]['name']); var baseValue; FR.addEventListener("load", function (e) { if (FR.result.indexOf("data:text/xml") < 0) { self.fileFlag = false; // jQuery('.attached-file-name').html(''); jQuery('#attach-xml').val(''); } else { baseValue = FR.result.split("data:text/xml;base64,")[1]; self.getImageFile(baseValue).then(function (data) { self.post = data; }, function (error) { // console.log(error); }) } }); FR.readAsDataURL(jQuery('#attach-xml').prop('files')[0]); } else { self.fileFlag = false; // jQuery('.attached-file-name').html(''); } }, getImageFile: function (imageBase64) { return new Promise(function (resolve, reject) { var base64Blob = agco.helper.base64toBlob(imageBase64, "text/xml"); resolve(base64Blob); }); }, toggleAlluser: function () { if (!jQuery(this).prop('checked')) { jQuery('tbody input[type="checkbox"]').each(function (i, element) { if (jQuery(element).prop('checked')) { jQuery(element).trigger('click'); } }); } else { jQuery('tbody input[type="checkbox"]').each(function (i, element) { if (!jQuery(element).prop('checked')) { jQuery(element).trigger('click'); } }); } }, checkInvoice: function () { var mechanic = jQuery('#cpf_mecanico').val(); if (!jQuery('tbody input[type="checkbox"]').length) { agco.helper.popUp('Error', 'Selecione uma nota para que o vínculo seja concluído.'); return false; } var selectedUser = {}; var forproductlist = []; var flag = false; jQuery('tbody input[type="checkbox"]').each(function (i, element) { if (jQuery(element).prop('checked')) { var selectedID = jQuery(element).val(); if (self.tableSelector.includes('vincula')) { selectedUser[selectedID] = true; flag = true; } else { var data = { 'codMaquina': '', 'item_id': '' }; data['item_id'] = selectedID; if (self.updatedProductListMap['mq' + selectedID]) { data['codMaquina'] = self.updatedProductListMap['mq' + selectedID]; } forproductlist.push(data); flag = true; } } }); if (!flag) { agco.helper.popUp('Error', 'Selecione uma nota para que o vínculo seja concluído.'); return false; } var endpoint; var data; var method; if (self.tableSelector.includes('vincula')) { endpoint = self.endpoints.checkInvoice; data = { 'invoices': selectedUser }; method = 'POST'; } else { endpoint = self.endpoints.updateLink; data = { 'data': forproductlist }; method = 'PUT'; if (mechanic) { data['cpf_mecanico'] = mechanic; } } agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, method, data, true, self.checkInvoiceSuccess, self.checkInvoiceError); }, checkInvoiceSuccess: function (success) { agco.helper.loader('hide'); if (!success || !success.code.includes('success')) { agco.helper.popUp('Error', 'Algo errado. Tente novamente'); return false; } agco.helper.popUp('SUCESSO!', success.message); }, checkInvoiceError: function (error) { agco.helper.loader('hide'); agco.helper.popUp('Error', 'Error al enviar el archivo. Soporte de contacto'); }, submitInvoiceNF: function () { // var clientCPF = jQuery('.client-cpf input').val(); // if (clientCPF.length < 14) { // agco.helper.popUp('Error', 'RUC/RUT no válido'); // return false; // } if (!self.fileFlag) { agco.helper.popUp('Error', 'Adjunte un archivo XML válido.'); return false; } var endpoint = self.endpoints.xmlInvoiceUpload; agco.helper.loader('show'); var data = new FormData; // data.append('score_cpf', clientCPF); data.append('file', self.post); agco.helper.appApiRequest(endpoint, 'POST', data, true, self.submitInvoiceSuccess, self.submitInvoiceError); // _success }, submitInvoiceSuccess: function (success) { agco.helper.loader('hide'); if (!success || success.code.includes('error')) { agco.helper.popUp('Error', success.message); return false; } agco.helper.popUp('Éxito', 'FACTURA TRIBUTARIA ENVIADA EXITOSAMENTE.'); }, submitInvoiceError: function (error) { agco.helper.loader('hide'); agco.helper.popUp('Error', 'Error al enviar el archivo. Soporte de contacto'); }, applyMask: function () { if (jQuery() && jQuery().mask()) { jQuery('#nota-programa-balcao').mask('00000000000000000000000000000000000000000000'); } else { setTimeout(function () { self.applyMask(); }, 300); } }, enviarNfs: function () { var endpoint = self.endpoints.enviarNfs; var mechanic = jQuery('#cpf_mecanico').val(); var invoices = jQuery('#nota-programa-balcao').val(); if (!invoices || invoices.length < 44) { agco.helper.popUp('Error', 'Favor digitar o número da nota'); return false; } var data = { 'invoices': invoices }; if (mechanic) { data['cpf_mecanico'] = mechanic; } //data.append('search_string', ''); agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', data, true, self.enviarNfsSuccess, self.enviarNfsError); }, enviarNfsSuccess: function (success) { agco.helper.loader('hide'); if (success.message) { agco.helper.popUp('Aviso', success.message); return false; } agco.helper.popUp('Aviso!', "Nota vinculada ao vendedor sucesso!"); }, enviarNfsError: function (error) { agco.helper.loader('hide'); if (error.message) { agco.helper.popUp('Error', error.message); return false; } agco.helper.popUp('Error', 'Erro ao enviar o arquivo. Entre em contato com o suporte.'); //agco.helper.popUp('SUCESSO!', "Nota vinculada ao vendedor sucesso!"); }, getCustomerList: function () { var endpoint = self.endpoints.getCustomer; var data = new FormData; data.append('search_string', ''); agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', data, true, self.getCustomerListSuccess, self.getCustomerListError); }, getCustomerListSuccess: function (success) { agco.helper.loader('hide'); }, getCustomerListError: function (error) { agco.helper.loader('hide'); }, getProductlist: function () { var endpoint = self.endpoints.productList; var data = new FormData; data.append('search_string', ''); agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', data, true, self.getProductlistSuccess, self.getProductlistError); }, getProductlistSuccess: function (success) { agco.helper.loader('hide'); if (success && success.data) { self.productList = success.data; } self.checkIfVendedor(); }, getProductlistError: function (error) { agco.helper.loader('hide'); }, checkIfVendedor: function () { var endpoint = self.endpoints.getList; if (self.tableSelector.includes('page-registero')) { endpoint = endpoint + '?linked=true'; } agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', {}, true, self.getListSuccess, self.getListError); }, getListSuccess: function (success) { agco.helper.loader('hide'); // console.log('Vinculo NF', success.data); var list = success.data ? success.data : []; agco.helper.loadDataTableWithdata(list, self.columnsSelected, self.tableSelector); self.applySelectPagenation(); list.forEach(element => { self.allCodeIdPairs[element.id] = element.codMaquina ? element.codMaquina : ""; }); }, getListError: function (error) { agco.helper.loader('hide'); self.allCodeIdPairs = {}; agco.helper.loadDataTableWithdata([], self.columnsSelected, self.tableSelector); }, } return self; }(); jQuery(document).ready(function () { agco.vincularDeNotas.ready(); }); agco.envioCampanha = function () { var self = { endpoints: { 'enviarNfs': 'v1/adm/venda/registernota/', 'sendFiles': 'v1/adm/register/files' }, allCodeIdPairs: {}, post: '', post_aut: '', tableSelector: '', updatedProductListMap: {}, columnsSelected: {}, ready: function () { if (jQuery('.page-template-page-concurso-cultural').length) { self.eventHandlers(); } else if (jQuery('.page-template-page-concurso-cultural-envio').length) { self.eventHandlers(); } }, eventHandlers: function () { jQuery(document).on('change', '#attach-xml', self.updateSelected); jQuery(document).on('change', '#attachh-xml', self.updateSelectedd); jQuery(document).on('click', '#billPay', self.submitFiles); jQuery(document).on('click', '#remove-xml', self.removeSelected); jQuery(document).on('click', '.upload-error', self.closePopup); }, removeSelected: function () { jQuery('#attach-xml').val(''); jQuery('#attachh-xml').val(''); self.fileFlag = false; jQuery('.attached-file-name').html(''); jQuery('#remove-xml').attr('hidden', true); jQuery('#billPay').attr('hidden', true); }, closePopup: function () { /*jQuery('.concurso-failure-content').attr('hidden',true); jQuery('.concurso-cultural-popup').attr('hidden', true);*/ jQuery('.concurso-cultural-popup').attr('hidden', true); jQuery('.concurso-success-section').attr('hidden', true); jQuery('.concurso-failure-section').attr('hidden', true); }, triggerFilePicker: function () { jQuery('#attach-xml').click(); jQuery('#attachh-xml').click(); }, redirectPage: function () { window.location.href = "/concurso-cultural-enviar/"; }, updateSelected: function () { var data = jQuery('#attach-xml').val(); jQuery('.updateIntimation').remove(); if (data) { self.fileFlag = true; var FR = new FileReader(); jQuery('.attached-file-name').html(jQuery('#attach-xml').prop('files')[0]['name']); jQuery('#remove-xml').attr('hidden', false); jQuery('#billPay').attr('hidden', false); var baseValue; FR.addEventListener("load", function (e) { // console.log(FR.result); if (FR.result.indexOf("data:") < 0) { self.fileFlag = false; // jQuery('.attached-file-name').html(''); jQuery('#attach-xml').val(''); } else { //baseValue = FR.result.split("data:application/pdf;base64,")[1]; if (FR.result.split("data:application/pdf;base64,")[1]) { baseValue = FR.result.split("data:application/pdf;base64,")[1]; self.getImagePDF(baseValue).then(function (data) { self.post_aut = data; }, function (error) { // console.log(error); }) } else if (FR.result.split("data:application/msword;base64,")[1]) { baseValue = FR.result.split("data:application/msword;base64,")[1]; self.getImageDOC(baseValue).then(function (data) { self.post_aut = data; }, function (error) { // console.log(error); }) } else if (FR.result.split("data:image/jpeg;base64,")[1]) { baseValue = FR.result.split("data:image/jpeg;base64,")[1]; self.getImageFileJpeg(baseValue).then(function (data) { self.post_aut = data; }, function (error) { // console.log(error); }) } else if (FR.result.split("data:image/png;base64,")[1]) { baseValue = FR.result.split("data:image/png;base64,")[1]; self.getImageFilePng(baseValue).then(function (data) { self.post_aut = data; }, function (error) { // console.log(error); }) } } }); FR.readAsDataURL(jQuery('#attach-xml').prop('files')[0]); } else { self.fileFlag = false; // jQuery('.attached-file-name').html(''); } }, updateSelectedd: function () { var data = jQuery('#attachh-xml').val(); jQuery('.updateIntimation').remove(); if (data) { self.fileFlag = true; var FR = new FileReader(); jQuery('.attached-file-name').html(jQuery('#attachh-xml').prop('files')[0]['name']); jQuery('#remove-xml').attr('hidden', false); jQuery('#billPay').attr('hidden', false); var baseValue; FR.addEventListener("load", function (e) { // console.log(FR.result.indexOf("data:video/mp4")); if (FR.result.indexOf("data:image/jpeg") < 0 && FR.result.indexOf("data:video/mp4") < 0) { self.fileFlag = false; //jQuery('.attached-file-name').html(''); jQuery('#attachh-xml').val(''); } // console.log(FR.result.indexOf("data:video/mp4") == 0); if (FR.result.indexOf("data:video/mp4") == 0) { baseValue = FR.result.split("data:video/mp4;base64,")[1]; self.getImageMovie(baseValue).then(function (data) { self.post = data; }, function (error) { // console.log(error); }); } else if (FR.result.indexOf("data:image/jpeg") == 0) { baseValue = FR.result.split("data:image/jpeg;base64,")[1]; self.getImageFileJpeg(baseValue).then(function (data) { self.post = data; }, function (error) { // console.log(error); }); } }); FR.readAsDataURL(jQuery('#attachh-xml').prop('files')[0]); } else { self.fileFlag = false; } }, getImageDOC: function (imageBase64) { // console.log('Aquii', imageBase64) return new Promise(function (resolve, reject) { var base64Blob = agco.helper.base64toBlob(imageBase64, "application/msword;base64"); resolve(base64Blob); }); }, getImagePDF: function (imageBase64) { // console.log('Aquii', imageBase64) return new Promise(function (resolve, reject) { var base64Blob = agco.helper.base64toBlob(imageBase64, "application/pdf"); resolve(base64Blob); }); }, getImageMovie: function (imageBase64) { return new Promise(function (resolve, reject) { var base64Blob = agco.helper.base64toBlob(imageBase64, "video/mp4"); resolve(base64Blob); }); }, getImageFileJpeg: function (imageBase64) { return new Promise(function (resolve, reject) { var base64Blob = agco.helper.base64toBlob(imageBase64, "image/jpeg"); resolve(base64Blob); }); }, getImageFilePng: function (imageBase64) { return new Promise(function (resolve, reject) { var base64Blob = agco.helper.base64toBlob(imageBase64, "image/png"); resolve(base64Blob); }); }, toggleAlluser: function () { if (!jQuery(this).prop('checked')) { jQuery('tbody input[type="checkbox"]').each(function (i, element) { if (jQuery(element).prop('checked')) { jQuery(element).trigger('click'); } }); } else { jQuery('tbody input[type="checkbox"]').each(function (i, element) { if (!jQuery(element).prop('checked')) { jQuery(element).trigger('click'); } }); } }, submitFiles: function () { if (!self.fileFlag) { jQuery('.concurso-cultural-popup').attr('hidden', false); jQuery('.concurso-success-section').attr('hidden', true); jQuery('.concurso-failure-section').attr('hidden', false); return false; } var endpoint = self.endpoints.sendFiles; agco.helper.loader('show'); // console.log('selfpost antes', self.post_aut); var data = new FormData; if (self.post_aut) { // console.log('cai aqui'); data.append('file_aut', self.post_aut); } else { data.append('file', self.post); } // console.log(data); agco.helper.appApiRequest(endpoint, 'POST', data, true, self.submitInvoiceSuccess, self.submitInvoiceError); // _success }, submitInvoiceSuccess: function (success) { agco.helper.loader('hide'); if (!success || success.code.includes('error')) { jQuery('.concurso-cultural-popup').attr('hidden', false); jQuery('.concurso-success-section').attr('hidden', true); jQuery('.concurso-failure-section').attr('hidden', false); return false; } jQuery('.concurso-cultural-popup').attr('hidden', false); jQuery('.concurso-success-section').attr('hidden', false); jQuery('.concurso-failure-section').attr('hidden', true); self.redirectPage(); }, submitInvoiceError: function (error) { agco.helper.loader('hide'); // console.log(error); jQuery('.concurso-cultural-popup').attr('hidden', false); jQuery('.concurso-cultural-popup').attr('hidden', false); jQuery('.concurso-success-section').attr('hidden', true); jQuery('.concurso-failure-section').attr('hidden', false); }, } return self; }(); jQuery(document).ready(function () { agco.envioCampanha.ready(); }); agco.lubrificante = function () { var self = { ready: function () { if (jQuery('.post-type-archive-lubrificante').length) { self.eventHandlers(); self.loadSlick(); } }, eventHandlers: function () { }, loadSlick: function () { if (jQuery() && jQuery().slick && jQuery('.lubrificante-row').length) { jQuery('.lubrificante-row').slick({ dots: true, arrows: true, infinite: false, slidesToShow: 3, slidesToScroll: 1, }); } else { setTimeout(function () { self.loadSlick(); }, 200); } }, } return self; }(); jQuery(document).ready(function () { agco.lubrificante.ready(); }); agco.CnpjGroup = function () { var self = { endpoints: { 'getCnpjGroup': 'v1/adm/list-cnpj-group/', 'insertCnpjGroup': 'v1/adm/insert-cnpj-group/', 'updateCnpjGroup': 'v1/adm/update-cnpj-group/', 'removeCnpjGroup': 'v1/adm/cnpj-group-delete/' }, ClienteColumns: [ { "data": "cnpj_matriz", "title": "CNPJ MATRIZ" }, { "data": "cnpj_filial", "title": "CNPJ FILIAL" }, { "data": "", "title": "", render: function (data, type, rowObject, metat) { return ""; } }, ], ready: function () { if (jQuery('.page-template-page-cnpj-group').length) { self.eventHandlers(); var data = { 'start_date': '', 'end_date': '' }; self.getCnpjCpf(data); } }, eventHandlers: function () { jQuery(document).on('click', '.filter-by-date', self.searchByDate); jQuery(document).on('click', '.editAction', self.filterUser); jQuery(document).on('click', '.createNew', self.showCreateVinc); jQuery(document).on('click', '.removeVinc', self.removeVinculo); jQuery(document).on('click', '#addNewPart', self.submitNewUser); jQuery(document).on('click', '#addNewCNPJGroup', self.createNewCNPJGroup); jQuery(document).on('click', '#close', self.hideAddForm); }, searchByDate: function () { var start = jQuery('#start-date').val(); var end = jQuery('#ending-date').val(); if ((start != end) && (!moment(end).isAfter(moment(start)))) { agco.helper.popUp('Erro', 'A data de início deve ser menor ou igual a data final.'); return false; } var data = { 'start_date': start, 'end_date': end }; self.getCnpjCpf(data); }, showAddForm: function () { jQuery('.addNewForm').attr('hidden', false); }, hideAddForm: function () { self.isEdit = false; jQuery('.addNewForm').attr('hidden', true); jQuery('.createNewForm').attr('hidden', true); }, showCreateVinc: function () { jQuery('.createNewForm').attr('hidden', false); }, createNewCNPJGroup: function () { var method = 'POST'; var endpoint = self.endpoints.insertCnpjGroup; var data; data = { 'cnpj_matriz' : jQuery('#new_cnpj_matriz').val(), 'cnpj_filial' : jQuery('#new_cnpj_filial').val(), } agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, method, data, true, self.successSubmitForm, self.errorCallBackSubmitForm); }, //Dados nos campos filterUser: function () { self.showAddForm(); var selectedData = {}; selectedData.cnpj_matriz = jQuery(this).data('cnpj_matriz'); selectedData.cnpj_filial = jQuery(this).data('cnpj_filial'); selectedData.id = jQuery(this).data('id'); jQuery('#edit_matriz').val(selectedData.cnpj_matriz); jQuery('#edit_filial').val(selectedData.cnpj_filial); jQuery('#id').val(selectedData.id); }, //Trazendo dados do banco getCnpjCpf: function (filter) { var endpoint = self.endpoints.getCnpjGroup; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', filter, true, self.getVendedorListSuccess, self.getVendedorListError); }, getVendedorListSuccess: function (success) { agco.helper.loader('hide'); var list = success.data ? success.data : []; agco.helper.loadDataTableWithdata(list, self.ClienteColumns, '.admin-page-registered-nf-detail table'); }, getVendedorListError: function (error) { agco.helper.loader('hide'); agco.helper.loadDataTableWithdata([], self.ClienteColumns, '.admin-page-registered-nf-detail table'); }, submitNewUser: function () { var method = 'POST'; var endpoint = self.endpoints.updateCnpjGroup; var data; data = { 'cnpj_matriz' : jQuery('#edit_matriz').val(), 'cnpj_filial' : jQuery('#edit_filial').val(), 'id' : jQuery('#id').val() } agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, method, data, true, self.successSubmitForm, self.errorCallBackSubmitForm); }, successSubmitForm: function (success) { // console.log('success SubmitForm', success); agco.helper.loader('hide'); if (location.href.indexOf('/cnpj-grupo-economico/') > 0) { if (success && success.code === 'insertCnpjGroup_success') { agco.helper.popUp('Sucesso', success.message); agco.helper.popUp('Sucesso', success.message, agco.Register.reloadPage); } if (success && success.code !== 'insertCnpjGroup_success') { agco.helper.popUp('Erro', success.message); return false; } } }, errorCallBackSubmitForm: function (error) { self.accessPageData = ''; agco.helper.loader('hide'); agco.helper.popUp('Erro', error.message); }, removeVinculo: function () { var endpoint = self.endpoints.removeCnpjGroup; var dataSend; dataSend = { 'cnpj_filial': jQuery(this).data('cnpj_filial') } agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', dataSend, true, self.successDelete, self.errorDelete); }, successDelete: function (success) { agco.helper.loader('hide'); if (location.href.indexOf('/cnpj-grupo-economico/') > 0) { if (success && success.code === 'deleteCnpjGroup_success') { agco.helper.popUp('Sucesso', success.message); agco.helper.popUp('Sucesso', success.message, agco.Register.reloadPage); } if (success && success.code !== 'deleteCnpjGroup_success') { agco.helper.popUp('Erro', success.message); } } }, errorDelete: function (error) { agco.helper.loader('hide'); agco.helper.popUp('Erro', error.message); }, } return self; }(); jQuery(document).ready(function () { agco.CnpjGroup.ready(); }); agco.managerDealership = function () { var self = { endpoints: { 'getListCnpj': 'v1/adm/list-manager-cnpj/', 'editCnpjCpf': 'v1/adm/update-cnpj-manager/', 'removeLinkDealership': 'v1/adm/delete-cnpj-manager/' }, ClienteColumns: [ { "data": "cnpj_concessionaria", "title": "CNPJ Associado" }, { "data": "cpf_gerente", "title": "CPF do Gerente" }, { "data": "", "title": "", render: function (data, type, rowObject, metat) { return ""; } }, { "data": "", "title": "", render: function (data, type, rowObject, metat) { return ""; } }, ], ready: function () { if (jQuery('.page-template-page-manager-dealership').length) { self.eventHandlers(); var data = { 'start_date': '', 'end_date': '' }; self.getListCnpjManager(data); } }, eventHandlers: function () { jQuery(document).on('click', '.filter-by-date', self.searchByDate); jQuery(document).on('click', '.editAction', self.filterUser); jQuery(document).on('click', '.createNew', self.showCreateVinc); jQuery(document).on('click', '.removeVinc', self.removeVinculo); jQuery(document).on('click', '#addNewPart', self.submitNewUser); jQuery(document).on('click', '#addNewVinc', self.createNewVinc); jQuery(document).on('click', '#close', self.hideAddForm); }, searchByDate: function () { var start = jQuery('#start-date').val(); var end = jQuery('#ending-date').val(); if ((start != end) && (!moment(end).isAfter(moment(start)))) { agco.helper.popUp('Erro', 'A data de início deve ser menor ou igual a data final.'); return false; } var data = { 'start_date': start, 'end_date': end }; self.getListCnpjManager(data); }, showAddForm: function () { jQuery('.addNewForm').attr('hidden', false); }, hideAddForm: function () { self.isEdit = false; jQuery('.addNewForm').attr('hidden', true); jQuery('.createNewForm').attr('hidden', true); }, showCreateVinc: function () { jQuery('.createNewForm').attr('hidden', false); }, createNewVinc: function () { var method = 'POST'; var endpoint = self.endpoints.editCnpjCpf; var cnpj = jQuery('#new_cnpj').val(); var cpf = jQuery('#new_cpf').val(); var dataUser = { 'cnpj': cnpj, 'cpf': cpf }; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, method, dataUser, true, self.successSubmitForm, self.errorCallBackSubmitForm); }, filterUser: function () { self.showAddForm(); var selectedData = {}; selectedData.cpf = jQuery(this).data('cpf'); selectedData.cnpj = jQuery(this).data('cnpj'); selectedData.id = jQuery(this).data('id'); jQuery('#cpf').val(selectedData.cpf); jQuery('#cnpj').val(selectedData.cnpj); jQuery('#id').val(selectedData.id); }, getListCnpjManager: function (filter) { var endpoint = self.endpoints.getListCnpj; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', filter, true, self.getVendedorListSuccess, self.getVendedorListError); }, getVendedorListSuccess: function (success) { agco.helper.loader('hide'); var list = success.data ? success.data : []; agco.helper.loadDataTableWithdata(list, self.ClienteColumns, '.admin-page-registered-nf-detail table'); }, getVendedorListError: function (error) { agco.helper.loader('hide'); agco.helper.loadDataTableWithdata([], self.ClienteColumns, '.admin-page-registered-nf-detail table'); }, submitNewUser: function () { var id = jQuery('#id').val(); var method = 'POST'; var endpoint = self.endpoints.editCnpjCpf; var cnpj = jQuery('#cnpj').val(); var cpf = jQuery('#cpf').val(); var dataUser = { 'cnpj': cnpj, 'cpf': cpf, 'id' : id }; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, method, dataUser, true, self.successSubmitForm, self.errorCallBackSubmitForm); }, successSubmitForm: function (success) { agco.helper.loader('hide'); if (location.href.indexOf('/dealership-manager-link/') > 0) { if (success && success.code === 'insertCnpjManager_success') { agco.helper.popUp('Sucesso', success.message); agco.helper.popUp('Sucesso', success.message, agco.Register.reloadPage); } if (success && success.code !== 'insertCnpjManager_success') { agco.helper.popUp('Erro', success.message); //agco.helper.popUp('Sucesso', success.message, agco.Register.reloadPage); return false; } } }, errorCallBackSubmitForm: function (error) { self.accessPageData = ''; if (location.href.indexOf('primeiro-acesso/') > 0) { jQuery('#stepform').steps("previous"); jQuery('#reg_email').prop('disabled', true); jQuery('#telefone').prop('disabled', true); jQuery('#nomecompleto').prop('disabled', true); } agco.helper.loader('hide'); agco.helper.popUp('Erro', error.message); }, removeVinculo: function () { var endpoint = self.endpoints.removeLinkDealership; var id = jQuery(this).data("id"); var data = { 'id': id }; agco.helper.loader('show'); agco.helper.appApiRequest(endpoint, 'POST', data, true, self.successDelete, self.errorDelete); }, successDelete: function (success) { agco.helper.loader('hide'); if (location.href.indexOf('/dealership-manager-link/') > 0) { if (success && success.code === 'deleteCnpjDealership_success') { agco.helper.popUp('Sucesso', success.message); agco.helper.popUp('Sucesso', success.message, agco.Register.reloadPage); } if (success && success.code !== 'deleteCnpjDealership_success') { agco.helper.popUp('Erro', success.message); return false; } } }, errorDelete: function (error) { agco.helper.loader('hide'); agco.helper.popUp('Erro', error.message); }, } return self; }(); jQuery(document).ready(function () { agco.managerDealership.ready(); });