From 2cea88149575308665bd073e5e5c065f99427b3a Mon Sep 17 00:00:00 2001 From: David Arranz Date: Fri, 31 May 2024 11:10:26 +0200 Subject: [PATCH] . --- helpers/hubspot.helper.js | 392 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 392 insertions(+) create mode 100644 helpers/hubspot.helper.js diff --git a/helpers/hubspot.helper.js b/helpers/hubspot.helper.js new file mode 100644 index 0000000..a3ddd4b --- /dev/null +++ b/helpers/hubspot.helper.js @@ -0,0 +1,392 @@ +"use strict"; + +const hubspot = require("@hubspot/api-client"); +const config = require("../config"); + +const HB_PERFIL = { + free: "Otros", + guest: "Invitado", + tutor: "Profesor", + student: "Estudiante", +}; + +function _getMemberByEmail(userEmail) { + // Configure API key authorization: api-key + const defaultClient = new hubspot.Client({ accessToken: config.hubspot.API_KEY }); + + return new Promise(function (resolve, reject) { + console.debug("_existsMember HS:", userEmail); + + defaultClient.crm.contacts.searchApi + .doSearch({ + filterGroups: [ + { + filters: [ + { + propertyName: "email", + operator: "EQ", + value: userEmail, + }, + ], + }, + ], + properties: [ + "email", + "firstname", + "lastname", + "phone", + "perfil", + "entidad_protagonista", + "ciudad_del_evento", + "pais", + "ano_del_congreso", + "tipo_de_evento", + ], + }) + .then(function (data) { + /** + * { + total: 1, + results: [ + { + createdAt: "2023-07-25T08:19:05.729Z", + archived: false, + id: "16173", + properties: { + createdate: "2023-07-25T08:19:05.729Z", + email: "darranz@rodax-software.com", + hs_object_id: "16173", + lastmodifieddate: "2024-04-17T00:46:35.476Z", + }, + updatedAt: "2024-04-17T00:46:35.476Z", + }, + ], + } + */ + console.debug("HS API called successfully. Returned total: " + data.total); + if (data.total === 1) { + resolve(data.results[0]); + } else { + resolve(null); + } + }) + .catch(function (error) { + console.error(error); + reject(error); + }); + }); +} + +function _createMember(member) { + // Configure API key authorization: api-key + const defaultClient = new hubspot.Client({ accessToken: config.hubspot.API_KEY }); + + return new Promise(function (resolve, reject) { + console.debug("_createMember HS:", member.email); + + /** + * member = { + id: "3cc58b92-d144-492d-a8e8-9e1294b5b10b", + source: "app", + event_name: "Sevilla 2023 - 22ª Edición", + event_date: "2024-06-03T07:00:00.000Z", + event_marketing_list: null, + date_inscription: "2024-05-29T13:52:01.752Z", + code_ticket: "ENT-99919197", + validated: true, + reservation_code: null, + color: "darkgreen", + description: "ENTRADA", + qrConfig: null, + qrCode: null, + email: "darranz@rodax-software.com", + name: "David", + surname: "Arranz Puerta", + phone: "+34629905522", + profile: "tutor", + userId: "e52294c5-e8c3-45b1-97ea-6e0a6c36eefa", + entity: "Asoc Nena Paine", + } + */ + + const newContact = { + email: member.email, + firstname: member.name, + lastname: member.surname, + phone: member.phone, + perfil: HB_PERFIL[member.profile] || HB_PERFIL.free, + entidad_protagonista: member.entity ? member.entity : "", + }; + + console.debug(newContact); + defaultClient.crm.contacts.basicApi + .create({ + properties: newContact, + }) + .then(function (newContact) { + console.debug("HS API called successfully. Returned data: " + newContact.id); + resolve(newContact); + }) + .catch(function (error) { + console.error(error); + reject(error); + }); + }); +} + +function _updateMember(email, member) { + // Configure API key authorization: api-key + const defaultClient = new hubspot.Client({ accessToken: config.hubspot.API_KEY }); + + return new Promise(function (resolve, reject) { + console.debug("_updateMember HS:", email); + + /** + * member = { + email: "darranz@rodax-software.com", + name: "David", + surname: "Arranz Puerta", + userId: "e52294c5-e8c3-45b1-97ea-6e0a6c36eefa", + profile: "tutor", + entity: "Asoc Nena Paine", + } + */ + + _getMemberByEmail(email).then((data) => { + if (data && data.id) { + defaultClient.crm.contacts.basicApi + .update(data.id, { + properties: { + email: member.email, + firstname: member.name, + lastname: member.surname, + phone: member.phone, + perfil: HB_PERFIL[member.profile] || HB_PERFIL.free, + entidad_protagonista: member.entity ? member.entity : "", + }, + }) + .then(function (response) { + /** + * response = { + createdAt: "2023-07-25T08:19:05.729Z", + archived: false, + id: "16173", + properties: { + ano_del_congreso: "2023", + ciudad_del_evento: "Barcelona", + createdate: "2023-07-25T08:19:05.729Z", + email: "darranz@rodax-software.com", + entidad_protagonista: "", + firstname: "David", + hs_object_id: "16173", + lastmodifieddate: "2024-05-29T09:43:07.118Z", + lastname: "Arranz Puerta", + pais: null, + perfil: "Otros;Profesor;Estudiante", + phone: "+34629905522", + tipo_de_evento: "Congreso", + }, + updatedAt: "2024-05-29T09:43:07.118Z", + }} + */ + + console.debug("HS API called successfully. Returned data: " + response); + resolve(updatedContact); + }) + .catch(function (error) { + console.error(error); + reject(error); + }); + } + }); + }); +} + +function _deleteMember(email) { + // Configure API key authorization: api-key + const defaultClient = new hubspot.Client({ accessToken: config.hubspot.API_KEY }); + + return new Promise(function (resolve, reject) { + console.debug("_deleteMember HS:", email); + + _getMemberByEmail(email).then((data) => { + if (data && data.id) { + defaultClient.crm.contacts.basicApi + .archive(data.id) + .then(function (response) { + console.debug("HS API called successfully. Returned data: " + response); + resolve(); + }) + .catch(function (error) { + console.error(error); + reject(error); + }); + } + }); + }); +} + +async function _addInscriptionToMember(hbContact, member) { + /** + * { + id: "700d5edd-c8da-4179-adfb-d41abeed1441", + source: "app", + event_name: "Sevilla 2023 - 22ª Edición", + event_date: "2024-06-03T07:00:00.000Z", + event_marketing_list: null, + event_country: "España", + event_city: "Sevilla", + date_inscription: "2024-05-30T15:01:31.420Z", + code_ticket: "ENT-09488890", + validated: true, + reservation_code: null, + color: "darkgreen", + description: "ENTRADA", + qrConfig: null, + qrCode: null, + email: "darranz@rodax-software.com", + name: "david", + surname: "arranz", + phone: "+34629905522", + profile: "free", + userId: "e52294c5-e8c3-45b1-97ea-6e0a6c36eefa", + entity: null, + } + */ + + const { properties } = hbContact; + let ciudad_del_evento, pais, ano_del_congreso; + + if (member.event_city) { + ciudad_del_evento = String(properties.ciudad_del_evento || "").split(";"); + ciudad_del_evento.push(member.event_city); + ciudad_del_evento = ciudad_del_evento.join(";"); + } + + if (member.event_country) { + pais = String(properties.pais || "").split(";"); + pais.push(member.event_country); + pais = pais.join(";"); + } + + if (member.event_date) { + ano_del_congreso = String(properties.ano_del_congreso || "").split(";"); + ano_del_congreso.push(String(new Date(member.event_date).getUTCFullYear())); + ano_del_congreso = ano_del_congreso.join(";"); + } + + const defaultClient = new hubspot.Client({ accessToken: config.hubspot.API_KEY }); + const updatedContact = await defaultClient.crm.contacts.basicApi.update(hbContact.id, { + properties: { + ciudad_del_evento, + pais, + ano_del_congreso, + tipo_de_evento: "Congreso", + }, + }); + + return updatedContact; +} + +async function _deleteInscriptionFromMember(hbContact, inscription) { + /** + * arg1: {id: 'c8a39de5-2de6-45e8-84b5-bda22ff81492', source: 'app', event_name: 'Sevilla 2023 - 22ª Edición', event_date: Mon Jun 03 2024 09:00:00 GMT+0200 (hora de verano de Europa central), event_marketing_list: null, …} + */ + console.log(inscription); + + const { + event: { + location: { city: delete_city, country: delete_country }, + }, + } = inscription; + + const { properties } = hbContact; + + let ciudad_del_evento = String(properties.ciudad_del_evento || "").split(";"); + if (ciudad_del_evento.includes(delete_city)) { + if (ciudad_del_evento.length > 1) { + ciudad_del_evento = ciudad_del_evento.filter((ciudad) => ciudad !== delete_city); + ciudad_del_evento = ciudad_del_evento.join(";"); + } else { + ciudad_del_evento = null; // + } + } + + let pais = String(properties.pais || "").split(";"); + if (pais.includes(delete_country)) { + if (pais.length > 1) { + pais = pais.filter((ciudad) => ciudad !== delete_city); + pais = pais.join(";"); + } else { + pais = null; // + } + } + + const defaultClient = new hubspot.Client({ accessToken: config.hubspot.API_KEY }); + const updatedContact = await defaultClient.crm.contacts.basicApi.update(hbContact.id, { + properties: { + ciudad_del_evento, + //pais, + //ano_del_congreso, + tipo_de_evento: "Congreso", + }, + }); + + return; +} + +async function addMemberToList(listId, member) { + let hbContact = await _getMemberByEmail(member.email); + if (hbContact && hbContact.id) { + hbContact = await _addInscriptionToMember(hbContact, member); + } else { + hbContact = await _createMember(member); + await _addInscriptionToMember(hbContact, member); + } + return hbContact; +} + +function updateMemberByEmail(userEmail, userData) { + return _updateMember(userEmail, userData); +} + +async function deleteMemberFromList(listId, userEmail, inscription) { + // <-- viene por eliminar inscripción + + let hbContact = await _getMemberByEmail(userEmail); + if (hbContact && hbContact.id) { + await _deleteInscriptionFromMember(hbContact, inscription); + + /* + _deleteInscriptionFromMember(hbContact, inscription).then(() => { + // ¿debo archivarlo? + // si-> _deleteMemeber(userEmail); + }) + if (_hbContactWithLastInscription(hbContact)) { + return _deleteMember(userEmail); + } else { + return _updateMember(email, inscription) + } + } else { + return _createMember(member); + }*/ + } + return; +} + +function deleteMemberByEmail(userEmail) { + // <- viene por borrar usuario + return _deleteMember(userEmail); +} + +function getMemberByEmail(userEmail) { + return _getMemberByEmail(userEmail).then((data) => data !== null); +} + +module.exports = { + addMemberToList, + deleteMemberFromList, + updateMemberByEmail, + deleteMemberByEmail, + getMemberByEmail, +};