PageSourceSearch

https://prod.camarabaq.org.co/wp-content/themes/nx/inc/assets/js/login.js?ver=1790272874

js camarabaq.org.co collected 2026-09-24 18:42:06 UTC 14,432 bytes, 394 lines download raw bytes

1$(document).ajaxSend(function (event, jqXHR, settings) {
2  // Remueve el parámetro `_tutor_nonce` de la URL
3  settings.url = settings.url.replace(/&?_tutor_nonce=[^&]*/g, '');
4});
5$(document).ready(function () {
6  loginForm = $('.js-login-form');
7  const rootUrl = window.location.protocol + "//" + window.location.hostname;
8  const api_path = 'https://anwt6pvh8s.us-east-1.awsapprunner.com/authentication';
9  $("#phone").intlTelInput({
10    initialCountry: "CO", // Establecer Colombia como país inicial
11    separateDialCode: true, // Mostrar el código de país en un elemento separado
12    nationalMode: true,
13    utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js" // Utilidades adicionales
14  });
15  $("#phoneregister").intlTelInput({
16    initialCountry: "CO", // Establecer Colombia como país inicial
17    separateDialCode: true, // Mostrar el código de país en un elemento separado
18    nationalMode: true,
19    utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js" // Utilidades adicionales
20  });
21  $('.js-login-form').submit(function (e) {
22    e.preventDefault(); // Evita que el formulario se envíe normalmente
23    $('.icon-send').addClass('d-none');
24    $('.icon-loader').removeClass('d-none');
25    var $form = $(this);
26    var input = $form.find("#phone");
27    var countryCode = input.intlTelInput("getSelectedCountryData").dialCode;
28    // Obtener los datos del formulario
29    var email = $form.find('#email').val();
30    var phone = $form.find('#phone').val();
31    var formData = {};
32    if (email.trim() !== '') {
33      // Si se proporciona un email, incluirlo en el formData y omitir el teléfono y el código de país
34      $(".js-client-login-username").html(email);
35      formData.strategy = "email"
36      formData.email = email;
37      $(".js-email-login").val(email);
38    } else {
39      formData.strategy = "sms"
40      // Si no se proporciona un email, incluir el teléfono y el código de país en el formData
41      formData.phone = phone;
42      formData.phone_country_code = countryCode;
43      $(".js-country-login").val(countryCode);
44      $(".js-phone-login").val(phone);
45      $(".js-client-login-username").html(phone);
46    }
47    if (email.trim() !== '' || phone.trim() !== '') {
48      $.ajax({
49        type: 'POST',
50        url: api_path,
51        data: JSON.stringify(formData),
52        contentType: 'application/json',
53        success: function (response) {
54          // Manejar la respuesta del servidor
55          success_form();
56          $('.icon-loader').addClass('d-none');
57          $('.icon-send').removeClass('d-none');
58          // Puedes mostrar un mensaje de éxito o realizar otras acciones aquí
59        },
60        error: function (xhr, status, error) {
61          // Manejar errores de la solicitud
62          var errorMessage = xhr.responseJSON ? xhr.responseJSON.message : xhr.responseText;
63          Swal.fire({
64            icon: 'error',
65            title: '¡Algo salio mal!',
66            text: errorMessage
67          }).then((result) => {
68            if (result.isConfirmed) {
69              window.location.href = rootUrl;
70            }
71          });
72          //console.error(xhr.responseText.body);
73          //console.log("Ocurrio un error: " + xhr.responseText)
74          $('.icon-loader').addClass('d-none');
75          $('.icon-send').removeClass('d-none');
76        }
77      });
78    } else {
79      $(".js-error-message").html("Campo Requerido");
80      $('.icon-loader').addClass('d-none');
81      $('.icon-send').removeClass('d-none');
82    }
83  });
84  $('.js-step2-form').submit(function (e) {
85    e.preventDefault();
86    $('.icon-send').addClass('d-none');
87    $('.icon-loader').removeClass('d-none');
88    var email = $('.js-email-login').val();
89    var phone = $('.js-phone-login').val();
90    var countryCode = $(".js-country-login").val();
91    var formData = {};
92    var otp = $(".otp-input").map(function () {
93      return $(this).val();
94    }).get().join('');
95    if (validarOTP(otp)) {
96      if (email.trim() !== '') {
97        formData.strategy = "email"
98        formData.email = email;
99        formData.token_login_email = otp;
100      } else {
101        formData.strategy = "sms"
102        formData.phone = phone;
103        formData.phone_country_code = countryCode;
104        formData.token_login_phone = otp;
105      }
106      $('.icon-loader').addClass('d-none');
107      $('.icon-send').removeClass('d-none');
108    } else {
109      $(".js-error-message").html("Campo Requerido");
110      return;
111    }
112
113    //console.log(formData);
114    if (email.trim() !== '' || phone.trim() !== '') {
115      try {
116        $.ajax({
117          type: 'POST',
118          url: api_path,
119          data: JSON.stringify(formData),
120          contentType: 'application/json',
121          success: function (response) {
122            // Manejar la respuesta del servidor
123            success_form();
124            //console.log(response);
125            jsonResponse = (response.accessToken);
126            var accessToken = response.accessToken;
127            localStorage.setItem('jwt', accessToken);
128            var email = response.user.email;
129            var firstName = response.user.first_name;
130            var lastName = response.user.last_name;
131            var userStatus = response.user.status;
132            var currentCompanyId = response.user.current_company_id;
133            var id = response.user.id;
134            var phone = response.user.phone;
135            var status = response.user.access_status;
136            var userData = {
137              email,
138              firstName,
139              lastName,
140              userStatus,
141              currentCompanyId,
142              id,
143              phone,
144              status
145            };
146            var userDataJson = JSON.stringify(userData);
147            localStorage.setItem('userData', userDataJson);
148            if (userData) {
149              getCompanies(userData);
150            }
151            $('.btn-close-modal').click();
152            if (response.user.status === 'active') {
153              Swal.fire({
154                icon: 'success',
155                title: '¡Bienvenido/a! ' + firstName + ' a nuestro Punto Empresario Virtual',
156                text: 'Ahora podrás disfrutar de contenidos, eventos y proyectos pensados para ti.'
157              }).then((result) => {
158                if (result.isConfirmed) {
159                  if (userData) {
160                    getCompanies(userData);
161                  }
162                  login();
163                  // window.location.reload();
164                }
165              });
166            } else {
167              Swal.fire({
168                icon: 'success',
169                title: '¡Bienvenido!',
170                text: 'No sabemos aún mucho de ti, déjanos conocerte para ofrecerte contenido, eventos y proyectos pensados para ti y tu negocio.'
171              }).then((result) => {
172                if (result.isConfirmed) {
173                  login();
174                  // Redirección a /pv/perfil deshabilitada temporalmente
175                  // window.location.href = "https://www.camarabaq.org.co/pv/perfil";
176                }
177              });
178            }
179          },
180          error: function (xhr, status, error) {
181            // Manejar errores de la solicitud
182            //console.log('error algo ha salido mal')
183            Swal.fire({
184              icon: 'error',
185              title: 'Lo sentimos',
186              text: 'Algo ha salido mal, intente nuevamente'
187            }).then((result) => {
188              if (result.isConfirmed) {
189                window.location.reload();
190              }
191            });
192
193            errorResponse = JSON.parse(xhr.responseJSON);
194            //console.error(xhr);
195            //console.log(errorResponse.message)
196            // Puedes mostrar un mensaje de error o realizar otras acciones aquí
197          }
198        });
199      } catch (error) {
200        //console.error('Ha ocurrido un error inesperado: ', error);
201      }
202    } else {
203      $(".js-error-message").html("Campo Requerido");
204    }
205  });
206  $('.js-resend-code').on('click', function (e) {
207    e.preventDefault();
208    var email = $('.js-email-login').val();
209    var phone = $('.js-phone-login').val();
210    var countryCode = $(".js-country-login").val();
211    var formData = {};
212    if (email.trim() !== '') {
213      formData.strategy = "email"
214      formData.email = email;
215    } else {
216      formData.strategy = "sms"
217      formData.phone = phone;
218      formData.phone_country_code = countryCode;
219    }
220    //console.log(formData);
221    if (email.trim() !== '' || phone.trim() !== '') {
222      try {
223        $.ajax({
224          type: 'POST',
225          url: api_path,
226          data: JSON.stringify(formData),
227          contentType: 'application/json',
228          success: function (response) {
229            // Manejar la respuesta del servidor
230            success_form();
231            //console.log(response);
232            Swal.fire({
233              icon: 'success',
234              title: '¡Éxito!',
235              text: 'Se ha enviado un nuevo código'
236            })
237          },
238          error: function (xhr, status, error) {
239            // Manejar errores de la solicitud
240            errorResponse = JSON.parse(xhr.responseJSON);
241            //console.error(xhr);
242            //console.log(errorResponse.message)
243            $(".js-error-message").html(errorResponse.message);
244            Swal.fire({
245              icon: 'error',
246              title: '¡Error!',
247              text: 'Algo ha salido mal, inténtelo nuevamente'
248            })
249            // Puedes mostrar un mensaje de error o realizar otras acciones aquí
250          }
251        });
252      } catch (error) {
253        //console.error('Ha ocurrido un error inesperado: ', error);
254      }
255    } else {
256      $(".js-error-message").html("Campo Requerido");
257    }
258  });
259});
260function success_form() {
261  $('.js-login-form').hide();
262  $('#radio-container').hide();
263  $('#radio-container').removeClass("d-flex");
264  $('.menu-info').addClass("d-none");
265  $('.js-step2-form').addClass("d-flex");
266  $('.js-step2-form').removeClass("d-none");
267  $('.btn-back-modal').removeClass("d-none");
268  $('.icon-loader').addClass('d-none');
269  $('.icon-send').removeClass('d-none');
270}
271function back_form() {
272  $('.js-login-form').show();
273  $('#radio-container').show();
274  $('#radio-container').addClass("d-flex");
275  $('.menu-info').addClass("d-none");
276  $('.js-step2-form').addClass("d-flex");
277  $('.js-step2-form').addClass("d-none");
278  $('.btn-back-modal').addClass("d-none");
279  $('.icon-loader').addClass('d-none');
280  $('.icon-send').removeClass('d-none');
281}
282document.addEventListener('DOMContentLoaded', function (event) {
283  var emailInput = document.getElementById('js-email');
284  var phoneInput = document.getElementById('js-phone');
285  var radioEmail = document.getElementById('radioEmail');
286  var radioPhone = document.getElementById('radioPhone');
287
288  radioEmail.addEventListener('input', function () {
289    if (this.checked) {
290      emailInput.style.display = 'block';
291      phoneInput.style.display = 'none';
292      limpiar_inputs(loginForm);
293    }
294  });
295  radioPhone.addEventListener('input', function () {
296    if (this.checked) {
297      limpiar_inputs(loginForm);
298      emailInput.style.display = 'none';
299      phoneInput.style.display = 'block';
300    }
301  });
302  // Mostrar el input correspondiente al radio button seleccionado al cargar la página
303  if (radioEmail.checked) {
304    emailInput.style.display = 'block';
305    phoneInput.style.display = 'none';
306  } else if (radioPhone.checked) {
307    emailInput.style.display = 'none';
308    phoneInput.style.display = 'block';
309  }
310});
311$(document).ready(function () {
312  $(".btn-back-modal").on('click', function () {
313    back_form();
314    limpiar_inputs(loginForm);
315  });
316  // Enfocar el primer campo de entrada al cargar la página
317  $("#otp-input-1").focus();
318  $(".otp-input").on("click", function (e) {
319    $(this).focus().select(); // Enfocar el siguiente campo de entrada
320  });
321
322  $(".otp-input").on('input', function (e) {
323    var $this = $(this);
324    var value = $this.val();
325    var $inputs = $(".otp-input"); // Selecciona todos los inputs con la clase otp-input
326    var currentIndex = $inputs.index(this); // Obtén el índice del input actual
327
328    // Moverse al siguiente input si se ingresó un dígito válido
329    if (value.match(/^[0-9]$/) && value.length === 1) {
330      if (currentIndex < $inputs.length - 1) {
331        $inputs.eq(currentIndex + 1).focus().select(); // Enfoca el siguiente input en la lista
332      }
333    }
334    // Verifica si se completaron los 4 dígitos
335    if ($("#otp-container .otp-input").filter(function () { return this.value.length === 1; }).length === 4) {
336      updateSubmitButton();
337    }
338  });
339  // Manejo específico de "backspace"
340  $(".otp-input").on('keydown', function (e) {
341    var $this = $(this);
342    var $inputs = $(".otp-input");
343    var currentIndex = $inputs.index(this);
344
345    // Detecta "backspace" cuando el input está vacío
346    if (e.key === 'Backspace' && $this.val() === '') {
347      if (currentIndex > 0) {
348        $inputs.eq(currentIndex - 1).focus().select(); // Enfoca el input anterior en la lista
349      }
350    }
351  });
352  function updateSubmitButton() {
353    var otp = $(".otp-input").map(function () {
354      return $(this).val();
355    }).get().join('');
356    if (validarOTP(otp)) {
357      $('.js-submit-step2').removeClass('disabled');
358    } else {
359      $('.js-submit-step2').addClass('disabled');
360    }
361  }
362
363});
364function limpiar_inputs(form) {
365  form.find('input[type=text], input[type=password], input[type=email], input[type=tel], input[type=number], textarea').val('');
366  $('.js-email-login').val('');
367  $('.js-phone-login').val('');
368  $('.js-country-login').val('');
369}
370
371function validarOTP(otp) {
372  var regex = /^\d{4}$/;
373  return regex.test(otp);
374}
375function login() {
376  //console.log("login exitoso")
377  crearSesion();
378  let userData = JSON.parse(localStorage.getItem('userData'));
379  if (userData && userData.firstName.trim() !== '') {
380    let name = userData.firstName.split(" ")[0];
381    $('.login-data').text(`Hola ${name}`);
382    $('.link-login').attr("href", 'https://www.camarabaq.org.co/pv/perfil/');
383    $('.link-login').attr("data-toggle", '');
384    $('.custom-selector').removeClass('d-none');
385    $('.link-login').attr("data-target", '');
386    $('.link-logout').removeClass('d-none');
387  }
388  if (userData) {
389    getCompanies(userData);
390    createCompaniesSelector();
391  }
392  window.location.reload();
393}
394

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.