const url = document.URL
const isDealers = url.split('/')[url.split('/').length - 1] === 'dealers'
const validateInputs = () => {
const pattern = '^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*_=+-]).{8,50}$'
const emailPattern = '^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,}$'
let isValid = true
let inputs = [
{ id: 'password', type: 'value', validation: 'pattern' },
{ id: 'email', type: 'value', validation: 'email' },
{ id: 'accept_terms', type: 'checked', validation: 'type' },
]
if (isDealers) {
inputs.push({ id: 'dealers', type: 'value', validation: 'not_empty' })
}
for (const input of inputs) {
try {
let x = document.forms['register-form'][input.id][input.type]
if (input.validation === 'type') {
if (input.type === 'value') {
if (x.length <= 0) {
isValid = false
break
}
} else {
if (!x) {
isValid = false
break
}
}
} else if (input.validation === 'not_empty') {
if (!x) {
const errorSection = document.getElementById('errorSection')
errorSection.innerHTML = `
Por favor, indicanos donde nos conociste
`
isValid = false
break
}
} else if (input.validation === 'pattern') {
if (x.includes('x')) {
const intro = document.getElementById('1min')
intro.style.backgroundColor = '#25B562'
} else {
const intro = document.getElementById('1min')
intro.style.backgroundColor = '#9CA09D'
}
if (new RegExp('(?=.*[a-z])').test(x?.trim())) {
const intro = document.getElementById('1min')
intro.style.backgroundColor = '#25B562'
} else {
const intro = document.getElementById('1min')
intro.style.backgroundColor = '#9CA09D'
}
if (new RegExp('(?=.*[A-Z])').test(x?.trim())) {
const intro = document.getElementById('1may')
intro.style.backgroundColor = '#25b562'
} else {
const intro = document.getElementById('1may')
intro.style.backgroundColor = '#9CA09D'
}
if (new RegExp('(?=.*[0-9])').test(x?.trim())) {
const intro = document.getElementById('1num')
intro.style.backgroundColor = '#25b562'
} else {
const intro = document.getElementById('1num')
intro.style.backgroundColor = '#9CA09D'
}
if (new RegExp('(?=.*[!@#$%^&*_=+-])').test(x?.trim())) {
const intro = document.getElementById('1especial')
intro.style.backgroundColor = '#25b562'
} else {
const intro = document.getElementById('1especial')
intro.style.backgroundColor = '#9CA09D'
}
if (new RegExp('.{8,50}').test(x?.trim())) {
const intro = document.getElementById('8caract')
intro.style.backgroundColor = '#25b562'
} else {
const intro = document.getElementById('8caract')
intro.style.backgroundColor = '#9CA09D'
}
if (!new RegExp(pattern).test(x?.trim())) {
isValid = false
break
}
} else if (input.validation === 'email') {
if (!/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(x?.trim())) {
const errorSection = document.getElementById('errorSection')
errorSection.innerHTML = `
Por favor revisa de ingresar un correo válido
`
isValid = false
break
} else {
const errorSection = document.getElementById('errorSection')
errorSection.innerHTML = ''
}
}
} catch (error) {
console.log(error)
}
}
document.getElementById('submit').disabled = !isValid;
}
const togglePassword = document.querySelector('#togglePassword');
const password = document.querySelector('#password');
togglePassword.addEventListener('click', function () {
const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
password.setAttribute('type', type);
togglePassword
.querySelector("svg > path:nth-of-type(1)")
.classList.toggle("invisible");
togglePassword
.querySelector("svg > path:nth-of-type(2)")
.classList.toggle("invisible");
});
// Ends of new scrpts
const urls = {
local: {
COGNITO_CLIENT_ID: '4ba23rg7vo0qmnf8poj1f2hfpk',
//COGNITO_CLIENT_ID: '3tk7vq4nv80vo0lu07osrubb62',
SAVE_PRE_SUBSCRIPTION: 'http://localhost:3030/api/external/presubscription/data',
REDIRECT_CONFIRM_CODE: (type, username, userCredential) => `http://localhost:8005/select_frist_plan/?type=${type}&username=${username}&credential=${userCredential}`,
COGNITO: 'https://cognito-idp.us-west-2.amazonaws.com/',
LOGIN: 'http://localhost:8005/login'
},
dev: {
COGNITO_CLIENT_ID: '4ba23rg7vo0qmnf8poj1f2hfpk',
SAVE_PRE_SUBSCRIPTION: 'https://api.dev.nonprodmiwally.com/crmb/api/external/presubscription/data',
REDIRECT_CONFIRM_CODE: (type, username, userCredential) => `https://cuenta.dev.nonprodmiwally.com/select_frist_plan/?type=${type}&username=${username}&credential=${userCredential}`,
COGNITO: 'https://cognito-idp.us-east-1.amazonaws.com/',
LOGIN: 'https://cuenta.dev.nonprodmiwally.com/login'
},
qas: {
COGNITO_CLIENT_ID: '5n9gou97a5mmp51ikqhpb0c5f6',
SAVE_PRE_SUBSCRIPTION: 'https://api.qas.nonprodmiwally.com/crmb/api/external/presubscription/data',
REDIRECT_CONFIRM_CODE: (type, username, userCredential) => `https://cuenta.qas.nonprodmiwally.com/select_frist_plan/?type=${type}&username=${username}&credential=${userCredential}`,
COGNITO: 'https://cognito-idp.us-east-1.amazonaws.com/',
LOGIN: 'https://cuenta.qas.nonprodmiwally.com/login'
},
prd: {
COGNITO_CLIENT_ID: '70gk8q3rj71a35f6v58og8f7po',
SAVE_PRE_SUBSCRIPTION: 'https://api.prd.miwally.com/crmb/api/external/presubscription/data',
REDIRECT_CONFIRM_CODE: (type, username, userCredential) => `https://cuenta.miwally.com/select_frist_plan/?type=${type}&username=${username}&credential=${userCredential}`,
COGNITO: 'https://cognito-idp.us-west-2.amazonaws.com/',
LOGIN: 'https://cuenta.miwally.com/'
}
}
// const currentEnvironment = urls.qas
const currentEnvironment = urls.prd
const errorCodes = {
CodeDeliveryFailureException:
'No se pudo mandar el código de autenticación',
InvalidPasswordException:
'La contraseña debería tener mínimo 8 caracteres, una mayúscula y minúscula',
TooManyRequestsException: 'Usted ha realizado demasiadas peticiones',
UsernameExistsException: 'Ya existe una cuenta con ese correo',
InvalidParameterException:
'Asegurese que el correo y clave no contienen espacios en blanco',
default: 'Ocurrio un error, por favor vuelve a intentar',
UsernameExistsException: 'El email ya se encuentra registrado'
}
const hubspotCodes = {
CULQI: 'CULQI CULQI FT - ' ,
DEFAULT: 'DEFAULT VD FT - ',
}
const hubspotPipelines = {
CULQI: '20116115' ,
DEFAULT: '13451065',
}
const dealStage = {
CULQI: '48855126',
DEFAULT: '37708717',
}
const catalogPlans = {
DEFAULT: 'DEFAULT',
COMERCIAL: 'COMERCIAL',
CULQI: 'CULQI',
DEALERS: 'DEALERS',
}
let catalogTypeParam = ''
let showLocation = false
let savedPassword = ''
const passwordSpace = document.getElementById('password')
const encryptText = (value) => {
const key = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ];
const text = value;
const textBytes = aesjs.utils.utf8.toBytes(text);
const aesCtr = new aesjs.ModeOfOperation.ctr(key, new aesjs.Counter(5));
const encryptedBytes = aesCtr.encrypt(textBytes);
const encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
return encryptedHex
}
passwordSpace.addEventListener("keyup",e=>{
let string = e.target.value;
e.target.value = string.replace(/ /g, "")
})
let enlaceIngresar = document.getElementById('ingresar')
enlaceIngresar.setAttribute("href", currentEnvironment.LOGIN)
const getRegistrationData = (event) => {
event.preventDefault()
document.getElementById('submit').disabled = true;
const formInputs = Array.from(document.querySelectorAll('input'))
.reduce((acc, input) => {
return {
...acc,
[input.id]: input.value
}
}, {})
let formSelects = {}
if(isDealers){
formSelects = Array.from(document.querySelectorAll('select'))
.reduce((acc, input) => {
return {
...acc,
[input.id]: input.value
}
}, {})
}
let formData = { ...formInputs, ...formSelects }
const accept_terms = document.getElementById('accept_terms')
const accept_personal_data = document.getElementById('accept_personal_data')
formData['accept_personal_data'] = accept_personal_data.checked ? 1 : 0
formData['accept_terms'] = accept_terms.checked ? 1 : 0
const password = formData.password.toString()
const username = formData.email
const userData = {
Username: username,
Password: formData.password,
UserAttributes: [
{ Name: "name", Value: username },
{ Name: "phone_number", Value: '+51111111111'},
{ Name: "custom:phone", Value: '51111111111'},
{ Name: "custom:channel", Value: document.URL },
{ Name: "custom:is_self_registered", Value: "1" },
{ Name: "custom:accept_personal_data", Value: formData.accept_personal_data.toString() },
{ Name: "custom:accept_terms", Value: formData.accept_terms.toString() }
],
ValidationData: null,
ClientId: currentEnvironment.COGNITO_CLIENT_ID
}
validateBusiness(formData, userData, username, password)
}
const validateBusiness = (formData, userData, username, password) => {
registerUser(formData, userData, username, password)
}
const registerUser = (formData, userData, username, password) => {
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/x-amz-json-1.1',
'x-amz-target': 'AWSCognitoIdentityProviderService.SignUp',
'x-amz-user-agent': 'aws-amplify/0.1.x js'
}
axios.post(currentEnvironment.COGNITO, userData, { headers })
.then(data => {
preRegisterUser(formData, username, password)
})
.catch(err => {
document.getElementById('submit').disabled = false;
const serverError = errorCodes[err?.response?.data?.__type || ''] || errorCodes.default
const errorSection = document.getElementById('errorSection')
errorSection.innerHTML = `
${serverError}
`
console.error({ err })
})
}
const preRegisterUser = (formData, username, password) => {
const routeName = window.location.pathname.split('/').at(-1).toUpperCase()
const type = catalogPlans[routeName] || 'DEFAULT'
savedPassword = password
catalogTypeParam = type
const payload = {
email: username,
formData: {
businessData: {
user: {
phone: 0,
email: username,
channel: document.URL
},
userInfo: {
personalData: {
accept: Number(formData.accept_personal_data),
created: new Date()
},
termsAndConditions: {
accept: Number(formData.accept_terms),
created: new Date()
}
},
lastName: ".",
phone: 0,
demoBusiness: false,
roleDescription: "Permiso de administrador",
roleName: "Administrador",
terminalLimit: 0,
channel: "WALLY",
dealersChannel: formData.dealers
},
}
}
axios.post(currentEnvironment.SAVE_PRE_SUBSCRIPTION, payload).then(res => {
const credencialKey = encryptText(savedPassword)
location.replace(currentEnvironment.REDIRECT_CONFIRM_CODE(catalogTypeParam, username, credencialKey))
}).catch(err => {
if (err.response?.data?.message === "Ya existe un usuario cargado con ese email") {
} else {
document.getElementById('submit').disabled = false;
const serverError = 'El correo ya existe, por favor intentar con otro correo.' || errorCodes.default
const errorSection = document.getElementById('errorSection')
errorSection.innerHTML = `
${serverError}
`
console.log({ err })
}
})
}
const hideSelectFieldDealers = () => {
if(!isDealers){
const dealers_label = document.getElementById('dealers-label')
const dealers = document.getElementById('dealers')
dealers.remove()
dealers_label.remove()
}
}
hideSelectFieldDealers()