Commit 62515151 authored by Gabriel's avatar Gabriel

Agrega integracion con sendinblue

parent 48551b82
...@@ -72,6 +72,10 @@ async function updateCrispData(website_id, session_id, correo, tipo_documento, n ...@@ -72,6 +72,10 @@ async function updateCrispData(website_id, session_id, correo, tipo_documento, n
}); });
} }
async function getCrispData(website_id, session_id) {
return await CrispClient.websiteConversations.getMeta(website_id, session_id);
}
async function updateUserData(website_id, session_id, data) { async function updateUserData(website_id, session_id, data) {
localData[website_id.concat(session_id)] = data; localData[website_id.concat(session_id)] = data;
} }
...@@ -85,5 +89,6 @@ module.exports = ...@@ -85,5 +89,6 @@ module.exports =
setSiguientePaso: setSiguientePaso, setSiguientePaso: setSiguientePaso,
getUserData: getUserData, getUserData: getUserData,
updateUserData: updateUserData, updateUserData: updateUserData,
updateCrispData: updateCrispData updateCrispData: updateCrispData,
getCrispData: getCrispData
} }
\ No newline at end of file
...@@ -2,8 +2,11 @@ const config = require('config'); ...@@ -2,8 +2,11 @@ const config = require('config');
const axios = require('axios'); const axios = require('axios');
var AUTH_TOKEN = config.get('credenciales.isApiToken'); var AUTH_TOKEN = config.get('credenciales.isApiToken');
axios.defaults.baseURL = config.get('baseUrl')
axios.defaults.headers.common = {'Authorization': `Bearer ${AUTH_TOKEN}`} let isClient = axios.create({
baseURL: config.get('isBaseUrl'),
headers: {'Authorization': `Bearer ${AUTH_TOKEN}`}
});
function sortProvinciasById(provincias) { function sortProvinciasById(provincias) {
let ids = []; let ids = [];
...@@ -33,7 +36,7 @@ function getProvinciaById(provincias, id) { ...@@ -33,7 +36,7 @@ function getProvinciaById(provincias, id) {
module.exports = module.exports =
{ {
getProvincias: async function () { getProvincias: async function () {
return await axios.get('provincias/atencion') return await isClient.get('provincias/atencion')
.then(async function (response) { .then(async function (response) {
let provincias = response.data; let provincias = response.data;
return sortProvinciasById(provincias); return sortProvinciasById(provincias);
...@@ -43,7 +46,7 @@ module.exports = ...@@ -43,7 +46,7 @@ module.exports =
}); });
}, },
getMedicosByName: async function (nombreMedico, idProvincia) { getMedicosByName: async function (nombreMedico, idProvincia) {
return await axios.get(`/medicos/atencion?id_provincia=${idProvincia}&nombre=${nombreMedico}`) return await isClient.get(`/medicos/atencion?id_provincia=${idProvincia}&nombre=${nombreMedico}`)
.then(async function (response) { .then(async function (response) {
return response.data.data; return response.data.data;
}) })
...@@ -52,7 +55,7 @@ module.exports = ...@@ -52,7 +55,7 @@ module.exports =
}); });
}, },
getEspecialidadesMedico: async function (idPersonaInstitucional, idProvincia) { getEspecialidadesMedico: async function (idPersonaInstitucional, idProvincia) {
return await axios.get(`/atenciones?id_provincia=${idProvincia}&id_persona_institucional=${idPersonaInstitucional}`) return await isClient.get(`/atenciones?id_provincia=${idProvincia}&id_persona_institucional=${idPersonaInstitucional}`)
.then(async function (response) { .then(async function (response) {
return response.data.data; return response.data.data;
}) })
...@@ -61,7 +64,7 @@ module.exports = ...@@ -61,7 +64,7 @@ module.exports =
}); });
}, },
getTurnosDisponibles: async function (idAgenda, idPersonaInstitucional, fechaUsa) { getTurnosDisponibles: async function (idAgenda, idPersonaInstitucional, fechaUsa) {
return await axios.get(`/turnos/turnos_disponibles?id_agenda=${idAgenda}&id_persona_institucional=${idPersonaInstitucional}&fecha=${fechaUsa}`) return await isClient.get(`/turnos/turnos_disponibles?id_agenda=${idAgenda}&id_persona_institucional=${idPersonaInstitucional}&fecha=${fechaUsa}`)
.then(async function (response) { .then(async function (response) {
return response.data.turnos; return response.data.turnos;
}) })
...@@ -70,7 +73,7 @@ module.exports = ...@@ -70,7 +73,7 @@ module.exports =
}); });
}, },
getSiguientesTurnosDisponibles: async function (idAgenda, idPersonaInstitucional) { getSiguientesTurnosDisponibles: async function (idAgenda, idPersonaInstitucional) {
return await axios.get(`/turnos/turnos_siguientes_disponibles?id_agenda=${idAgenda}&id_persona_institucional=${idPersonaInstitucional}`) return await isClient.get(`/turnos/turnos_siguientes_disponibles?id_agenda=${idAgenda}&id_persona_institucional=${idPersonaInstitucional}`)
.then(async function (response) { .then(async function (response) {
return response.data; return response.data;
}) })
...@@ -79,7 +82,7 @@ module.exports = ...@@ -79,7 +82,7 @@ module.exports =
}); });
}, },
existeUsuario: async function(tipo_documento, numero_documento, fecha_nacimiento, sexo){ existeUsuario: async function(tipo_documento, numero_documento, fecha_nacimiento, sexo){
return await axios.get(`/watson/existe_persona?tipo_documento=${tipo_documento}&numero_documento=${numero_documento}&fecha_nacimiento=${fecha_nacimiento}&sexo=${sexo}`) return await isClient.get(`/watson/existe_persona?tipo_documento=${tipo_documento}&numero_documento=${numero_documento}&fecha_nacimiento=${fecha_nacimiento}&sexo=${sexo}`)
.then(async function (response) { .then(async function (response) {
return response.data.existe; return response.data.existe;
}) })
...@@ -88,7 +91,7 @@ module.exports = ...@@ -88,7 +91,7 @@ module.exports =
}); });
}, },
crearTurno: async function (tipoDocumento, numeroDocumento, fechaNacimiento, sexo, mail, telefono, idHorario, fechaHora) { crearTurno: async function (tipoDocumento, numeroDocumento, fechaNacimiento, sexo, mail, telefono, idHorario, fechaHora) {
return await axios.post('/watson/confirmar_reserva', { return await isClient.post('/watson/confirmar_reserva', {
"tipo_documento": tipoDocumento, "tipo_documento": tipoDocumento,
"numero_documento": numeroDocumento, "numero_documento": numeroDocumento,
"fecha_nacimiento": fechaNacimiento, "fecha_nacimiento": fechaNacimiento,
......
const config = require('config');
const axios = require('axios');
const API_KEY = config.get('credenciales.sendinblue.apiKey');
const COUNTRY_CODE_ARG = "+54";
const ERROR_CODE_DUPLICATE_PARAMETER = 'duplicate_parameter';
let sendinblueClient = axios.create({
baseURL: config.get('sendingbluBaseUrl'),
headers: {'api-key': `${API_KEY}`}
});
async function saveContactToList(email, nombres, apellidos, sms, listId){
sms = parseSms(sms);
createOrUpdateContact(email, nombres, apellidos, sms)
.then(function (data){
console.log(`Usuario ${email} creado/actualizado`);
addContactToList(email, listId);
})
.catch(function (error) {
console.log(`Error al crear/actualizar usuario en sendinblue: ${JSON.stringify(error?.response?.data)}`);
});
}
function parseSms(sms){
return sms.includes(COUNTRY_CODE_ARG) ? sms : `${COUNTRY_CODE_ARG}${sms}`;
}
async function createOrUpdateContact(email, nombres, apellidos, sms){
return await sendinblueClient.post('/contacts', {
"email": email,
"attributes": {
"NOMBRE": nombres,
"SURNAME": apellidos,
"SMS": sms
}
})
.then(async function (response) {
return response.data;
})
.catch(async function (error) {
if(error?.response?.data?.code === ERROR_CODE_DUPLICATE_PARAMETER){
console.log(error?.response?.data)
return await sendinblueClient.put(encodeURI(`/contacts/${email}`), {
"attributes": {
"NOMBRE": nombres,
"SURNAME": apellidos,
"SMS": sms
}
})
.then(async function (response) {
return response.data;
})
}
});
}
async function addContactToList(email, listId){
return await sendinblueClient.post(`/contacts/lists/${listId}/contacts/add`, {
"emails": [email]
})
.then(async function (response) {
console.log(`Usuario ${email} agregado a lista ${listId}`)
return response.data;
})
.catch(async function (error) {
console.log(`Error al agregar al usuario ${email} a la lista ${listId}: ${JSON.stringify(error?.response?.data)}`);
});
}
module.exports =
{
saveContactToList: saveContactToList
}
\ No newline at end of file
...@@ -4,7 +4,8 @@ const handlers = require('./handlers.js'); ...@@ -4,7 +4,8 @@ const handlers = require('./handlers.js');
const crisp = require('./crisp.js'); const crisp = require('./crisp.js');
const utils = require('./utils.js'); const utils = require('./utils.js');
const pasos = require('./pasos.js'); const pasos = require('./pasos.js');
const is = require('./endpoints/is.js') const is = require('./endpoints/is.js');
const sendinblue = require('./endpoints/sendinblue.js');
crisp.CrispClient.on("message:updated", async function (message) { crisp.CrispClient.on("message:updated", async function (message) {
darSiguientePaso(message, message.website_id, message.session_id); darSiguientePaso(message, message.website_id, message.session_id);
...@@ -22,8 +23,21 @@ crisp.CrispClient.on("message:send", async function (message) { ...@@ -22,8 +23,21 @@ crisp.CrispClient.on("message:send", async function (message) {
} }
let siguientePaso = await crisp.getSiguientePaso(message.website_id, message.session_id); let siguientePaso = await crisp.getSiguientePaso(message.website_id, message.session_id);
if (siguientePaso == null) { if (siguientePaso == null) {
enviarUserAListaSendingblue(message.website_id, message.session_id, config.get('sendingblueListId'));
await crisp.setSiguientePaso(message.website_id, message.session_id, pasos.ASK_RESERVAR_TURNO) await crisp.setSiguientePaso(message.website_id, message.session_id, pasos.ASK_RESERVAR_TURNO)
} }
await darSiguientePaso(message, message.website_id, message.session_id); await darSiguientePaso(message, message.website_id, message.session_id);
}); });
async function enviarUserAListaSendingblue(website_id, session_id, listId){
let crispUsrData = await crisp.getCrispData(website_id, session_id);
let nombreCompleto = crispUsrData['nickname']; // ej: "Lucas Mariano | Rodriguez"
let nombres = nombreCompleto.split("|")[0].slice(0, -1);
let apellidos = nombreCompleto.split("|")[1].substring(1);
let email = crispUsrData['email'];
let phone = crispUsrData['phone'];
console.log(nombres, apellidos, email, phone);
sendinblue.saveContactToList(email, nombres, apellidos, phone, listId);
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment