2
0

fix: 🚑️ Webhook and instant updates

This commit is contained in:
Baptiste Arnaud
2022-02-22 10:16:35 +01:00
parent 642a42779b
commit d49461cde6
36 changed files with 317 additions and 204 deletions

View File

@@ -91,13 +91,20 @@ export const BlockNode = ({ block, blockIndex }: Props) => {
}) })
} }
const onDragStart = () => setIsMouseDown(true)
const onDragStop = () => setIsMouseDown(false)
return ( return (
<ContextMenu<HTMLDivElement> <ContextMenu<HTMLDivElement>
renderMenu={() => <BlockNodeContextMenu blockIndex={blockIndex} />} renderMenu={() => <BlockNodeContextMenu blockIndex={blockIndex} />}
isDisabled={isReadOnly} isDisabled={isReadOnly}
> >
{(ref, isOpened) => ( {(ref, isOpened) => (
<DraggableCore onDrag={onDrag} onMouseDown={(e) => e.stopPropagation()}> <DraggableCore
onDrag={onDrag}
onStart={onDragStart}
onStop={onDragStop}
onMouseDown={(e) => e.stopPropagation()}
>
<Stack <Stack
ref={setMultipleRefs([ref, blockRef])} ref={setMultipleRefs([ref, blockRef])}
data-testid="block" data-testid="block"

View File

@@ -94,9 +94,14 @@ export const TypebotContext = ({
}) })
useEffect(() => { useEffect(() => {
if (!typebot || !localTypebot || deepEqual(typebot, localTypebot)) return if (
if (typebot?.blocks.length === localTypebot?.blocks.length) !typebot ||
setLocalTypebot({ ...typebot }) !localTypebot ||
typebot.updatedAt <= localTypebot.updatedAt ||
deepEqual(typebot, localTypebot)
)
return
setLocalTypebot({ ...typebot })
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [typebot]) }, [typebot])
@@ -113,8 +118,8 @@ export const TypebotContext = ({
] = useUndo<Typebot | undefined>(undefined) ] = useUndo<Typebot | undefined>(undefined)
const saveTypebot = async () => { const saveTypebot = async () => {
if (deepEqual(typebot, localTypebot)) return
const typebotToSave = currentTypebotRef.current const typebotToSave = currentTypebotRef.current
if (deepEqual(typebot, typebotToSave)) return
if (!typebotToSave) return if (!typebotToSave) return
setIsSavingLoading(true) setIsSavingLoading(true)
const { error } = await updateTypebot(typebotToSave.id, typebotToSave) const { error } = await updateTypebot(typebotToSave.id, typebotToSave)

View File

@@ -12,7 +12,8 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.status(401).json({ message: 'Not authenticated' }) return res.status(401).json({ message: 'Not authenticated' })
const user = session.user as User const user = session.user as User
const { code } = JSON.parse(req.body) const { code } =
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const coupon = await prisma.coupon.findFirst({ const coupon = await prisma.coupon.findFirst({
where: { code, dateRedeemed: null }, where: { code, dateRedeemed: null },
}) })

View File

@@ -26,7 +26,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ folders }) return res.send({ folders })
} }
if (req.method === 'POST') { if (req.method === 'POST') {
const data = JSON.parse(req.body) as Pick<DashboardFolder, 'parentFolderId'> const data = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as Pick<DashboardFolder, 'parentFolderId'>
const folder = await prisma.dashboardFolder.create({ const folder = await prisma.dashboardFolder.create({
data: { ...data, ownerId: user.id, name: 'New folder' }, data: { ...data, ownerId: user.id, name: 'New folder' },
}) })

View File

@@ -26,7 +26,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ folders }) return res.send({ folders })
} }
if (req.method === 'PATCH') { if (req.method === 'PATCH') {
const data = JSON.parse(req.body) as Partial<DashboardFolder> const data = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as Partial<DashboardFolder>
const folders = await prisma.dashboardFolder.update({ const folders = await prisma.dashboardFolder.update({
where: { id_ownerId: { id, ownerId: user.id } }, where: { id_ownerId: { id, ownerId: user.id } },
data, data,

View File

@@ -5,8 +5,9 @@ import { createTransport } from 'nodemailer'
const handler = async (req: NextApiRequest, res: NextApiResponse) => { const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') { if (req.method === 'POST') {
const { from, port, isTlsEnabled, username, password, host, to } = const { from, port, isTlsEnabled, username, password, host, to } = (
JSON.parse(req.body) as SmtpCredentialsData & { to: string } typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as SmtpCredentialsData & { to: string }
const transporter = createTransport({ const transporter = createTransport({
host, host,
port, port,

View File

@@ -12,7 +12,8 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
try { try {
if (req.method === 'POST') { if (req.method === 'POST') {
const data = JSON.parse(req.body) const data =
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebot = await prisma.publicTypebot.create({ const typebot = await prisma.publicTypebot.create({
data: { ...data }, data: { ...data },
}) })

View File

@@ -12,7 +12,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const id = req.query.id.toString() const id = req.query.id.toString()
if (req.method === 'PUT') { if (req.method === 'PUT') {
const data = JSON.parse(req.body) const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebots = await prisma.publicTypebot.update({ const typebots = await prisma.publicTypebot.update({
where: { id }, where: { id },
data, data,

View File

@@ -10,7 +10,8 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, { const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2020-08-27', apiVersion: '2020-08-27',
}) })
const { email, currency } = JSON.parse(req.body) const { email, currency } =
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const session = await stripe.checkout.sessions.create({ const session = await stripe.checkout.sessions.create({
success_url: `${req.headers.origin}/typebots?stripe=success`, success_url: `${req.headers.origin}/typebots?stripe=success`,
cancel_url: `${req.headers.origin}/typebots?stripe=cancel`, cancel_url: `${req.headers.origin}/typebots?stripe=cancel`,

View File

@@ -26,7 +26,8 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ typebots }) return res.send({ typebots })
} }
if (req.method === 'POST') { if (req.method === 'POST') {
const data = JSON.parse(req.body) const data =
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebot = await prisma.typebot.create({ const typebot = await prisma.typebot.create({
data: data:
'blocks' in data 'blocks' in data

View File

@@ -41,7 +41,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ typebots }) return res.send({ typebots })
} }
if (req.method === 'PUT') { if (req.method === 'PUT') {
const data = JSON.parse(req.body) const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebots = await prisma.typebot.update({ const typebots = await prisma.typebot.update({
where: { id_ownerId: { id: typebotId, ownerId: user.id } }, where: { id_ownerId: { id: typebotId, ownerId: user.id } },
data: { data: {
@@ -53,7 +53,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ typebots }) return res.send({ typebots })
} }
if (req.method === 'PATCH') { if (req.method === 'PATCH') {
const data = JSON.parse(req.body) const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebots = await prisma.typebot.update({ const typebots = await prisma.typebot.update({
where: { id_ownerId: { id: typebotId, ownerId: user.id } }, where: { id_ownerId: { id: typebotId, ownerId: user.id } },
data, data,

View File

@@ -12,7 +12,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const id = req.query.id.toString() const id = req.query.id.toString()
if (req.method === 'PUT') { if (req.method === 'PUT') {
const data = JSON.parse(req.body) const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebots = await prisma.user.update({ const typebots = await prisma.user.update({
where: { id }, where: { id },
data, data,

View File

@@ -23,7 +23,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ credentials }) return res.send({ credentials })
} }
if (req.method === 'POST') { if (req.method === 'POST') {
const data = JSON.parse(req.body) as Omit<Credentials, 'ownerId'> const data = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as Omit<Credentials, 'ownerId'>
const { encryptedData, iv } = encrypt(data.data) const { encryptedData, iv } = encrypt(data.data)
const credentials = await prisma.credentials.create({ const credentials = await prisma.credentials.create({
data: { data: {

View File

@@ -22,7 +22,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ customDomains }) return res.send({ customDomains })
} }
if (req.method === 'POST') { if (req.method === 'POST') {
const data = JSON.parse(req.body) as Omit<CustomDomain, 'ownerId'> const data = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as Omit<CustomDomain, 'ownerId'>
try { try {
await createDomainOnVercel(data.name) await createDomainOnVercel(data.name)
} catch (err) { } catch (err) {

View File

@@ -129,7 +129,7 @@ const createAnswers = () => {
const parseTypebotToPublicTypebot = ( const parseTypebotToPublicTypebot = (
id: string, id: string,
typebot: Typebot typebot: Typebot
): PublicTypebot => ({ ): Omit<PublicTypebot, 'createdAt' | 'updatedAt'> => ({
id, id,
name: typebot.name, name: typebot.name,
blocks: parseBlocksToPublicBlocks(typebot.blocks), blocks: parseBlocksToPublicBlocks(typebot.blocks),
@@ -157,10 +157,9 @@ const parseTestTypebot = (partialTypebot: Partial<Typebot>): Typebot => ({
ownerId: 'proUser', ownerId: 'proUser',
theme: defaultTheme, theme: defaultTheme,
settings: defaultSettings, settings: defaultSettings,
createdAt: new Date(),
publicId: null, publicId: null,
publishedTypebotId: null,
updatedAt: new Date(), updatedAt: new Date(),
publishedTypebotId: null,
customDomain: null, customDomain: null,
variables: [{ id: 'var1', name: 'var1' }], variables: [{ id: 'var1', name: 'var1' }],
...partialTypebot, ...partialTypebot,

View File

@@ -6,7 +6,7 @@ import path from 'path'
const typebotId = generate() const typebotId = generate()
test.describe('Dashboard page', () => { test.describe('Dashboard page', () => {
test('folders navigation should work', async ({ page }) => { test('should be able to connect custom domain', async ({ page }) => {
await createTypebots([ await createTypebots([
{ {
id: typebotId, id: typebotId,

View File

@@ -6,7 +6,9 @@ import { methodNotAllowed } from 'utils'
const handler = async (req: NextApiRequest, res: NextApiResponse) => { const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'PUT') { if (req.method === 'PUT') {
const answer = JSON.parse(req.body) as Answer const answer = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as Answer
const result = await prisma.answer.upsert({ const result = await prisma.answer.upsert({
where: { where: {
resultId_blockId_stepId: { resultId_blockId_stepId: {

View File

@@ -27,8 +27,8 @@ const defaultFrom = {
const handler = async (req: NextApiRequest, res: NextApiResponse) => { const handler = async (req: NextApiRequest, res: NextApiResponse) => {
await cors(req, res) await cors(req, res)
if (req.method === 'POST') { if (req.method === 'POST') {
const { credentialsId, recipients, body, subject, cc, bcc } = JSON.parse( const { credentialsId, recipients, body, subject, cc, bcc } = (
req.body typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as SendEmailOptions ) as SendEmailOptions
const { host, port, isTlsEnabled, username, password, from } = const { host, port, isTlsEnabled, username, password, from } =

View File

@@ -37,7 +37,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') { if (req.method === 'POST') {
const spreadsheetId = req.query.spreadsheetId.toString() const spreadsheetId = req.query.spreadsheetId.toString()
const sheetId = req.query.sheetId.toString() const sheetId = req.query.sheetId.toString()
const { credentialsId, values } = JSON.parse(req.body) as { const { credentialsId, values } = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as {
credentialsId: string credentialsId: string
values: { [key: string]: string } values: { [key: string]: string }
} }
@@ -51,7 +53,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'PATCH') { if (req.method === 'PATCH') {
const spreadsheetId = req.query.spreadsheetId.toString() const spreadsheetId = req.query.spreadsheetId.toString()
const sheetId = req.query.sheetId.toString() const sheetId = req.query.sheetId.toString()
const { credentialsId, values, referenceCell } = JSON.parse(req.body) as { const { credentialsId, values, referenceCell } = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as {
credentialsId: string credentialsId: string
referenceCell: Cell referenceCell: Cell
values: { [key: string]: string } values: { [key: string]: string }

View File

@@ -6,7 +6,9 @@ import { methodNotAllowed } from 'utils'
const handler = async (req: NextApiRequest, res: NextApiResponse) => { const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') { if (req.method === 'POST') {
const resultData = JSON.parse(req.body) as { const resultData = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as {
typebotId: string typebotId: string
prefilledVariables: VariableWithValue[] prefilledVariables: VariableWithValue[]
} }

View File

@@ -5,7 +5,9 @@ import { methodNotAllowed } from 'utils'
const handler = async (req: NextApiRequest, res: NextApiResponse) => { const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'PATCH') { if (req.method === 'PATCH') {
const data = JSON.parse(req.body) as { isCompleted: true } const data = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as { isCompleted: true }
const id = req.query.id.toString() const id = req.query.id.toString()
const result = await prisma.result.update({ const result = await prisma.result.update({
where: { id }, where: { id },

View File

@@ -1,12 +1,21 @@
import prisma from 'libs/prisma' import prisma from 'libs/prisma'
import { KeyValue, Typebot, Variable, Webhook, WebhookResponse } from 'models' import {
KeyValue,
PublicTypebot,
ResultValues,
Typebot,
Variable,
Webhook,
WebhookResponse,
} from 'models'
import { parseVariables } from 'bot-engine' import { parseVariables } from 'bot-engine'
import { NextApiRequest, NextApiResponse } from 'next' import { NextApiRequest, NextApiResponse } from 'next'
import got, { Method, Headers, HTTPError } from 'got' import got, { Method, Headers, HTTPError } from 'got'
import { byId, initMiddleware, methodNotAllowed } from 'utils' import { byId, initMiddleware, methodNotAllowed, parseAnswers } from 'utils'
import { stringify } from 'qs' import { stringify } from 'qs'
import { withSentry } from '@sentry/nextjs' import { withSentry } from '@sentry/nextjs'
import Cors from 'cors' import Cors from 'cors'
import { parseSampleResult } from 'services/api/webhooks'
const cors = initMiddleware(Cors()) const cors = initMiddleware(Cors())
const handler = async (req: NextApiRequest, res: NextApiResponse) => { const handler = async (req: NextApiRequest, res: NextApiResponse) => {
@@ -15,87 +24,125 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const typebotId = req.query.typebotId.toString() const typebotId = req.query.typebotId.toString()
const blockId = req.query.blockId.toString() const blockId = req.query.blockId.toString()
const stepId = req.query.stepId.toString() const stepId = req.query.stepId.toString()
const variables = JSON.parse(req.body).variables as Variable[] const { resultValues, variables } = (
const typebot = await prisma.typebot.findUnique({ typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as {
resultValues: ResultValues | undefined
variables: Variable[]
}
const typebot = (await prisma.typebot.findUnique({
where: { id: typebotId }, where: { id: typebotId },
}) })) as unknown as Typebot
const step = (typebot as unknown as Typebot).blocks const step = typebot.blocks.find(byId(blockId))?.steps.find(byId(stepId))
.find(byId(blockId))
?.steps.find(byId(stepId))
if (!step || !('webhook' in step)) if (!step || !('webhook' in step))
return res return res
.status(404) .status(404)
.send({ statusCode: 404, data: { message: `Couldn't find webhook` } }) .send({ statusCode: 404, data: { message: `Couldn't find webhook` } })
const result = await executeWebhook(step.webhook, variables) const result = await executeWebhook(typebot)(
step.webhook,
variables,
blockId,
resultValues
)
return res.status(200).send(result) return res.status(200).send(result)
} }
return methodNotAllowed(res) return methodNotAllowed(res)
} }
const executeWebhook = async ( const executeWebhook =
webhook: Webhook, (typebot: Typebot) =>
variables: Variable[] async (
): Promise<WebhookResponse> => { webhook: Webhook,
if (!webhook.url || !webhook.method) variables: Variable[],
return { blockId: string,
statusCode: 400, resultValues?: ResultValues
data: { message: `Webhook doesn't have url or method` }, ): Promise<WebhookResponse> => {
} if (!webhook.url || !webhook.method)
const basicAuth: { username?: string; password?: string } = {}
const basicAuthHeaderIdx = webhook.headers.findIndex(
(h) =>
h.key?.toLowerCase() === 'authorization' &&
h.value?.toLowerCase().includes('basic')
)
if (basicAuthHeaderIdx !== -1) {
const [username, password] =
webhook.headers[basicAuthHeaderIdx].value?.slice(6).split(':') ?? []
basicAuth.username = username
basicAuth.password = password
webhook.headers.splice(basicAuthHeaderIdx, 1)
}
const headers = convertKeyValueTableToObject(webhook.headers, variables) as
| Headers
| undefined
const queryParams = stringify(
convertKeyValueTableToObject(webhook.queryParams, variables)
)
const contentType = headers ? headers['Content-Type'] : undefined
try {
const response = await got(
parseVariables(variables)(webhook.url + `?${queryParams}`),
{
method: webhook.method as Method,
headers,
...basicAuth,
json:
contentType !== 'x-www-form-urlencoded' && webhook.body
? JSON.parse(parseVariables(variables)(webhook.body))
: undefined,
form:
contentType === 'x-www-form-urlencoded' && webhook.body
? JSON.parse(parseVariables(variables)(webhook.body))
: undefined,
}
)
return {
statusCode: response.statusCode,
data: parseBody(response.body),
}
} catch (error) {
if (error instanceof HTTPError) {
return { return {
statusCode: error.response.statusCode, statusCode: 400,
data: parseBody(error.response.body as string), data: { message: `Webhook doesn't have url or method` },
}
const basicAuth: { username?: string; password?: string } = {}
const basicAuthHeaderIdx = webhook.headers.findIndex(
(h) =>
h.key?.toLowerCase() === 'authorization' &&
h.value?.toLowerCase().includes('basic')
)
if (basicAuthHeaderIdx !== -1) {
const [username, password] =
webhook.headers[basicAuthHeaderIdx].value?.slice(6).split(':') ?? []
basicAuth.username = username
basicAuth.password = password
webhook.headers.splice(basicAuthHeaderIdx, 1)
}
const headers = convertKeyValueTableToObject(webhook.headers, variables) as
| Headers
| undefined
const queryParams = stringify(
convertKeyValueTableToObject(webhook.queryParams, variables)
)
const contentType = headers ? headers['Content-Type'] : undefined
const body = getBodyContent(typebot)({
body: webhook.body,
resultValues,
blockId,
})
try {
const response = await got(
parseVariables(variables)(webhook.url + `?${queryParams}`),
{
method: webhook.method as Method,
headers,
...basicAuth,
json:
contentType !== 'x-www-form-urlencoded' && body
? JSON.parse(parseVariables(variables)(body))
: undefined,
form:
contentType === 'x-www-form-urlencoded' && body
? JSON.parse(parseVariables(variables)(body))
: undefined,
}
)
return {
statusCode: response.statusCode,
data: parseBody(response.body),
}
} catch (error) {
if (error instanceof HTTPError) {
return {
statusCode: error.response.statusCode,
data: parseBody(error.response.body as string),
}
}
console.error(error)
return {
statusCode: 500,
data: { message: `Error from Typebot server: ${error}` },
} }
} }
console.error(error)
return {
statusCode: 500,
data: { message: `Error from Typebot server: ${error}` },
}
} }
}
const getBodyContent =
(typebot: Pick<Typebot | PublicTypebot, 'blocks' | 'variables' | 'edges'>) =>
({
body,
resultValues,
blockId,
}: {
body?: string
resultValues?: ResultValues
blockId: string
}): string | undefined => {
if (!body) return
return body === '{{state}}'
? JSON.stringify(
resultValues
? parseAnswers(typebot)(resultValues)
: parseSampleResult(typebot)(blockId)
)
: body
}
const parseBody = (body: string) => { const parseBody = (body: string) => {
try { try {

View File

@@ -1,8 +1,9 @@
import prisma from 'libs/prisma' import prisma from 'libs/prisma'
import { Block, InputStep, InputStepType, Typebot } from 'models' import { Typebot } from 'models'
import { NextApiRequest, NextApiResponse } from 'next' import { NextApiRequest, NextApiResponse } from 'next'
import { authenticateUser } from 'services/api/utils' import { authenticateUser } from 'services/api/utils'
import { byId, isDefined, isInputStep, methodNotAllowed } from 'utils' import { parseSampleResult } from 'services/api/webhooks'
import { methodNotAllowed } from 'utils'
const handler = async (req: NextApiRequest, res: NextApiResponse) => { const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'GET') { if (req.method === 'GET') {
@@ -12,87 +13,11 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const blockId = req.query.blockId.toString() const blockId = req.query.blockId.toString()
const typebot = (await prisma.typebot.findUnique({ const typebot = (await prisma.typebot.findUnique({
where: { id_ownerId: { id: typebotId, ownerId: user.id } }, where: { id_ownerId: { id: typebotId, ownerId: user.id } },
})) as Typebot | undefined })) as unknown as Typebot | undefined
if (!typebot) return res.status(400).send({ message: 'Typebot not found' }) if (!typebot) return res.status(400).send({ message: 'Typebot not found' })
const previousBlockIds = getPreviousBlocks(typebot)(blockId) return res.send(parseSampleResult(typebot)(blockId))
const previousBlocks = typebot.blocks.filter((b) =>
previousBlockIds.includes(b.id)
)
return res.send(parseSampleResult(typebot)(previousBlocks))
} }
methodNotAllowed(res) methodNotAllowed(res)
} }
const parseSampleResult =
(typebot: Typebot) =>
(blocks: Block[]): Record<string, string> => {
const parsedBlocks = parseBlocksResultSample(typebot, blocks)
return {
message: 'This is a sample result, it has been generated ⬇️',
'Submitted at': new Date().toISOString(),
...parsedBlocks,
...parseVariablesHeaders(typebot, parsedBlocks),
}
}
const parseBlocksResultSample = (typebot: Typebot, blocks: Block[]) =>
blocks
.filter((block) => typebot && block.steps.some((step) => isInputStep(step)))
.reduce<Record<string, string>>((blocks, block) => {
const inputStep = block.steps.find((step) => isInputStep(step))
if (!inputStep || !isInputStep(inputStep)) return blocks
const matchedVariableName =
inputStep.options.variableId &&
typebot.variables.find(byId(inputStep.options.variableId))?.name
const value = getSampleValue(inputStep)
return {
...blocks,
[matchedVariableName ?? block.title]: value,
}
}, {})
const getSampleValue = (step: InputStep) => {
switch (step.type) {
case InputStepType.CHOICE:
return 'Item 1, Item 2, Item3'
case InputStepType.DATE:
return new Date().toUTCString()
case InputStepType.EMAIL:
return 'test@email.com'
case InputStepType.NUMBER:
return '20'
case InputStepType.PHONE:
return '+33665566773'
case InputStepType.TEXT:
return 'answer value'
case InputStepType.URL:
return 'https://test.com'
}
}
const parseVariablesHeaders = (
typebot: Typebot,
parsedBlocks: Record<string, string>
) =>
typebot.variables.reduce<Record<string, string>>((headers, v) => {
if (parsedBlocks[v.name]) return headers
return {
...headers,
[v.name]: 'value',
}
}, {})
const getPreviousBlocks =
(typebot: Typebot) =>
(blockId: string): string[] => {
const previousBlocks = typebot.edges
.map((edge) =>
edge.to.blockId === blockId ? edge.from.blockId : undefined
)
.filter(isDefined)
return previousBlocks.concat(
previousBlocks.flatMap(getPreviousBlocks(typebot))
)
}
export default handler export default handler

View File

@@ -18,7 +18,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const stepId = req.query.stepId.toString() const stepId = req.query.stepId.toString()
const typebot = (await prisma.typebot.findUnique({ const typebot = (await prisma.typebot.findUnique({
where: { id_ownerId: { id: typebotId, ownerId: user.id } }, where: { id_ownerId: { id: typebotId, ownerId: user.id } },
})) as Typebot | undefined })) as unknown as Typebot | undefined
if (!typebot) return res.status(400).send({ message: 'Typebot not found' }) if (!typebot) return res.status(400).send({ message: 'Typebot not found' })
try { try {
const updatedTypebot = addUrlToWebhookStep(url, typebot, stepId) const updatedTypebot = addUrlToWebhookStep(url, typebot, stepId)

View File

@@ -15,7 +15,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const stepId = req.query.stepId.toString() const stepId = req.query.stepId.toString()
const typebot = (await prisma.typebot.findUnique({ const typebot = (await prisma.typebot.findUnique({
where: { id_ownerId: { id: typebotId, ownerId: user.id } }, where: { id_ownerId: { id: typebotId, ownerId: user.id } },
})) as Typebot | undefined })) as unknown as Typebot | undefined
if (!typebot) return res.status(400).send({ message: 'Typebot not found' }) if (!typebot) return res.status(400).send({ message: 'Typebot not found' })
try { try {
const updatedTypebot = removeUrlFromWebhookStep(typebot, stepId) const updatedTypebot = removeUrlFromWebhookStep(typebot, stepId)

View File

@@ -20,7 +20,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
take: limit, take: limit,
include: { answers: true }, include: { answers: true },
})) as unknown as ResultWithAnswers[] })) as unknown as ResultWithAnswers[]
res.send({ results: results.map(parseAnswers(typebot as Typebot)) }) res.send({
results: results.map(parseAnswers(typebot as unknown as Typebot)),
})
} }
methodNotAllowed(res) methodNotAllowed(res)
} }

View File

@@ -74,7 +74,6 @@ const parseTestTypebot = (partialTypebot: Partial<Typebot>): Typebot => ({
ownerId: 'user', ownerId: 'user',
theme: defaultTheme, theme: defaultTheme,
settings: defaultSettings, settings: defaultSettings,
createdAt: new Date(),
publicId: partialTypebot.id + '-public', publicId: partialTypebot.id + '-public',
publishedTypebotId: null, publishedTypebotId: null,
updatedAt: new Date(), updatedAt: new Date(),

View File

@@ -0,0 +1,80 @@
import { Block, InputStep, InputStepType, PublicTypebot, Typebot } from 'models'
import { isInputStep, byId, isDefined } from 'utils'
export const parseSampleResult =
(typebot: Pick<Typebot | PublicTypebot, 'blocks' | 'variables' | 'edges'>) =>
(currentBlockId: string): Record<string, string> => {
const previousBlocks = (typebot.blocks as Block[]).filter((b) =>
getPreviousBlockIds(typebot)(currentBlockId).includes(b.id)
)
const parsedBlocks = parseBlocksResultSample(typebot, previousBlocks)
return {
message: 'This is a sample result, it has been generated ⬇️',
'Submitted at': new Date().toISOString(),
...parsedBlocks,
...parseVariablesHeaders(typebot, parsedBlocks),
}
}
const parseBlocksResultSample = (
typebot: Pick<Typebot | PublicTypebot, 'blocks' | 'variables'>,
blocks: Block[]
) =>
blocks
.filter((block) => typebot && block.steps.some((step) => isInputStep(step)))
.reduce<Record<string, string>>((blocks, block) => {
const inputStep = block.steps.find((step) => isInputStep(step))
if (!inputStep || !isInputStep(inputStep)) return blocks
const matchedVariableName =
inputStep.options.variableId &&
typebot.variables.find(byId(inputStep.options.variableId))?.name
const value = getSampleValue(inputStep)
return {
...blocks,
[matchedVariableName ?? block.title]: value,
}
}, {})
const getSampleValue = (step: InputStep) => {
switch (step.type) {
case InputStepType.CHOICE:
return 'Item 1, Item 2, Item3'
case InputStepType.DATE:
return new Date().toUTCString()
case InputStepType.EMAIL:
return 'test@email.com'
case InputStepType.NUMBER:
return '20'
case InputStepType.PHONE:
return '+33665566773'
case InputStepType.TEXT:
return 'answer value'
case InputStepType.URL:
return 'https://test.com'
}
}
const parseVariablesHeaders = (
typebot: Pick<Typebot | PublicTypebot, 'blocks' | 'variables'>,
parsedBlocks: Record<string, string>
) =>
typebot.variables.reduce<Record<string, string>>((headers, v) => {
if (parsedBlocks[v.name]) return headers
return {
...headers,
[v.name]: 'value',
}
}, {})
const getPreviousBlockIds =
(typebot: Pick<Typebot | PublicTypebot, 'blocks' | 'variables' | 'edges'>) =>
(blockId: string): string[] => {
const previousBlocks = typebot.edges
.map((edge) =>
edge.to.blockId === blockId ? edge.from.blockId : undefined
)
.filter(isDefined)
return previousBlocks.concat(
previousBlocks.flatMap(getPreviousBlockIds(typebot))
)
}

View File

@@ -1,10 +1,6 @@
import { Answer, ResultWithAnswers, VariableWithValue } from 'models' import { Answer, ResultValues, VariableWithValue } from 'models'
import React, { createContext, ReactNode, useContext, useState } from 'react' import React, { createContext, ReactNode, useContext, useState } from 'react'
export type ResultValues = Pick<
ResultWithAnswers,
'answers' | 'createdAt' | 'prefilledVariables'
>
const answersContext = createContext<{ const answersContext = createContext<{
resultValues: ResultValues resultValues: ResultValues
addAnswer: (answer: Answer) => void addAnswer: (answer: Answer) => void

View File

@@ -1,4 +1,3 @@
import { ResultValues } from 'contexts/AnswersContext'
import { import {
IntegrationStep, IntegrationStep,
IntegrationStepType, IntegrationStepType,
@@ -14,9 +13,10 @@ import {
SendEmailStep, SendEmailStep,
PublicBlock, PublicBlock,
ZapierStep, ZapierStep,
ResultValues,
} from 'models' } from 'models'
import { stringify } from 'qs' import { stringify } from 'qs'
import { parseAnswers, sendRequest } from 'utils' import { sendRequest } from 'utils'
import { sendGaEvent } from '../../lib/gtag' import { sendGaEvent } from '../../lib/gtag'
import { sendErrorMessage, sendInfoMessage } from './postMessage' import { sendErrorMessage, sendInfoMessage } from './postMessage'
import { parseVariables, parseVariablesInObject } from './variable' import { parseVariables, parseVariablesInObject } from './variable'
@@ -166,6 +166,8 @@ const executeWebhook = async (
updateVariableValue, updateVariableValue,
typebotId, typebotId,
apiHost, apiHost,
resultValues,
isPreview,
}: IntegrationContext }: IntegrationContext
) => { ) => {
if (!step.webhook) return step.outgoingEdgeId if (!step.webhook) return step.outgoingEdgeId
@@ -174,9 +176,11 @@ const executeWebhook = async (
method: 'POST', method: 'POST',
body: { body: {
variables, variables,
resultValues,
}, },
}) })
console.error(error) console.error(error)
if (isPreview && error) sendErrorMessage(`Webhook failed: ${error.message}`)
step.options.responseVariableMapping.forEach((varMapping) => { step.options.responseVariableMapping.forEach((varMapping) => {
if (!varMapping?.bodyPath || !varMapping.variableId) return if (!varMapping?.bodyPath || !varMapping.variableId) return
const value = safeEval(`(${JSON.stringify(data)}).${varMapping?.bodyPath}`) const value = safeEval(`(${JSON.stringify(data)}).${varMapping?.bodyPath}`)
@@ -186,7 +190,7 @@ const executeWebhook = async (
const sendEmail = async ( const sendEmail = async (
step: SendEmailStep, step: SendEmailStep,
{ variables, apiHost, isPreview, resultValues, blocks }: IntegrationContext { variables, apiHost, isPreview }: IntegrationContext
) => { ) => {
if (isPreview) sendInfoMessage('Emails are not sent in preview mode') if (isPreview) sendInfoMessage('Emails are not sent in preview mode')
if (isPreview) return step.outgoingEdgeId if (isPreview) return step.outgoingEdgeId
@@ -198,15 +202,11 @@ const sendEmail = async (
credentialsId: options.credentialsId, credentialsId: options.credentialsId,
recipients: options.recipients.map(parseVariables(variables)), recipients: options.recipients.map(parseVariables(variables)),
subject: parseVariables(variables)(options.subject ?? ''), subject: parseVariables(variables)(options.subject ?? ''),
body: body: parseVariables(variables)(options.body ?? ''),
options.body === '{{state}}'
? parseAnswers({ variables, blocks })(resultValues)
: parseVariables(variables)(options.body ?? ''),
cc: (options.cc ?? []).map(parseVariables(variables)), cc: (options.cc ?? []).map(parseVariables(variables)),
bcc: (options.bcc ?? []).map(parseVariables(variables)), bcc: (options.bcc ?? []).map(parseVariables(variables)),
}, },
}) })
console.error(error) console.error(error)
if (isPreview && error) sendErrorMessage(`Webhook failed: ${error.message}`)
return step.outgoingEdgeId return step.outgoingEdgeId
} }

View File

@@ -0,0 +1,9 @@
-- AlterTable
ALTER TABLE "DashboardFolder" ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
-- AlterTable
ALTER TABLE "PublicTypebot" ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
-- AlterTable
ALTER TABLE "Result" ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;

View File

@@ -90,6 +90,7 @@ model VerificationToken {
model DashboardFolder { model DashboardFolder {
id String @id @default(cuid()) id String @id @default(cuid())
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
name String name String
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade) owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
ownerId String ownerId String
@@ -104,7 +105,7 @@ model DashboardFolder {
model Typebot { model Typebot {
id String @id @default(cuid()) id String @id @default(cuid())
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @default(now()) updatedAt DateTime @default(now()) @updatedAt
name String name String
ownerId String ownerId String
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade) owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
@@ -125,22 +126,25 @@ model Typebot {
} }
model PublicTypebot { model PublicTypebot {
id String @id @default(cuid()) id String @id @default(cuid())
typebotId String @unique createdAt DateTime @default(now())
typebot Typebot @relation(fields: [typebotId], references: [id], onDelete: Cascade) updatedAt DateTime @default(now()) @updatedAt
typebotId String @unique
typebot Typebot @relation(fields: [typebotId], references: [id], onDelete: Cascade)
name String name String
blocks Json[] blocks Json[]
variables Json[] variables Json[]
edges Json[] edges Json[]
theme Json theme Json
settings Json settings Json
publicId String? @unique publicId String? @unique
customDomain String? @unique customDomain String? @unique
} }
model Result { model Result {
id String @id @default(cuid()) id String @id @default(cuid())
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
typebotId String typebotId String
typebot Typebot @relation(fields: [typebotId], references: [id], onDelete: Cascade) typebot Typebot @relation(fields: [typebotId], references: [id], onDelete: Cascade)
answers Answer[] answers Answer[]

View File

@@ -3,7 +3,13 @@ import { PublicTypebot as PublicTypebotFromPrisma } from 'db'
export type PublicTypebot = Omit< export type PublicTypebot = Omit<
PublicTypebotFromPrisma, PublicTypebotFromPrisma,
'blocks' | 'theme' | 'settings' | 'variables' | 'edges' | 'blocks'
| 'theme'
| 'settings'
| 'variables'
| 'edges'
| 'createdAt'
| 'updatedAt'
> & { > & {
blocks: PublicBlock[] blocks: PublicBlock[]
variables: Variable[] variables: Variable[]

View File

@@ -7,3 +7,8 @@ export type Result = Omit<
> & { createdAt: string; prefilledVariables: VariableWithValue[] } > & { createdAt: string; prefilledVariables: VariableWithValue[] }
export type ResultWithAnswers = Result & { answers: Answer[] } export type ResultWithAnswers = Result & { answers: Answer[] }
export type ResultValues = Pick<
ResultWithAnswers,
'answers' | 'createdAt' | 'prefilledVariables'
>

View File

@@ -6,7 +6,7 @@ import { Variable } from './variable'
export type Typebot = Omit< export type Typebot = Omit<
TypebotFromPrisma, TypebotFromPrisma,
'blocks' | 'theme' | 'settings' | 'variables' | 'edges' 'blocks' | 'theme' | 'settings' | 'variables' | 'edges' | 'createdAt'
> & { > & {
blocks: Block[] blocks: Block[]
variables: Variable[] variables: Variable[]

View File

@@ -34,6 +34,12 @@ export const sendRequest = async <ResponseData>(
const response = await fetch(url, { const response = await fetch(url, {
method: typeof params === 'string' ? 'GET' : params.method, method: typeof params === 'string' ? 'GET' : params.method,
mode: 'cors', mode: 'cors',
headers:
typeof params !== 'string' && isDefined(params.body)
? {
'Content-Type': 'application/json',
}
: undefined,
body: body:
typeof params !== 'string' && isDefined(params.body) typeof params !== 'string' && isDefined(params.body)
? JSON.stringify(params.body) ? JSON.stringify(params.body)