2
0
Files
bot/packages/bot-engine/src/services/integration.ts

211 lines
6.3 KiB
TypeScript
Raw Normal View History

import { ResultValues } from 'contexts/AnswersContext'
import {
IntegrationStep,
IntegrationStepType,
GoogleSheetsStep,
GoogleSheetsAction,
GoogleSheetsInsertRowOptions,
Variable,
GoogleSheetsUpdateRowOptions,
Cell,
GoogleSheetsGetOptions,
GoogleAnalyticsStep,
2022-01-22 18:24:57 +01:00
WebhookStep,
SendEmailStep,
PublicBlock,
} from 'models'
import { stringify } from 'qs'
import { parseAnswers, sendRequest } from 'utils'
import { sendGaEvent } from '../../lib/gtag'
import { sendErrorMessage, sendInfoMessage } from './postMessage'
import { parseVariables, parseVariablesInObject } from './variable'
2022-01-22 18:24:57 +01:00
const safeEval = eval
type IntegrationContext = {
apiHost: string
typebotId: string
2022-02-15 12:36:08 +01:00
blockId: string
stepId: string
isPreview: boolean
variables: Variable[]
resultValues: ResultValues
blocks: PublicBlock[]
updateVariableValue: (variableId: string, value: string) => void
}
export const executeIntegration = ({
step,
context,
}: {
step: IntegrationStep
context: IntegrationContext
}): Promise<string | undefined> => {
switch (step.type) {
case IntegrationStepType.GOOGLE_SHEETS:
return executeGoogleSheetIntegration(step, context)
case IntegrationStepType.GOOGLE_ANALYTICS:
return executeGoogleAnalyticsIntegration(step, context)
2022-01-22 18:24:57 +01:00
case IntegrationStepType.WEBHOOK:
return executeWebhook(step, context)
case IntegrationStepType.EMAIL:
return sendEmail(step, context)
}
}
export const executeGoogleAnalyticsIntegration = async (
step: GoogleAnalyticsStep,
{ variables }: IntegrationContext
) => {
if (!step.options?.trackingId) return step.outgoingEdgeId
const { default: initGoogleAnalytics } = await import('../../lib/gtag')
await initGoogleAnalytics(step.options.trackingId)
sendGaEvent(parseVariablesInObject(step.options, variables))
return step.outgoingEdgeId
}
const executeGoogleSheetIntegration = async (
step: GoogleSheetsStep,
context: IntegrationContext
) => {
if (!('action' in step.options)) return step.outgoingEdgeId
switch (step.options.action) {
case GoogleSheetsAction.INSERT_ROW:
await insertRowInGoogleSheets(step.options, context)
break
case GoogleSheetsAction.UPDATE_ROW:
await updateRowInGoogleSheets(step.options, context)
break
case GoogleSheetsAction.GET:
await getRowFromGoogleSheets(step.options, context)
break
}
return step.outgoingEdgeId
}
const insertRowInGoogleSheets = async (
options: GoogleSheetsInsertRowOptions,
{ variables, apiHost }: IntegrationContext
) => {
if (!options.cellsToInsert) return
return sendRequest({
url: `${apiHost}/api/integrations/google-sheets/spreadsheets/${options.spreadsheetId}/sheets/${options.sheetId}`,
method: 'POST',
body: {
credentialsId: options.credentialsId,
values: parseCellValues(options.cellsToInsert, variables),
},
})
}
const updateRowInGoogleSheets = async (
options: GoogleSheetsUpdateRowOptions,
{ variables, apiHost }: IntegrationContext
) => {
if (!options.cellsToUpsert || !options.referenceCell) return
return sendRequest({
url: `${apiHost}/api/integrations/google-sheets/spreadsheets/${options.spreadsheetId}/sheets/${options.sheetId}`,
method: 'PATCH',
body: {
credentialsId: options.credentialsId,
values: parseCellValues(options.cellsToUpsert, variables),
referenceCell: {
column: options.referenceCell.column,
value: parseVariables(variables)(options.referenceCell.value ?? ''),
},
},
})
}
const getRowFromGoogleSheets = async (
options: GoogleSheetsGetOptions,
{ variables, updateVariableValue, apiHost }: IntegrationContext
) => {
if (!options.referenceCell || !options.cellsToExtract) return
const queryParams = stringify(
{
credentialsId: options.credentialsId,
referenceCell: {
column: options.referenceCell.column,
value: parseVariables(variables)(options.referenceCell.value ?? ''),
},
columns: options.cellsToExtract.map((cell) => cell.column),
},
{ indices: false }
)
const { data } = await sendRequest<{ [key: string]: string }>({
url: `${apiHost}/api/integrations/google-sheets/spreadsheets/${options.spreadsheetId}/sheets/${options.sheetId}?${queryParams}`,
method: 'GET',
})
if (!data) return
options.cellsToExtract.forEach((cell) =>
updateVariableValue(cell.variableId ?? '', data[cell.column ?? ''])
)
}
const parseCellValues = (
cells: Cell[],
variables: Variable[]
): { [key: string]: string } =>
cells.reduce((row, cell) => {
return !cell.column || !cell.value
? row
: {
...row,
[cell.column]: parseVariables(variables)(cell.value),
}
}, {})
2022-01-22 18:24:57 +01:00
const executeWebhook = async (
step: WebhookStep,
{
2022-02-15 12:36:08 +01:00
blockId,
stepId,
variables,
updateVariableValue,
typebotId,
apiHost,
}: IntegrationContext
2022-01-22 18:24:57 +01:00
) => {
if (!step.webhook) return step.outgoingEdgeId
2022-01-22 18:24:57 +01:00
const { data, error } = await sendRequest({
2022-02-15 12:36:08 +01:00
url: `${apiHost}/api/typebots/${typebotId}/blocks/${blockId}/steps/${stepId}/executeWebhook`,
2022-01-22 18:24:57 +01:00
method: 'POST',
body: {
variables,
},
})
console.error(error)
step.options.responseVariableMapping.forEach((varMapping) => {
2022-01-22 18:24:57 +01:00
if (!varMapping?.bodyPath || !varMapping.variableId) return
const value = safeEval(`(${JSON.stringify(data)}).${varMapping?.bodyPath}`)
updateVariableValue(varMapping.variableId, value)
})
}
const sendEmail = async (
step: SendEmailStep,
{ variables, apiHost, isPreview, resultValues, blocks }: IntegrationContext
) => {
if (isPreview) sendInfoMessage('Emails are not sent in preview mode')
if (isPreview) return step.outgoingEdgeId
const { options } = step
const { error } = await sendRequest({
url: `${apiHost}/api/integrations/email`,
method: 'POST',
body: {
credentialsId: options.credentialsId,
recipients: options.recipients.map(parseVariables(variables)),
subject: parseVariables(variables)(options.subject ?? ''),
body:
options.body === '{{state}}'
? parseAnswers({ variables, blocks })(resultValues)
: parseVariables(variables)(options.body ?? ''),
cc: (options.cc ?? []).map(parseVariables(variables)),
bcc: (options.bcc ?? []).map(parseVariables(variables)),
},
})
console.error(error)
if (isPreview && error) sendErrorMessage(`Webhook failed: ${error.message}`)
return step.outgoingEdgeId
}