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('
");
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('', {
class: errorClassName,
for : element,
html: errorMessage,
});
if (!jQuery('#' + element).parent().find('.error').length) {
jQuery('#' + element).addClass('error');
jQuery(errorLabel).appendTo(jQuery('#' + element).parent());
}
},
listenAjaxCall: function () {
jQuery(document).ajaxComplete(function (event, request, settings) {
if (settings && settings.url.indexOf('/contact-forms/') <= 0) {
return false;
}
if (request && request.status === 200) {
if (request.responseJSON && request.responseJSON.status == 'validation_failed') {
jQuery('.wpcf7-validation-errors').remove();
agco.helper.loader('hide');
} else if (request.responseJSON && request.responseJSON.status == 'mail_sent') {
jQuery('.wpcf7-response-output').remove();
agco.helper.loader('hide');
agco.helper.popUp('Éxito', 'Mensagem enviada com sucesso.', agco.contactPage.toHomePage);
} else {
agco.helper.loader('hide');
}
}
});
},
toHomePage: function () {
window.location.href = window.location.protocol + "//" + document.location.host + '/';
}
};
return self;
}();
jQuery(document).ready(function () {
agco.contactPage.ready();
});
agco.checkoutPage = function () {
var self = {
endpoints: {
'checkBarcode': 'site/check/barcode',
},
fieldsToValidate: [
{
id: 'tipoConta',
errorMessage: 'Tipo de Conta inválido',
isValid: false,
mandatory: true,
},
{
id: 'pagBarcode',
errorMessage: 'Código de Barras inválido',
isValid: false,
mandatory: true,
},
{
id: 'pagVencimento',
errorMessage: 'Vencimento inválido',
isValid: false,
mandatory: true,
},
{
id: 'pagPagamento',
errorMessage: 'Pagamento inválido',
isValid: false,
mandatory: true,
},
{
id: 'pagCPF',
errorMessage: 'CPF inválido',
isValid: false,
mandatory: true,
},
{
id: 'pagPontos',
errorMessage: 'Valor de Boleto inválido',
isValid: false,
mandatory: true,
},
{
id: 'pagVencimento',
errorMessage: 'Valor em Pontos inválido',
isValid: false,
mandatory: true,
},
],
ready: function () {
if (jQuery('.page-template-page-checkout-php').length) {
self.load();
}
},
load: function () {
self.removeSelect2();
},
removeSelect2: function () {
if (jQuery() && jQuery().select2 && jQuery('#billing_state').hasClass('select2-hidden-accessible')) {
jQuery('#billing_state').select2('destroy');
} else {
setTimeout(function () {
self.removeSelect2();
}, 300);
}
},
};
return self;
}();
jQuery(document).ready(function () {
agco.checkoutPage.ready();
});
agco.seusPedidos = function () {
var self = {
isValidDate: false,
endpoint: {
'extrato': 'v1/orders'
},
columns: [
{
"data": "order_date",
"title": "FECHA",
render: function (data, type, rowObject, metat) {
var date = rowObject.order_date;
if (date) {
var formatedDate = moment(data).format('DD/MM/YYYY');
return formatedDate;
} else {
return '';
}
}
},
{
"data": "order_id",
"title": "NUMÉRO DEL PEDIDO"
},
{
"data": "order_status",
"title": "ESCRIBE"
},
{
"data": "order_fee",
"title": "VALOR",
render: function (data, type, rowObject, metat) {
var points = rowObject.order_fee != 0 ? rowObject.order_fee + ' pts ' : '0,00 pts ';
var rDollerValue = rowObject.order_total != 0 ? ' R$ ' + rowObject.order_total : ' R$ 0,00';
return points + '+' + rDollerValue;
}
},
// {
// "data": "order_fee",
// "title": "Ações",
// render: function (data, type, rowObject, metat) {
// var text = rowObject.order_view_url;
// text = text + rowObject.order_pay_url;
// return text;
// }
// },
],
ready: function () {
if (jQuery('.page-template-page-ecom-orders-php').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.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();
},
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.seusPedidos.ready();
});
agco.voucherPage = function () {
var self = {
endpoint: {
'receipt': 'v1/site/user/receipts'
},
columns: [
{
"data": "entrydate",
"title": "DATA",
render: function (data, type, rowObject, metat) {
var date = rowObject.entrydate;
if (date) {
var formatedDate = moment(data).format('DD/MM/YYYY');
return formatedDate;
} else {
return '';
}
}
},
{
"data": "points",
"title": "QTD PTS",
render: function (data, type, rowObject, metat) {
return agco.helper.ptBrNumberFormat(rowObject.points, true);
}
},
{
"data": "receiptid",
"title": "PROTOCOLO"
},
{
"data": "orderid",
"title": "PEDIDO"
},
{
"data": "valordaconta",
"title": "VALOR (R$)",
render: function (data, type, rowObject, metat) {
return agco.helper.ptBrNumberFormat(rowObject.valordaconta, true);
}
},
{
"data": "status",
"title": "COMPROVANTE",
render: function (data, type, rowObject, metat) {
var text;
if (rowObject.status === 'completo') {
text = "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('', {
class: 'delete-comment',
id: comment[1][0]['comment_ID'],
html: "X"
}).appendTo(jQuery('div.replySlice_' + comment[1][0]['comment_ID']));
}
}
} else {
jQuery('', {
class: 'comment_holder comment_holder_' + self.postID + '_id_' + index,
html: ''
}).appendTo(commentSection);
jQuery('', {
class: 'single-comment single_holder_' + self.postID + '_id_' + index,
html: ''
}).appendTo('div.comment_holder_' + self.postID + '_id_' + index);
jQuery(' ', {
class: 'comment-avatar',
src: comment[1][0]['avatar_url'],
}).appendTo(jQuery('div.single_holder_' + self.postID + '_id_' + index));
jQuery('', {
class: 'like-reply liked',
id: 'like_' + comment[1][0].comment_ID,
}).appendTo(jQuery('div.single_holder_' + self.postID + '_id_' + index));
jQuery('', {
class: 'comment-reactions-count d-flex',
id: 'comment_reaction_' + comment[1][0].comment_ID,
}).appendTo(jQuery('div.single_holder_' + self.postID + '_id_' + index));
jQuery('div#comment_reaction_' + comment[1][0].comment_ID).append(reactions);
jQuery('', {
html: 'Responder',
class: 'replyToggle'
}).appendTo(jQuery('div#comment_reaction_' + comment[1][0].comment_ID));
jQuery('', {
html: reactionCount
}).appendTo(jQuery('div#comment_reaction_' + comment[1][0].comment_ID + ' .icon a'));
if (comment[1][0]['liked_users'] && comment[1][0]['liked_users'].length) {
var likedUsers = jQuery('', {
style: "display:none",
class: "liked-users",
likedUsers: JSON.stringify(comment[1][0]['liked_users'])
}).appendTo(jQuery('div#comment_reaction_' + comment[1][0].comment_ID).find('.like'));
comment[1][0]['liked_users'].forEach(function (user) {
jQuery('', {
html: user.display_name
}).appendTo(likedUsers);
})
}
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('', {
class: 'single-comment-data',
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('', {
class: 'delete-comment',
id: comment[1][0].comment_ID,
html: "X"
}).appendTo(jQuery('div.single_holder_' + self.postID + '_id_' + index));
}
jQuery('', {
class: 'reply-comment-section hide reply_' + comment[1][0].comment_ID,
}).appendTo(jQuery('div.comment_holder_' + self.postID + '_id_' + index));
jQuery('', {
class: 'new-reply new-reply_' + self.postID + '_id_' + index
}).appendTo(jQuery('.reply_' + comment[1][0].comment_ID));
jQuery('', {
placeholder: "Responder"
}).appendTo(jQuery('.new-reply_' + self.postID + '_id_' + index));
jQuery('', {
class: 'attachReplyFile btn btn-gray',
type: 'file',
id: "attachReplyFile_" + self.postID,
}).appendTo(jQuery('.new-reply_' + self.postID + '_id_' + index));
jQuery('', {
for : "attachReplyFile_" + self.postID,
html: '',
}).appendTo(jQuery('.new-reply_' + self.postID + '_id_' + index));
jQuery('', {
class: 'replyComment',
id: 'replyBtn_' + comment[1][0].comment_ID,
html: ""
}).appendTo(jQuery('.new-reply_' + self.postID + '_id_' + index));
}
// let momentDate = moment(comment[1][0].comment_date);
// let postDateWithFormat = momentDate.format("DD") + " de " + momentDate.format("MMM") + " às " + momentDate.format("hh:mm");
let agoFormat = moment.utc(comment[1][0].comment_date_gmt).local().fromNow(true);
jQuery('', {
class: 'remaining-time',
html: agoFormat ? 'Há ' + agoFormat : ''
}).appendTo('div#comment_reaction_' + comment[1][0].comment_ID);
// jQuery('div.comment_holder_' + self.postID + '_id_' + index).find('.reply-comment-section').hide();
});
jQuery('.new-reply').hide();
jQuery('.new-reply').addClass('hide');
// jQuery('.new-comment').hide();
// jQuery('.new-comment').addClass('hide');
if (jQuery('div.comment_toggle_' + self.postID + ' a').length && cmtLength > 3) {
jQuery('div.comment_toggle_' + self.postID + ' a').remove();
jQuery('', {
class: 'show-more-comments',
href: 'javascript:void(0);',
html: 'MAIS COMENTÁRIOS'
}).appendTo(jQuery('div.comment_toggle_' + self.postID));
} else {
jQuery('div.comment_toggle_' + self.postID + ' a').remove();
}
jQuery(singlePost).find('.comment_holder').each(function (index, ele) {
if (index > 2) {
jQuery(ele).hide();
}
});
jQuery(singlePost).find('div.replyHolder').each(function (position, element) {
if (jQuery(element).find('div.replySlice').length > 2) {
let replyHolderID = jQuery(element).attr('id');
jQuery('', {
class: 'show-more-replies',
href: 'javascript:void(0);',
html: 'Ver mais respostas'
}).appendTo(jQuery('div#' + replyHolderID));
jQuery(element).find('div.replySlice').each(function (index, ele) {
if (index > 1 && jQuery(ele).attr('class') != 'show-more-replies') {
jQuery(ele).hide();
}
});
}
});
jQuery('', {
class: 'comment-text',
type: 'text',
placeholder: 'Adicionar comentário'
}).appendTo(jQuery('.new-comment_' + self.postID));
jQuery('', {
class: 'attachFile btn btn-gray',
id: "attachFile_" + self.postID,
type: 'file',
}).appendTo(jQuery('.new-comment_' + self.postID));
jQuery('', {
for : "attachFile_" + self.postID,
html: '',
}).appendTo(jQuery('.new-comment_' + self.postID));
jQuery('', {
class: 'add-new-comment btn btn-gray',
id: self.postID,
type: 'button',
html: ''
}).appendTo(jQuery('.new-comment_' + self.postID));
self.timeLineLoader('hide');
},
errorCallBackGetExactComment: function (error) {
self.timeLineLoader('hide');
// console.log("cmt exact error", error);
},
addReaction: function (e) {
e.preventDefault();
self.previousLikeCount = '';
self.emojiToken = this;
let emojiIndex = jQuery(this).parent().index() + 1;
let postId = jQuery(this).closest('.single-post').find('.add-new-comment').attr('id');
var likeCount = jQuery(this).find('.reactionCount').html();
self.previousLikeCount = parseInt(likeCount);
if (jQuery(this).parent().hasClass('like')) {
if (likeCount) {
jQuery(this).find('.reactionCount').html(parseInt(likeCount) - 1);
self.removeLikedUser(postId, 'post');
}
} else {
jQuery(this).find('.reactionCount').html(parseInt(likeCount) + 1);
self.addLikedUser(postId, 'post');
}
self.postID = postId;
let endpoint = self.endPoint.emoji;
let emojiData = {
"emoji_id": emojiIndex.toString(),
"post_id": postId.toString(),
"cpf": agco.helper.getCpf()
}
// agco.helper.loader('show');
agco.helper.appApiRequest(endpoint, 'POST', emojiData, true, self.successCallBackAddReaction, self.errorCallBackAddReaction);
},
removeLikedUser: function (postId, type) {
var userName = globalJsData.user.data.display_name;
if (type == 'post') {
var likeListElement = jQuery('#' + postId + '-likeShow').find('.liked-users');
var likeList = JSON.parse(jQuery(likeListElement).attr('likedusers'));
var updatedList = likeList;
var userIndex;
if (likeList.length) {
likeList.forEach(function (element, index) {
if (element.display_name == userName) {
userIndex = index;
updatedList.splice(index, 1);
}
});
jQuery(likeListElement).attr('likedusers', JSON.stringify(updatedList));
jQuery(likeListElement).find('p')[userIndex].remove();
}
} else {
}
},
addLikedUser: function (postId, type) {
var userName = globalJsData.user.data.display_name;
if (type == 'post') {
var likeListElement = jQuery('#' + postId + '-likeShow').find('.liked-users');
var likeList = JSON.parse(jQuery(likeListElement).attr('likedusers'));
var structure = {
display_name: userName
};
likeList.push(structure)
jQuery(likeListElement).attr('likedusers', JSON.stringify(likeList));
var userNameElement = jQuery('', {
html: userName,
})
jQuery(userNameElement).appendTo(likeListElement);
} else {
}
},
successCallBackAddReaction: function (success) {
self.timeLineLoader('hide');
let endpoint = self.endPoint.emoji;
let emojiData = {
"post_id": self.postID.toString(),
"cpf": agco.helper.getCpf()
}
agco.helper.appApiRequest(endpoint, 'GET', emojiData, true, self.successCallBackReaction, self.errorCallBackReaction);
},
errorCallBackAddReaction: function (error) {
self.timeLineLoader('hide');
jQuery(this).find('.reactionCount').html(self.previousLikeCount);
self.previousLikeCount = '';
// console.log("errorCallBackAddReaction ", error);
},
successCallBackReaction: function (success) {
self.timeLineLoader('hide');
var emojiCount = 0;
emojiCount += parseInt(success['emoji_1_count']);
let likeEmoji = jQuery(self.emojiToken).closest('.reaction-content .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);
}
jQuery(self.emojiToken).closest('.reaction-content').find('a .reactionCount').html(emojiCount);
// jQuery(self.emojiToken).closest('.reaction-content').find('div span.reactionText').html(" Curtidas");
},
errorCallBackReaction: function (error) {
self.timeLineLoader('hide');
jQuery(this).find('.reactionCount').html(self.previousLikeCount);
self.previousLikeCount = '';
// console.log(error);
},
appendFileAttachmentError: function (className, message) {
if (!jQuery("p." + className).length) {
jQuery('', {
class: className + " error",
html: message,
style: 'margin-left: 10px;'
}).insertAfter(jQuery('input#post-media'));
}
},
checkPostFile: function () {
if (!jQuery(this).val()) {
self.appendFileAttachmentError('fileValidation', 'Arquivo necessário.');
jQuery('p#fileName').remove();
} else {
jQuery('p.fileValidation').remove();
jQuery('p#fileName').remove();
jQuery('', {
html: jQuery('#post-media').prop('files')[0]['name'],
id: 'fileName',
style: 'margin-left: 10px;'
}).insertAfter(jQuery('input#post-media'));
}
},
checkTitle: function () {
if (!jQuery('.textarea').val().trim()) {
self.appendFileAttachmentError('titleValidation', 'Descrição está vazia.');
return;
} else {
jQuery('p.titleValidation').remove();
}
},
checkSelectMission: function () {
if (jQuery('select#getMission').val() === "-1") {
self.appendFileAttachmentError(jQuery('select#getMission'), 'selectMissionValidation', 'Selecione uma missão');
return;
} else {
jQuery('p.selectMissionValidation').remove();
}
},
addNewPost: function () {
if (!jQuery('#description').val().trim() && !jQuery('#post-media').val()) {
self.appendFileAttachmentError('titleValidation', 'Você não pode criar uma postagem vazia.');
return;
} else {
jQuery("p.titleValidation").remove();
}
jQuery("p.fileValidation").remove();
let post = new FormData();
if (jQuery('#post-media').val()) {
post.append('file', new Blob(jQuery('#post-media').prop('files'), {type: 'image/jpg'}), jQuery('#post-media').prop('files')[0]['name']);
}
if (jQuery("#description").val()) {
post.append('description', self.commentContent = self.getEmojiParsedString(jQuery("#description").val()));
}
post.append('cpf', agco.helper.getCpf());
post.append('orgin', 'site');
let endpoint = self.endPoint.achievement;
let postData = post;
self.timeLineLoader('show');
agco.helper.appApiRequest(endpoint, 'POST', postData, true, self.successCallBackAddPost, self.errorCallBackAddPost);
},
successCallBackAddPost: function (success) {
self.timeLineLoader('hide');
if ("insert_achievement_success" === success['code']) {
jQuery('.textarea').val('');
jQuery('p#fileName').remove();
jQuery('#post-media').val('');
// self.newPublishedPostId = success['data'][''].toString();
jQuery('div.post-list').scrollTop(10);
jQuery('div.post-list').scrollTop(0);
}
// console.log(success);
},
errorCallBackAddPost: function (erro) {
self.timeLineLoader('hide');
// console.log(erro);
},
getPosts: function () {
let endpoint = self.endPoint.achievement;
endpoint = endpoint + "?post_per_page=" + self.postsPerPage;
endpoint = endpoint + "&page=" + self.currentPage + "&cpf=" + agco.helper.getCpf();
if (self.postCallFlag) {
self.postCallFlag = false;
// if (self.currentPage == 1) {
self.timeLineLoader('show');
// }
agco.helper.appApiRequest(endpoint, 'GET', {}, true, self.successCallBackGetPosts, self.errorCallBackGetPosts);
}
},
successCallBackGetPosts: function (success) {
// console.log("Get Posts Success", success);
if (success.code !== "get_achievement_success" && success.code !== "get_admin_achievements_success") {
self.timeLineLoader('hide');
jQuery('#end-of-posts').html('');
self.postCallFlag = true;
jQuery('.load-more').hide();
return false;
}
var pickedList = success.data;
if (self.currentPage !== parseInt(pickedList.current_page)) {
self.timeLineLoader('hide');
self.postCallFlag = true;
jQuery('#end-of-posts').html('');
jQuery('.load-more').hide();
return false;
}
self.currentPage = parseInt(pickedList.current_page) + 1;
if (pickedList && pickedList.posts && pickedList.posts.length > 0) {
if (jQuery('#skyPost').hasClass('active')) {
self.printPosts(pickedList.posts);
} else {
self.printPosts(pickedList.posts);
}
if (pickedList.posts.length < 10) {
jQuery('.load-more').hide();
} else {
jQuery('.load-more').show();
}
} else {
self.timeLineLoader('hide');
jQuery('#end-of-posts').html('');
self.postCallFlag = true;
jQuery('.reaction-content').removeClass('d-flex');
jQuery('.reaction-content').hide();
jQuery('.load-more').hide();
}
},
errorCallBackGetPosts: function (error) {
self.timeLineLoader('hide');
jQuery('#end-of-posts').html('');
// console.log("Get Posts Error ", error);
self.postCallFlag = true;
jQuery('.load-more').hide();
},
printPosts: function (posts) {
// jQuery(".post-list").empty();
jQuery('.reaction-content').last().addClass('source');
let reactions = jQuery('.source').find('ol')[0].outerHTML;
if (!jQuery('.reaction-content').find('.likes').length) {
jQuery('.reaction-content').last().append("");
}
posts.forEach(function (post, index) {
if (jQuery('.post_' + post.id).length) {
jQuery('.post_' + post.id).parent().remove();
}
let cmtLength = Object.keys(post.comments).length;
let emoji = ['emoji_1_count', 'emoji_2_count', 'emoji_3_count', 'emoji_4_count', 'emoji_5_count', 'emoji_6_count'];
var emojiCount = 0;
emojiCount += parseInt(post['emoji_1_count']);
jQuery('.source').find('span').parent().html('');
// let reactionText = jQuery('', {
// class: 'reactionText',
// html: " Curtidas"
// }).appendTo(jQuery('.reaction-content').last().find('.likes'));
let reactionHtml = jQuery('.source').html();
let singlePost = jQuery('', {
class: 'single-post',
}).appendTo('.post-list');
let profileInfoDiv = jQuery('', {
class: 'profile-info'
}).appendTo(singlePost);
jQuery(' ', {
src: post.avatar_url,
class: 'comment-avatar'
}).appendTo(profileInfoDiv);
let nameTimeDiv = jQuery('', {
class: 'name-time'
}).appendTo(profileInfoDiv);
jQuery('', {
html: post.user_name,
class: 'userName-container'
}).appendTo(nameTimeDiv);
if (post.thumbnail && post.thumbnail[0]) {
let postImageDiv = jQuery('', {
class: 'post-image',
}).appendTo(singlePost);
jQuery(' ', {
src: post.thumbnail[0]
}).appendTo(postImageDiv);
}
if (post.can_delete == "yes") {
jQuery('', {
class: 'delete-post-button',
id: post.id,
'data-toggle': "modal",
'data-target': "#deletePopup",
html: "X"
}).appendTo(profileInfoDiv);
}
// var now = moment(new Date());
// var end = moment(post.date);
// var duration = moment.duration(now.diff(end));
// var days = duration.asHours();
// if (parseFloat(days) < 6) {
// jQuery('', {
// class: 'newPost',
// html: 'POST NOVO!'
// }).appendTo(profileInfoDiv);
// }
jQuery('', {
class: 'single-post-content ' + 'post_' + post.id,
}).appendTo(singlePost);
jQuery('', {
class: 'reaction-content d-flex',
html: reactionHtml
}).appendTo(singlePost);
if (post.current_user_emoji && post.current_user_emoji != "0") {
let likeEmoji = jQuery(singlePost).find(" .reaction-content .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);
}
let avatarHolder = jQuery('', {
class: 'single-comment'
}).appendTo('.post_' + post.id);
if (!post.public_post) {
jQuery('.post_' + post.id).parent().addClass('admin_post');
jQuery('', {
html: post.title,
class: 'userName-container'
}).appendTo('.post_' + post.id);
// jQuery('', {
// html: '@meumundomassey',
// class: 'siteName-container'
// }).appendTo('.post_' + post.id);
}
jQuery('', {
html: post.post_content
}).appendTo('.post_' + post.id);
jQuery('', {
class: 'reactionCount',
html: emojiCount | 0
// }).appendTo(jQuery('.reaction-content').last().find('.likes'));
}).insertAfter(jQuery('.post_' + post.id).parent().find('.reaction-content a img'));
// jQuery('', {
// class: 'toggleComment',
// html: 'Responder'
// }).insertAfter(jQuery('.post_' + post.id).parent().find('.reaction-content .reaction-list'));
// let momentDate = moment(post.date);
let agoFormat = moment(post.date).fromNow(true);
// let postDateWithFormat = momentDate.format("DD") + " de " + momentDate.format("MMM") + " às " + momentDate.format("hh:mm");
jQuery('', {
class: 'remaining-time',
html: agoFormat ? 'Há ' + agoFormat : ''
}).appendTo(jQuery('.post_' + post.id).parent().find('.reaction-content .likes'));
jQuery('', {
class: 'likeShow',
id: post.id + '-likeShow',
html: "Quem curtiu?"
}).insertBefore(jQuery('.post_' + post.id).parent().find('.reaction-content > p'));
if (post && post.liked_users) {
var likedUsers = jQuery('', {
style: "display:none",
class: "liked-users",
likedUsers: JSON.stringify(post.liked_users)
}).appendTo(jQuery('.post_' + post.id).parent().find('#' + post.id + '-likeShow'));
post.liked_users.forEach(function (user) {
jQuery('', {
html: user.display_name
}).appendTo(likedUsers);
})
}
jQuery('', {
class: 'new-comment new-comment_' + post.id,
id: 'new-comment_' + post.id,
}).appendTo(singlePost);
if (cmtLength) {
jQuery('', {
class: 'comment-info toggleComment',
id: 'comment_info_' + post.id
}).appendTo(singlePost);
// jQuery('', {
// class: 'd-flex comment_count comment_toggle_' + post.id,
// }).appendTo(singlePost);
jQuery('', {
class: 'comment_count_' + post.id + ' show-more-comments',
html: cmtLength + ' Comentários'
}).appendTo('#comment_info_' + post.id);
}
let commentSection = jQuery('', {
class: 'comment-section'
}).appendTo(singlePost);
Object.entries(post.comments).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('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',
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('', {
class: 'delete-comment',
id: comment[1][0].comment_ID,
html: "X"
}).appendTo(jQuery('div.replySlice_' + comment[1][0]['comment_ID']));
}
// let momentDate = moment(post.comment_date);
// let postDateWithFormat = momentDate.format("DD") + " de " + momentDate.format("MMM") + " às " + momentDate.format("hh:mm");
let agoFormat = moment.utc(comment[1][0].comment_date_gmt).local().fromNow(true);
jQuery('', {
class: 'remaining-time',
html: agoFormat ? 'Há ' + agoFormat : ''
}).appendTo(jQuery('div#comment_reaction_' + comment[1][0].comment_ID));
} else {
jQuery('', {
class: 'comment_holder comment_holder_' + post['id'] + '_id_' + index,
html: ''
}).appendTo(commentSection);
jQuery('', {
class: 'single-comment single_holder_' + post['id'] + '_id_' + index,
html: ''
}).appendTo('div.comment_holder_' + post['id'] + '_id_' + index);
jQuery(' ', {
class: 'comment-avatar',
src: comment[1][0]['avatar_url'],
}).appendTo(jQuery('div.single_holder_' + post['id'] + '_id_' + index));
jQuery('', {
class: 'like-reply liked',
id: 'like_' + comment[1][0].comment_ID,
}).appendTo(jQuery('div.single_holder_' + post['id'] + '_id_' + index));
var commentCountSection = jQuery('', {
class: 'comment-reactions-count d-flex',
id: 'comment_reaction_' + comment[1][0].comment_ID,
}).appendTo(jQuery('div.single_holder_' + post['id'] + '_id_' + index));
if (Number(reactionCount) > 0) {
var usersLikedComment = jQuery('', {
class: 'users-liked-comment',
style: 'display:none'
}).appendTo(commentCountSection);
if (comment[1][0].liked_users && comment[1][0].liked_users.length > 0) {
comment[1][0].liked_users.forEach(function (user) {
jQuery('', {
html: user.display_name
}).appendTo(usersLikedComment);
})
}
}
jQuery('div#comment_reaction_' + comment[1][0].comment_ID).append(reactions);
jQuery('', {
html: 'Responder',
class: 'replyToggle'
}).appendTo(jQuery('div#comment_reaction_' + comment[1][0].comment_ID));
jQuery('', {
html: reactionCount
}).appendTo(jQuery('div#comment_reaction_' + comment[1][0].comment_ID).find('.icon a'));
if (comment[1][0]['liked_users'] && comment[1][0]['liked_users'].length) {
var likedUsers = jQuery('', {
style: "display:none",
class: "liked-users",
likedUsers: JSON.stringify(comment[1][0]['liked_users'])
}).appendTo(jQuery('div#comment_reaction_' + comment[1][0].comment_ID).find('.like'));
comment[1][0]['liked_users'].forEach(function (user) {
jQuery('', {
html: user.display_name
}).appendTo(likedUsers);
})
}
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('', {
class: 'single-comment-data',
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('', {
class: 'delete-comment',
id: comment[1][0].comment_ID,
html: "X"
}).appendTo(jQuery('div.single_holder_' + post['id'] + '_id_' + index));
}
jQuery('', {
class: 'reply-comment-section hide reply_' + comment[1][0].comment_ID,
}).appendTo(jQuery('div.comment_holder_' + post['id'] + '_id_' + index));
jQuery('', {
class: 'new-reply new-reply_' + post['id'] + '_id_' + index
}).appendTo(jQuery('.reply_' + comment[1][0].comment_ID));
jQuery('', {
placeholder: "Responder"
}).appendTo(jQuery('.new-reply_' + post['id'] + '_id_' + index));
jQuery('', {
class: 'attachReplyFile btn btn-gray',
id: "attachReplyFile_" + post['id'],
type: 'file',
}).appendTo('.new-reply_' + post['id'] + '_id_' + index);
jQuery('', {
for : "attachReplyFile_" + post['id'],
html: '',
}).appendTo('.new-reply_' + post['id'] + '_id_' + index);
jQuery('', {
class: 'replyComment',
id: 'replyBtn_' + comment[1][0].comment_ID,
html: ""
}).appendTo(jQuery('.new-reply_' + post['id'] + '_id_' + index));
// let momentDate = moment(comment[1][0].comment_date);
// let postDateWithFormat = momentDate.format("DD") + " de " + momentDate.format("MMM") + " às " + momentDate.format("hh:mm");
let agoFormat = moment.utc(comment[1][0].comment_date_gmt).local().fromNow(true);
jQuery('', {
class: 'remaining-time',
html: agoFormat ? 'Há ' + agoFormat : ''
}).appendTo(commentCountSection);
}
// jQuery('div.comment_holder_' + post['id'] + '_id_' + index).find('.reply-comment-section').hide();
});
jQuery('.new-reply').hide();
jQuery('.new-reply').addClass('hide');
if (jQuery(singlePost).find('.comment_holder').length > 3) {
jQuery('', {
class: 'show-more-comments',
href: 'javascript:void(0);',
html: 'MAIS COMENTÁRIOS'
}).appendTo(jQuery('div.comment_toggle_' + post.id));
jQuery(singlePost).find('.comment_holder').each(function (index, ele) {
if (index > 2) {
jQuery(ele).hide();
}
});
}
jQuery('', {
class: 'comment-text',
type: 'text',
placeholder: 'Deja el primer comentário'
}).appendTo('div.new-comment_' + post.id);
jQuery('', {
class: 'attachFile btn btn-gray',
id: "attachFile_" + post.id,
type: 'file',
}).appendTo(jQuery('div.new-comment_' + post.id));
jQuery('', {
for : "attachFile_" + post.id,
html: '',
}).appendTo(jQuery('.new-comment_' + post.id));
jQuery('', {
class: 'add-new-comment btn btn-gray',
id: post.id,
type: 'button',
html: ''
}).appendTo('div.new-comment_' + post.id);
});
self.replyOptomize();
jQuery('.source').last().hide();
jQuery('#end-of-posts').remove();
jQuery('', {
id: 'end-of-posts',
class: 'timeline-loader'
}).appendTo('.post-list');
// jQuery(' ', {
// src: location.origin + '/wp-content/themes/sky-child/assets/images/common/timeline-loader.gif',
// }).appendTo('#end-of-posts');
self.timeLineLoader('hide');
self.postCallFlag = true;
// if (self.newPublishedPostId) {
// document.querySelector('.post_' + self.newPublishedPostId).parentElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
// self.newPublishedPostId = '';
// }
},
replyOptomize: function () {
jQuery('div.comment_holder').find('div.replyHolder').each(function (position, element) {
if (jQuery(element).find('div.replySlice').length > 2) {
let replyHolderID = jQuery(element).attr('id');
jQuery('', {
class: 'show-more-replies',
href: 'javascript:void(0);',
html: 'Ver mais respostas'
}).appendTo(jQuery('div#' + replyHolderID));
jQuery(element).find('div.replySlice').each(function (index, ele) {
if (index > 1 && jQuery(ele).attr('class') != 'show-more-replies') {
jQuery(ele).hide();
}
});
}
});
},
};
return self;
}();
jQuery(document).ready(function () {
agco.timeLine.ready();
});
agco.gallery = function () {
var self = {
ready: function () {
self.load();
},
load: function () {
self.eventHandler();
if (jQuery('.single-photos').length) {
self.loadSingleGalaryFunction();
}
if (jQuery('.post-type-archive-photos').length) {
self.filterPhotoTitle();
}
if (location.href.includes('/calendar')) {
self.checkParam();
}
},
eventHandler: function () {
jQuery(document).on('click', '#month-filter-btn', self.filterPhoto);
},
checkParam: function () {
var pageURLParam = new URLSearchParams(window.location.search);
if (!pageURLParam.has('month') || !pageURLParam.get('month')) {
return false;
}
var value = pageURLParam.get('month');
var key = moment(value + '-30').format('M/D/YYYY');
},
filterPhoto: function (e) {
var data = jQuery('#month-filter').val();
if (!data) {
e.preventDefault();
return false;
}
},
filterPhotoTitle: function () {
var pageURLParam = new URLSearchParams(window.location.search);
if (pageURLParam.has('month_filter') && pageURLParam.get('month_filter')) {
var title = jQuery('#filter').html();
if (!title) {
return false;
}
title = title.split('/')[0];
jQuery('#filter').html(title);
jQuery('.recent-gallery-details').hide();
}
},
loadSingleGalaryFunction: function () {
self.popupView();
},
popupView: function () {
if (lightbox) {
lightbox.option({
'resizeDuration': 200,
'wrapAround': true
})
} else {
setTimeout(() => {
self.popupView();
}, 100);
}
},
toggleView: function () {
},
singleView: function () {
jQuery('', {
class: 'single-view-date',
html: 'Date '
});
jQuery('', {
class: 'single-view-title',
html: 'Title'
});
jQuery('', {
class: 'single-view-description',
html: 'Description'
});
jQuery('', {
class: 'like',
html: 'like',
});
var imageHolder = jQuery('', {
class: 'image-holder',
});
array.forEach(function (element) {
jQuery(' ', {
class: 'image',
alt: element,
src: ''
}).appendTo(imageHolder);
});
},
archiveView: function () {
},
archiveListGenerator: function () {
var array = [];
array.forEach(function (element) {
var card = jQuery('', {
class: 'card',
id: element.id + '-card',
});
var cardHeader = jQuery('', {
class: 'image-holder',
html: ' '
});
var cardContent = jQuery('', {
class: 'card-content'
});
jQuery('', {
class: 'date',
html: 'date'
}).appendTo(cardContent);
jQuery('', {
class: 'title',
html: 'title'
}).appendTo(cardContent);
jQuery('', {
class: 'like',
html: 'like',
id: element.id + '-like',
}).appendTo(cardContent);
jQuery(cardContent).appendTo(card);
jQuery(cardHeader).appendTo(card);
});
var container = jQuery('#pagination-' + name);
container.pagination({
dataSource: 'https://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?',
locator: 'items',
totalNumber: 10,
pageSize: 1,
showPageNumbers: true,
showPrevious: true,
showNext: true,
showNavigator: true,
showFirstOnEllipsisShow: true,
showLastOnEllipsisShow: true,
ajax: {
beforeSend: function () {
container.prev().html('Loading data from flickr.com ...');
}
},
callback: function (response, pagination) {
var dataHtml = '';
jQuery.each(response, function (index, item) {
dataHtml += '- ' + item.title + '
';
});
dataHtml += ' ';
container.prev().html(dataHtml);
}
});
},
};
return self;
}();
jQuery(document).ready(function () {
agco.gallery.ready();
});
agco.badges = function () {
var self = {
flag: false,
currentPopUpID: '',
modelID: '',
endpoints: {
'seloes': 'v1/selos/list'
},
load: function () {
jQuery(document).ready(function () {
self.ready();
});
},
ready: function () {
if (jQuery('.post-type-archive-selos').length) {
self.applySlick();
self.eventHandlers();
// self.selosHoverEvents();
}
if (jQuery('#gallery-id').length) {
self.getSeloes();
}
},
eventHandlers: function () {
jQuery(document).on('click', 'div.modal-body .close', self.closePopUp);
jQuery(document).on('click', 'div.featured-image > img', self.preventDefault);
jQuery(document).on('click', 'a.selos-link', self.openAsPopUp);
},
closePopUp: function () {
jQuery(self.currentPopUpID).modal('hide');
},
openAsPopUp: function () {
self.flag = true;
var seloesID = jQuery(this).attr('href');
self.currentPopUpID = seloesID;
jQuery(seloesID).bind('click', self.clickclose);
jQuery(seloesID).modal('show');
},
applySlick: function () {
if (jQuery() && jQuery().slick && jQuery('.selos-rows').length) {
jQuery('.selos-rows').slick({
dots: true,
arrows: true,
infinite: false,
centerMode: false,
slidesToShow: 3,
slidesToScroll: 1,
variableWidth: true
});
} else {
setTimeout(function () {
self.applySlick();
}, 200);
}
},
getSeloes: function () {
var endpoint = self.endpoints.seloes;
var cpf = agco.helper.getCpf()
var data = {
cpf: cpf
}
agco.helper.loader('show');
agco.helper.appApiRequest(endpoint, 'GET', data, true, self.getSeloesSuccess, self.getSeloesError);
},
getSeloesSuccess: function (success) {
agco.helper.loader('hide');
// console.log(success)
if (success.code != "get_selos_success") {
return false;
}
var list = success.message.all_selos;
var userOwned = success.message.selos;
var userList = [];
var count = 0;
var parentElement = jQuery('#gallery-id').siblings('.gallery-contents').find('ul');
if (!userOwned) {
jQuery(parentElement).find('.count').html(count ? count : 0);
return false;
}
var customOwned = [];
for (const [key, value] of Object.entries(userOwned)) {
customOwned.push(value);
}
count = customOwned.length;
list.forEach(function (element) {
if (customOwned.indexOf(element.ID.toString()) >= 0) {
userList.push(element);
}
});
jQuery('#gallery-id').siblings('.gallery-contents').find('li').remove();
jQuery(parentElement).find('.count').html(count ? count : 0);
userList.forEach(function (element) {
var image = jQuery(' ', {
src: element.image_url,
alt: element.name,
});
var list = jQuery('', {
html: image,
});
jQuery(list).appendTo(parentElement);
});
},
getSeloesError: function (error) {
agco.helper.loader('hide');
// console.log(error)
},
selosHoverEvents: function () {
var timer;
jQuery('div.selos-card').on({
'click': function () {
var that = this;
setTimeout(function () {
if (jQuery(".modal .in").length === 0) {
self.flag = true;
var seloesID = jQuery(that).parent().attr('href');
jQuery(seloesID).bind('click', self.clickclose);
jQuery(seloesID).modal('show');
}
}, 200);
},
'mouseout': function () {
if (timer)
clearTimeout(timer);
}
});
},
clickclose: function () {
if (self.flag) {
self.flag = false;
}
},
preventDefault: function (e) {
self.flag = false;
e.preventDefault();
},
}
return self;
}();
jQuery(document).ready(function () {
agco.badges.ready();
});
agco.envioNF = function () {
var self = {
fileFlag: false,
post: '',
endpoints: {
'xmlInvoiceUpload': 'v1/adm/register/invoice'
},
currentBarCodeMask: '',
ready: function () {
if (jQuery('.page-template-page-envio-de-notas-xml').length) {
self.eventHandlers();
self.applyMechanicSelect2();
}
},
eventHandlers: function () {
// jQuery(document).on('click', '.attach-xml', self.triggerFilePicker);
jQuery(document).on('click', '#billPay', self.submitInvoice);
jQuery(document).on('change', '#attach-xml', self.updateSelected);
jQuery(document).on('click', '#remove-xml', self.removeSelected);
},
applyMechanicSelect2: function () {
if (jQuery() && jQuery().select2) {
jQuery("#cpf_mecanico").select2({
minimumInputLength: 0,
language: "pt-BR",
ajax: {
url: agco.helper.baseUrl + 'v1/adm/user/filter/mecanica/',
dataType: 'json',
type: 'GET',
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,
};
return dataObject;
},
processResults: function (data, params) {
params.page = params.page || 1;
var arr = []
if (data.length) {
jQuery.each(data, function (index, value) {
if (value.value) {
arr.push({
id: value.value,
text: value["concat(CPF,'-',Nome)"]
});
}
});
}
return {
results: arr,
};
},
},
placeholder: 'Mecánico',
});
} else {
setTimeout(self.applyMechanicSelect2, 300);
}
},
removeSelected: function () {
jQuery('#attach-xml').val('');
self.fileFlag = false;
jQuery('.attached-file-name').html('');
jQuery('#remove-xml').attr('hidden', true);
},
triggerFilePicker: function () {
jQuery('#attach-xml').click();
},
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);
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('');
jQuery('#remove-xml').attr('hidden', true);
} 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('#remove-xml').attr('hidden', true);
jQuery('.attached-file-name').html('');
}
},
getImageFile: function (imageBase64) {
return new Promise(function (resolve, reject) {
var base64Blob = agco.helper.base64toBlob(imageBase64, "text/xml");
resolve(base64Blob);
});
},
submitInvoice: function () {
var clientCPF = jQuery('.client-cpf input').val();
var mechanic = jQuery('#cpf_mecanico').val();
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);
if (mechanic) {
data.append('cpf_mecanico', mechanic);
}
agco.helper.appApiRequest(endpoint, 'POST', data, true, self.submitInvoiceSuccess, self.submitInvoiceError);
// _success
},
submitInvoiceSuccess: function (success) {
agco.helper.loader('hide');
if (success == 1) {
agco.helper.popUp('Éxito', 'FACTURA TRIBUTARIA ENVIADA EXITOSAMENTE.');
return false;
}
agco.helper.popUp('Error', success);
},
submitInvoiceError: function (error) {
agco.helper.loader('hide');
//agco.helper.popUp('Error', 'Erro ao enviar o arquivo. Entre em contato com o suporte');
agco.helper.popUp('Error', error.responseText);
},
updateIntimation: function (message) {
jQuery('.updateIntimation').remove();
if (message) {
jQuery('', {
html: message,
class: 'updateIntimation'
}).appendTo(jQuery('.attach-xml').parent().parent());
}
},
}
return self;
}();
jQuery(document).ready(function () {
agco.envioNF.ready();
});
agco.resumo = function () {
var self = {
fileFlag: false,
post: '',
endpoints: {
'resumoDealer': 'v1/adm/report/dealer/',
'resumoSeller': 'v1/adm/report/seller/',
},
columns: [
{
"data": "display_name",
"title": "NOME"
},
{
"data": "cpf",
"title": "CPF"
},
{
"data": "cnpj",
"title": "CNPJ"
},
{
"data": "cadastro_qtd",
"title": "cant. registrados (total)",
},
{
"data": "cadastro_valido_qtd",
"title": "cant. registrados (activos)",
},
],
concessionariaColumn: [
{
"data": "qtd_cadastro",
"title": "cant. registrados (total)"
},
{
"data": "qtd_accept",
"title": "cant. registrados (activos)"
},
{
"data": "qtd_invoice",
"title": "cant. de facturas registradas (total)"
},
/*{
"data": "cnpj",
"title": "CNPJ"
},*/
],
ready: function () {
if (jQuery('.page-template-page-resumo').length) {
self.eventHandlers();
self.getConsistanareo();
}
},
eventHandlers: function () {
jQuery(document).on('click', '#concessionaria-tab', self.openConsistanareo);
jQuery(document).on('click', '#salesperson-tab', self.openVendedor);
jQuery(document).on('click', '.filter-by-date', self.searchByDate);
},
searchByDate: function () {
if (jQuery('#concessionaria-tab').hasClass('active')) {
var start = jQuery('#concessionaria-start-date').val();
var end = jQuery('#concessionaria-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.getConsistanareo(data);
} else {
var start = jQuery('#sales-start-date').val();
var end = jQuery('#sales-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.getVendedor(data);
}
},
openConsistanareo: function () {
self.getConsistanareo({});
},
openVendedor: function () {
self.getVendedor({});
},
getConsistanareo: function (filter) {
var endpoint = self.endpoints.resumoDealer;
agco.helper.loader('show');
jQuery('.admin-page-concessionaria-abstract-detail table').html('');
agco.helper.appApiRequest(endpoint, 'POST', filter, true, self.getConsistanareoSuccess, self.getConsistanareoError);
},
getConsistanareoSuccess: function (success) {
agco.helper.loader('hide');
// if (!success || success.code != "report_by_dealer_success") {
// return false;
// }
var list = success.data ? success.data : [];
agco.helper.loadDataTableWithdata(list, self.concessionariaColumn, '.admin-page-concessionaria-abstract-detail table');
},
getConsistanareoError: function (error) {
agco.helper.loader('hide');
},
getVendedor: function (filter) {
var endpoint = self.endpoints.resumoSeller;
agco.helper.loader('show');
jQuery('.admin-page-salesperson-abstract-detail table').html('');
agco.helper.appApiRequest(endpoint, 'POST', filter, true, self.getVendedorSuccess, self.getVendedorError);
},
getVendedorSuccess: function (success) {
agco.helper.loader('hide');
// if (!success || success.code != "report_by_seller_success") {
// return false;
// }
var list = success.data ? success.data : [];
agco.helper.loadDataTableWithdata(list, self.columns, '.admin-page-salesperson-abstract-detail table');
},
getVendedorError: function (error) {
agco.helper.loader('hide');
},
}
return self;
}();
jQuery(document).ready(function () {
agco.resumo.ready();
});
agco.dePara = function () {
var self = {
fileFlag: false,
isMaqunia: false,
isEdit: false,
post: '',
selectedData: {},
backupAGCONum: '',
endpoints: {
'getLubList': 'v1/adm/report/product',
'addNewLub': "v1/adm/product",
'update': "v1/adm/product",
'delete': "v1/adm/product",
'addImportProduct': "v1/adm/product/new/import/",
'addImportLub': "v1/adm/product/new/import/lub",
'productListForAddNew': 'v1/adm/product/list/',
'downloadExcelSample': 'v1/adm/report/product/new/bulk/'
},
LubColumns: [
{
"data": "item",
"title": "ITEM"
},
{
"data": "part_number_agco",
"title": "PART NUMBER AGCO"
},
{
"data": "part_number_service_station",
"title": "PART NUMBER ESTAÇÃO DE SERVIÇO"
},
{
"data": "part_number_type",
"title": "PART NUMBER CONCESSIONÁRIA"
},
{
"data": "",
"title": "",
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 DESTINATARION. 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();
}); |