feat: Adjustment in functions to search for company Id and client Id for oauth2

master
adriano 2025-01-15 11:53:39 -03:00
parent 1bdc545b4f
commit 12a87332f4
12 changed files with 82 additions and 33 deletions

View File

@ -184,9 +184,14 @@ const oauthCallBack = async (req, res) => {
console.log('xxxxxxxxxx clientId: ', clientId)
console.log('xxxxxxxxxx companyId: ', companyId)
console.log('xxxxxxxxxx code: ', code)
if (code) {
console.log('xxxxxxxxxx passed')
let crmOauth = await CRM.findOne({ 'crm.authentication.crmClientId': clientId, 'companyId': companyId })
crmOauth = crmOauth.toObject()
let authCodeProof = {
@ -221,7 +226,7 @@ const oauthCallBack = async (req, res) => {
// Exchange the authorization code for an access token and refresh token
await exchangeForTokens(crmOauth, authCodeProof)
await exchangeForTokens(crmOauth, authCodeProof, companyId)
const url = `${process.env.URL_OAUTH_FRONTEND_SUCCESS_REDIRECT}?clientId=${encodeURIComponent(clientId)}&codWeb=${companyId}`
@ -260,6 +265,11 @@ const uploadCrmConfig = async (req, res) => {
mustContainProperties(req, ['companyId',])
//test
// console.log('============> uploadCrmConfig companyId: ', companyId)
// return res.send()
//
if (!req?.file)
throw new CustomError.BadRequestError(`The crm property file must be provided`)

View File

@ -41,8 +41,8 @@ async function createContact(companyId, rest, authentication, crmPhone, crmFirst
const { type, userName, passWord, token, crmClientId } = authentication
//url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data = ''
const config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, body)
//url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data = '', ticketId = '', companyId
const config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, body, '', companyId)
if (test?.testing) {
msg = `Tentanto criar contato de numero ${crmPhone} no crm`

View File

@ -46,8 +46,8 @@ async function createTicket(companyId, rest, authentication, crmPhone, crmFirstN
const { type, userName, passWord, token, crmClientId } = authentication
//url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data = ''
const config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, body)
//url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data = '', ticketId = '', companyId
const config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, body, '', companyId)
if (test?.testing) {
msg = `Tentanto criar ticket do numero ${crmPhone} no crm`

View File

@ -23,7 +23,7 @@ async function journaling(companyId, operation, crmPhone, crmAgent, crmCallDurat
let body = findProperty(calls, operation)
await journalingRequest(request, body, crmCallDuration, contact, crmAgent, crmPhone, authentication, rest)
await journalingRequest(request, body, crmCallDuration, contact, crmAgent, crmPhone, authentication, rest, companyId)
}

View File

@ -6,8 +6,8 @@ const axios = require('axios')
const path = require('path')
const convertToIntegerIfNumber = require('./convertToIntegerIfNumber')
const sendMessageSocket = require('./sendMessageSocket')
async function journalingRequest(request, body, crmCallDuration, contact, crmAgent, crmPhone, authentication, test = {}) {
// request, body, crmCallDuration, contact, crmAgent, crmPhone, authentication, rest, companyId
async function journalingRequest(request, body, crmCallDuration, contact, crmAgent, crmPhone, authentication, test = {}, companyId='') {
const { requestContentType, requestEncoding, requestType, responseType, url } = request
console.log('----------> crmCallDuration: ', crmCallDuration)
@ -118,8 +118,8 @@ async function journalingRequest(request, body, crmCallDuration, contact, crmAge
const data = unflatten(body)
const { type, userName, passWord, token, crmClientId } = authentication
const config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data)
// url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data = '', ticketId = '', companyId
const config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data, '', companyId)
if (test?.testing && test?.companyId && test?.msg) {
sendMessageSocket({ companyId: test.companyId, status: 'processing', data: { request: config, msg: test.msg } })
@ -132,7 +132,20 @@ async function journalingRequest(request, body, crmCallDuration, contact, crmAge
try {
const res = await axios(config)
} catch (error) {
console.log(`CALL JOURNALING ERROR: `, error)
// console.log(`CALL JOURNALING ERROR: `, error)
if (error.response) {
console.error('==================> journalingRequest Erro na resposta da API:', {
status: error.response.status,
data: error.response.data,
})
}
else if (error.request) {
console.error('==================> journalingRequest Nenhuma resposta recebida da API:', error.request)
}
else {
console.error('==================> journalingRequest Erro ao configurar a request:', error.message)
}
}

View File

@ -23,7 +23,7 @@ async function lookupContactByPhone(rest, authentication, crmPhone, companyId, t
if (crmInfo) return { exist: true, contactId: crmInfo.contactId, phone: crmPhone }
const config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId)
const config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, '', '', companyId)
if (test?.testing) {
let msg = `Tentanto checar se o contato de numero ${crmPhone} existe no crm`
@ -49,7 +49,7 @@ async function lookupContactByPhone(rest, authentication, crmPhone, companyId, t
console.error('==================> Erro ao configurar a request:', error.message)
}
throw error
// throw error
}

View File

@ -20,7 +20,7 @@ async function lookupCrmTicket(rest, authentication, crmPhone, companyId, test =
const { type, userName, passWord, token, crmClientId } = authentication
const config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, '', ticketId)
const config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, '', ticketId, companyId)
if (test?.testing) {
let msg = `Tentanto checar o status do ticket para o numer ${crmPhone} no crm`

View File

@ -6,7 +6,9 @@ const CRM = require('../models/CRM')
const { set, get, del } = require('./redisClient')
const get75PercentTimeInSeconds = require('./get75PercentTimeInSeconds')
const exchangeForTokens = async (crmOauth, exchangeProof) => {
const exchangeForTokens = async (crmOauth, exchangeProof, companyId) => {
console.log('===========> exchangeForTokens companyId: ', companyId)
const { request, body, response } = findProperty(crmOauth.crm.crmRest, 'tokenEndpoint')
@ -27,6 +29,7 @@ const exchangeForTokens = async (crmOauth, exchangeProof) => {
}
console.log('======> CONFIG: ', config)
console.log('======> companyId: ', companyId)
// const { data } = await axios(config)
@ -56,20 +59,27 @@ const exchangeForTokens = async (crmOauth, exchangeProof) => {
//
console.log('===========> auth2 data: ', data)
const { refresh_token, access_token, token_type, expires_in, issued_at } = data
console.log('===========> refresh_token: ', refresh_token)
console.log('===========> access_token: ', access_token)
// `${clientId+companyId}`
// salesforce case
if (issued_at)
await set(crmOauth.crm.authentication.crmClientId, access_token, get75PercentTimeInSeconds(issued_at))
await set(`${crmOauth.crm.authentication.crmClientId+companyId}`, access_token, get75PercentTimeInSeconds(issued_at))
else
await set(crmOauth.crm.authentication.crmClientId, access_token, Math.round(expires_in * 0.75))
await set(`${crmOauth.crm.authentication.crmClientId+companyId}`, access_token, Math.round(expires_in * 0.75))
crmOauth = await CRM.findOne({ 'crm.authentication.crmClientId': crmOauth.crm.authentication.crmClientId })
crmOauth = await CRM.findOne({ 'crm.authentication.crmClientId': crmOauth.crm.authentication.crmClientId, 'companyId': companyId })
if (refresh_token) {
console.log('===========> refresh_token2: ', refresh_token)
crmOauth.crm.authentication.crmOAuthRefreshToken = refresh_token
}
crmOauth.crm.authentication.crmOAuthToken = access_token
@ -79,9 +89,9 @@ const exchangeForTokens = async (crmOauth, exchangeProof) => {
}
const refreshAccessToken = async (clientId) => {
const refreshAccessToken = async (clientId, companyId) => {
let crmOauth = await CRM.findOne({ 'crm.authentication.crmClientId': clientId })
let crmOauth = await CRM.findOne({ 'crm.authentication.crmClientId': clientId, companyId })
crmOauth = crmOauth.toObject()
const refreshTokenProof = {
@ -91,16 +101,18 @@ const refreshAccessToken = async (clientId) => {
redirect_uri: process.env.URL_OAUTH_CALLBACK,
refresh_token: crmOauth.crm.authentication.crmOAuthRefreshToken
}
return await exchangeForTokens(crmOauth, refreshTokenProof)
return await exchangeForTokens(crmOauth, refreshTokenProof, companyId)
}
const getAccessToken = async (clientId) => {
const getAccessToken = async (clientId, companyId) => {
if (!await get(clientId)) {
console.log(`============> clientId+companyId: ${clientId+companyId}`)
if (!await get(`${clientId+companyId}`)) {
console.log('Refreshing expired access token')
await refreshAccessToken(clientId)
await refreshAccessToken(clientId, companyId)
}
return await get(clientId)
return await get(`${clientId+companyId}`)
}

View File

@ -1,6 +1,6 @@
const { getAccessToken } = require('./oauth2')
async function requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data = '', ticketId = '') {
async function requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data = '', ticketId = '', companyId) {
let config = {}
console.log('requestConfigHeader ticketId: ', ticketId)
@ -46,7 +46,8 @@ async function requestConfigHeader(url, crmPhone, requestType, requestContentTyp
}
}
} else if (type === 'oauth2') {
const accessToken = await getAccessToken(crmClientId)
console.log('===============> requestConfigHeader oauth2 companyId: ', companyId)
const accessToken = await getAccessToken(crmClientId, companyId)
config = {
...commonConfig,
headers: {

View File

@ -39,7 +39,7 @@ async function sfcase(companyId, crmPhone) {
const { type, userName, passWord, token, crmClientId } = authentication
const { requestContentType, requestEncoding, requestType, responseType, url } = request
let config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, body)
let config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, body, '', companyId)
console.log("====> config", config)
console.log("====> accountId: ", accountId, " | contactId: ", contactId)
@ -67,7 +67,20 @@ async function sfcase(companyId, crmPhone) {
res.caseId = data.id
} catch (error) {
console.log(`CASE CREATE ERROR: `, error)
// console.log(`CASE CREATE ERROR: `, error)
if (error.response) {
console.error('==================> sfCase Erro na resposta da API:', {
status: error.response.status,
data: error.response.data,
})
}
else if (error.request) {
console.error('==================> sfCase Nenhuma resposta recebida da API:', error.request)
}
else {
console.error('==================> sfCase Erro ao configurar a request:', error.message)
}
}
}

View File

@ -26,7 +26,7 @@ async function sfCaseUpdate(companyId, caseId, caseUpdate) {
const { type, userName, passWord, token, crmClientId } = authentication
const { requestContentType, requestEncoding, requestType, responseType, url } = request
let config = await requestConfigHeader(url, "17999999999", requestType, requestContentType, type, userName, passWord, token, crmClientId, body)
let config = await requestConfigHeader(url, "17999999999", requestType, requestContentType, type, userName, passWord, token, crmClientId, body, '', companyId)
config = {

View File

@ -71,7 +71,7 @@ async function whatsappJournalingCRM(companyId, crmPhone, crmAgent, crmFirstName
await journalingRequest(request, body, crmCallDuration = 0, contact, crmAgent, crmPhone, authentication, rest)
await journalingRequest(request, body, crmCallDuration = 0, contact, crmAgent, crmPhone, authentication, rest, companyId)
}
//