Skip to content

Commit

Permalink
⚡ (chatwoot) Add result URL custom attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
baptisteArno committed Apr 25, 2023
1 parent 3529da2 commit c09a840
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 29 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { Stack } from '@chakra-ui/react'
import React, { useState } from 'react'
import React, { useEffect, useState } from 'react'
import { LogsModal } from './LogsModal'
import { useTypebot } from '@/features/editor/providers/TypebotProvider'
import { useResults } from '../ResultsProvider'
import { ResultModal } from './ResultModal'
import { ResultsTable } from './table/ResultsTable'
import { useRouter } from 'next/router'

export const ResultsTableContainer = () => {
const { query } = useRouter()
const {
flatResults: results,
fetchNextPage,
Expand Down Expand Up @@ -34,6 +36,10 @@ export const ResultsTableContainer = () => {
setExpandedResultId(results[index].id)
}

useEffect(() => {
if (query.id) setExpandedResultId(query.id as string)
}, [query.id])

return (
<Stack pb="28" px={['4', '0']} spacing="4" maxW="1600px" w="full">
{publishedTypebot && (
Expand Down
13 changes: 13 additions & 0 deletions apps/docs/docs/editor/blocks/integrations/chatwoot.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,16 @@ To find your website token, head over to Chatwoot in your Inbox settings:
You can prefill user information by adding collected variables to the "Set user details" inputs.

For example, if you set the "Email" input to "john@gmail.com" then Chatwoot will automatically associate this email to the current user.

## Custom attributes

You can add these custom attributes that Typebot will automatically fill in for you:

### Result URL

You can link the current result URL to the Chatwoot conversation by creating this custom attribute:

<img
src="/img/blocks/integrations/chatwoot/custom-attribute.png"
alt="Chatwoot custom attribute"
/>
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,47 @@ import { ExecuteIntegrationResponse } from '@/features/chat/types'
import { extractVariablesFromText } from '@/features/variables/extractVariablesFromText'
import { parseGuessedValueType } from '@/features/variables/parseGuessedValueType'
import { parseVariables } from '@/features/variables/parseVariables'
import { isDefined } from '@typebot.io/lib'
import {
ChatwootBlock,
ChatwootOptions,
SessionState,
} from '@typebot.io/schemas'

const parseSetUserCode = (user: ChatwootOptions['user']) => `
window.$chatwoot.setUser("${user?.id ?? ''}", {
email: ${user?.email ? `"${user.email}"` : 'undefined'},
name: ${user?.name ? `"${user.name}"` : 'undefined'},
avatar_url: ${user?.avatarUrl ? `"${user.avatarUrl}"` : 'undefined'},
phone_number: ${user?.phoneNumber ? `"${user.phoneNumber}"` : 'undefined'},
});
const parseSetUserCode = (user: ChatwootOptions['user'], resultId: string) =>
user?.email || user?.id
? `
window.$chatwoot.setUser(${user?.id ?? `"${resultId}"`}, {
email: ${user?.email ? user.email : 'undefined'},
name: ${user?.name ? user.name : 'undefined'},
avatar_url: ${user?.avatarUrl ? user.avatarUrl : 'undefined'},
phone_number: ${user?.phoneNumber ? user.phoneNumber : 'undefined'},
});`
: ''

`
const parseChatwootOpenCode = ({
baseUrl,
websiteToken,
user,
}: ChatwootOptions) => `
if (window.$chatwoot) {
if(${Boolean(user)}) {
${parseSetUserCode(user)}
}
resultId,
typebotId,
}: ChatwootOptions & { typebotId: string; resultId: string }) => {
const openChatwoot = `${parseSetUserCode(user, resultId)}
window.$chatwoot.setCustomAttributes({
typebot_result_url: "${
process.env.NEXTAUTH_URL
}/typebots/${typebotId}/results?id=${resultId}",
});
window.$chatwoot.toggle("open");
} else {
`

return `
window.addEventListener("chatwoot:error", function (error) {
console.log(error);
});
if (window.$chatwoot) {${openChatwoot}}
else {
(function (d, t) {
var BASE_URL = "${baseUrl}";
var g = d.createElement(t),
Expand All @@ -41,15 +56,11 @@ if (window.$chatwoot) {
websiteToken: "${websiteToken}",
baseUrl: BASE_URL,
});
window.addEventListener("chatwoot:ready", function () {
if(${Boolean(user?.id || user?.email)}) {
${parseSetUserCode(user)}
}
window.$chatwoot.toggle("open");
});
window.addEventListener("chatwoot:ready", function () {${openChatwoot}});
};
})(document, "script");
}`
}

const chatwootCloseCode = `
if (window.$chatwoot) {
Expand All @@ -59,28 +70,31 @@ if (window.$chatwoot) {
`

export const executeChatwootBlock = (
{ typebot: { variables }, result }: SessionState,
{ typebot, result }: SessionState,
block: ChatwootBlock,
lastBubbleBlockId?: string
): ExecuteIntegrationResponse => {
const isPreview = !result.id
const chatwootCode =
block.options.task === 'Close widget'
? chatwootCloseCode
: isPreview
? ''
: parseChatwootOpenCode(block.options)
: isDefined(result.id)
? parseChatwootOpenCode({
...block.options,
typebotId: typebot.id,
resultId: result.id,
})
: ''
return {
outgoingEdgeId: block.outgoingEdgeId,
clientSideActions: [
{
lastBubbleBlockId,
chatwoot: {
scriptToExecute: {
content: parseVariables(variables, { fieldToParse: 'id' })(
content: parseVariables(typebot.variables, { fieldToParse: 'id' })(
chatwootCode
),
args: extractVariablesFromText(variables)(chatwootCode).map(
args: extractVariablesFromText(typebot.variables)(chatwootCode).map(
(variable) => ({
id: variable.id,
value: parseGuessedValueType(variable.value),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ export const extractVariablesFromText =
const variable = variables.find(
(variable) => variable.name === variableName
)
if (!variable) return acc
if (
!variable ||
acc.find((accVariable) => accVariable.id === variable.id)
)
return acc
return [...acc, variable]
}, [])
}

4 comments on commit c09a840

@vercel
Copy link

@vercel vercel bot commented on c09a840 Apr 25, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on c09a840 Apr 25, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

builder-v2 – ./apps/builder

builder-v2-typebot-io.vercel.app
builder-v2-git-main-typebot-io.vercel.app
app.typebot.io

@vercel
Copy link

@vercel vercel bot commented on c09a840 Apr 25, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

docs – ./apps/docs

docs-typebot-io.vercel.app
docs-git-main-typebot-io.vercel.app
docs.typebot.io

@vercel
Copy link

@vercel vercel bot commented on c09a840 Apr 25, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

viewer-v2 – ./apps/viewer

sakuranembro.it
typebot.aloe.do
bot.contakit.com
bot.piccinato.co
bot.sv-energy.it
botc.ceox.com.br
clo.closeer.work
cockroach.cr8.ai
faqs.nigerias.io
form.syncwin.com
haymanevents.com
kw.wpwakanda.com
myrentalhost.com
stan.vselise.com
start.taxtree.io
typebot.aloe.bot
voicehelp.cr8.ai
zap.fundviser.in
app.bouclidom.com
app.chatforms.net
bot.hostnation.de
bot.maitempah.com
bot.phuonghub.com
bot.reviewzer.com
bot.rihabilita.it
cares.urlabout.me
chat.gaswadern.de
chat.rojie.online
fmm.wpwakanda.com
footballmeetup.ie
gentleman-shop.fr
k1.kandabrand.com
kp.pedroknoll.com
lb.ticketfute.com
ov1.wpwakanda.com
ov2.wpwakanda.com
ov3.wpwakanda.com
support.triplo.ai
viewer.typebot.io
welcome.triplo.ai
1988.bouclidom.com
andreimayer.com.br
bot.danyservice.it
bot.iconicbrows.it
bot.lucide.contact
bot.megafox.com.br
bot.neferlopez.com
bots.robomotion.io
sbutton.wpwakanda.com
test.leadbooster.help
815639944.21000000.one
83720273.bouclidom.com
mainmenu1one.wpwakanda.com
newsletter.itshcormeos.com
rsvp.virtuesocialmedia.com
tarian.theiofoundation.org
ted.meujalecobrasil.com.br
type.dericsoncalari.com.br
bot.pinpointinteractive.com
bot.polychromes-project.com
bot.seidinembroseanchetu.it
chat.semanalimpanome.com.br
designguide.techyscouts.com
liveconvert2.kandalearn.com
presente.empresarias.com.mx
register.algorithmpress.com
sell.sellthemotorhome.co.uk
anamnese.odontopavani.com.br
austin.channelautomation.com
bot.marketingplusmindset.com
bot.seidibergamoseanchetu.it
desabafe.sergiolimajr.com.br
download.venturemarketing.in
piazzatorre.barrettamario.it
type.cookieacademyonline.com
upload.atlasoutfittersk9.com
bot.brigadeirosemdrama.com.br
forms.escoladeautomacao.com.br
onboarding.libertydreamcare.ie
type.talitasouzamarques.com.br
agendamento.sergiolimajr.com.br
anamnese.clinicamegasjdr.com.br
bookings.littlepartymonkeys.com
bot.comercializadoraomicron.com
elevateyourmind.groovepages.com
viewer-v2-typebot-io.vercel.app
yourfeedback.comebackreward.com
bot.cabin-rentals-of-georgia.net
gerador.verificadordehospedes.com
personal-trainer.barrettamario.it
preagendamento.sergiolimajr.com.br
studiotecnicoimmobiliaremerelli.it
download.thailandmicespecialist.com
register.thailandmicespecialist.com
bot.studiotecnicoimmobiliaremerelli.it
pesquisa.escolamodacomproposito.com.br
anamnese.clinicaramosodontologia.com.br
chrome-os-inquiry-system.itschromeos.com
viewer-v2-git-main-typebot-io.vercel.app
main-menu-for-itschromeos.itschromeos.com

Please sign in to comment.