diff --git a/backend/controllers/transcriptionController.js b/backend/controllers/transcriptionController.js index a98a25d..f57c4dc 100644 --- a/backend/controllers/transcriptionController.js +++ b/backend/controllers/transcriptionController.js @@ -1,7 +1,7 @@ const HubspotService = require('../services/hubspotService'); const { get, del } = require('../utils/redisClient') -const hubspotService = new HubspotService(); + const receiveTranscription = async (req, res) => { try { @@ -36,8 +36,10 @@ const receiveTranscription = async (req, res) => { console.warn(`Nenhum ticketId encontrado no Redis para o crmPhone: ${crmPhone}. A transcrição será salva como uma nota sem associação ao ticket.`); } + const hubspotService = await new HubspotService(companyId).init(); + // 2. Buscar ou criar contato no HubSpot - const contact = await hubspotService.createContactIfNotExists(companyId, crmPhone); + const contact = await hubspotService.createContactIfNotExists(crmPhone); // 3. Criar nota no HubSpot e associar ao contato e ao ticket (se existir) await hubspotService.createCallNote(contact.contactId, { diff --git a/backend/services/hubspotService.js b/backend/services/hubspotService.js index 6ee2616..ca6f348 100644 --- a/backend/services/hubspotService.js +++ b/backend/services/hubspotService.js @@ -12,17 +12,28 @@ class HubspotService { /** * Inicializa o serviço HubspotService com configuração da API. */ - constructor() { + constructor(companyId) { this.logger = Logger; - this.baseUrl = 'https://api.hubapi.com'; - this.apiKey = process.env.HUBSPOT_API_KEY; - this.client = axios.create({ - baseURL: this.baseUrl, - headers: { - 'Authorization': `Bearer ${this.apiKey}`, - 'Content-Type': 'application/json' - } - }); + this.companyId = companyId + } + + async init() { + this.crmFiles = await loadCRM(this.companyId); + + if (this?.crmFiles?.length > 0) { + + const { authentication } = this.crmFiles[0].crm + + this.client = axios.create({ + baseURL: 'https://api.hubapi.com', + headers: { + 'Authorization': `Bearer ${authentication.token}`, + 'Content-Type': 'application/json' + } + }); + } + + return this; } /** @@ -118,23 +129,17 @@ Link da Gravação: ${recordingUrl} * @param {string} crmPhone - Número de telefone do contato. * @returns {Promise} - Contato existente ou novo contato criado. */ - async createContactIfNotExists(companyId, crmPhone) { + async createContactIfNotExists(crmPhone) { - console.log('=========> companyId: ', companyId) + if (this?.crmFiles?.length > 0) { - const crmFiles = await loadCRM(companyId) - - console.log('=========> crmFiles: ', crmFiles) - - if (crmFiles.length > 0) { - - const { crmRest: rest, authentication } = crmFiles[0].crm + const { crmRest: rest, authentication } = this.crmFiles[0].crm let contact = await lookupContactByPhone(rest, authentication, crmPhone, companyId) if (!contact.exist) { contact = await createContact(companyId, rest, authentication, crmPhone) - + } console.log('========> contact', contact) return contact