Skip to content

Commit

Permalink
⚡ (setVariable) Add "Environment name" value in Set variable block (#850
Browse files Browse the repository at this point in the history
)

Closes #848
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
### Summary by CodeRabbit

- New Feature: Added "Environment name" as a new value type in the
SetVariable function, allowing users to distinguish between 'web' and
'whatsapp' environments.
- Refactor: Simplified session state handling in `resumeWhatsAppFlow.ts`
for improved code clarity.
- Refactor: Updated `startWhatsAppSession.ts` to include an initial
session state with WhatsApp contact and expiry timeout, enhancing
session management.
- Bug Fix: Improved null handling in `executeSetVariable.ts` for
'Contact name' and 'Phone number', preventing potential issues with
falsy values.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • Loading branch information
baptisteArno authored Sep 26, 2023
1 parent 7b3cbdb commit 1ca742f
Show file tree
Hide file tree
Showing 9 changed files with 58 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ const Expression = ({
case 'Tomorrow':
case 'User ID':
case 'Moment of the day':
case 'Environment name':
case 'Yesterday': {
return (
<Text as="span">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,17 @@ const SetVariableValue = ({
</Alert>
)
}
case 'Environment name': {
return (
<Alert fontSize="sm">
<AlertIcon />
<Text>
Will return either <Tag size="sm">web</Tag> or{' '}
<Tag size="sm">whatsapp</Tag>.
</Text>
</Alert>
)
}
case 'Contact name':
case 'Phone number':
case 'Random ID':
Expand Down
7 changes: 7 additions & 0 deletions apps/docs/openapi/builder/_spec_.json
Original file line number Diff line number Diff line change
Expand Up @@ -1979,6 +1979,7 @@
"enum": [
"Custom",
"Empty",
"Environment name",
"User ID",
"Now",
"Today",
Expand Down Expand Up @@ -6367,6 +6368,7 @@
"enum": [
"Custom",
"Empty",
"Environment name",
"User ID",
"Now",
"Today",
Expand Down Expand Up @@ -10396,6 +10398,7 @@
"enum": [
"Custom",
"Empty",
"Environment name",
"User ID",
"Now",
"Today",
Expand Down Expand Up @@ -14565,6 +14568,7 @@
"enum": [
"Custom",
"Empty",
"Environment name",
"User ID",
"Now",
"Today",
Expand Down Expand Up @@ -18614,6 +18618,7 @@
"enum": [
"Custom",
"Empty",
"Environment name",
"User ID",
"Now",
"Today",
Expand Down Expand Up @@ -22718,6 +22723,7 @@
"enum": [
"Custom",
"Empty",
"Environment name",
"User ID",
"Now",
"Today",
Expand Down Expand Up @@ -26885,6 +26891,7 @@
"enum": [
"Custom",
"Empty",
"Environment name",
"User ID",
"Now",
"Today",
Expand Down
1 change: 1 addition & 0 deletions apps/docs/openapi/chat/_spec_.json
Original file line number Diff line number Diff line change
Expand Up @@ -1574,6 +1574,7 @@
"enum": [
"Custom",
"Empty",
"Environment name",
"User ID",
"Now",
"Today",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,11 @@ const getExpressionToEvaluate =
(options: SetVariableBlock['options']): string | null => {
switch (options.type) {
case 'Contact name':
return state.whatsApp?.contact.name ?? ''
case 'Phone number':
return `"${state.whatsApp?.contact.phoneNumber}"` ?? ''
return state.whatsApp?.contact.name ?? null
case 'Phone number': {
const phoneNumber = state.whatsApp?.contact.phoneNumber
return phoneNumber ? `"${state.whatsApp?.contact.phoneNumber}"` : null
}
case 'Now':
case 'Today':
return 'new Date().toISOString()'
Expand Down Expand Up @@ -112,6 +114,9 @@ const getExpressionToEvaluate =
if(now.getHours() >= 18) return 'evening'
if(now.getHours() >= 22 || now.getHours() < 6) return 'night'`
}
case 'Environment name': {
return state.whatsApp ? 'whatsapp' : 'web'
}
case 'Custom':
case undefined: {
return options.expressionToEvaluate ?? null
Expand Down
3 changes: 3 additions & 0 deletions packages/bot-engine/startSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,13 @@ import { injectVariablesFromExistingResult } from './variables/injectVariablesFr
type Props = {
startParams: StartParams
userId: string | undefined
initialSessionState?: Pick<SessionState, 'whatsApp' | 'expiryTimeout'>
}

export const startSession = async ({
startParams,
userId,
initialSessionState,
}: Props): Promise<ChatReply & { newSessionState: SessionState }> => {
if (!startParams)
throw new TRPCError({
Expand Down Expand Up @@ -108,6 +110,7 @@ export const startSession = async ({
dynamicTheme: parseDynamicThemeInState(typebot.theme),
isStreamEnabled: startParams.isStreamEnabled,
typingEmulation: typebot.settings.typingEmulation,
...initialSessionState,
}

if (startParams.isOnlyRegistering) {
Expand Down
14 changes: 2 additions & 12 deletions packages/bot-engine/whatsapp/resumeWhatsAppFlow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,6 @@ export const resumeWhatsAppFlow = async ({
typebotId: typebot?.id,
})

const sessionState =
isPreview && session?.state
? ({
...session?.state,
whatsApp: {
contact,
},
} satisfies SessionState)
: session?.state

const credentials = await getCredentials({ credentialsId, isPreview })

if (!credentials) {
Expand All @@ -71,8 +61,8 @@ export const resumeWhatsAppFlow = async ({
session?.updatedAt.getTime() + session.state.expiryTimeout < Date.now()

const resumeResponse =
sessionState && !isSessionExpired
? await continueBotFlow(sessionState)(messageContent)
session && !isSessionExpired
? await continueBotFlow(session.state)(messageContent)
: workspaceId
? await startWhatsAppSession({
incomingMessage: messageContent,
Expand Down
46 changes: 24 additions & 22 deletions packages/bot-engine/whatsapp/startWhatsAppSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
} from '@typebot.io/schemas'
import {
WhatsAppCredentials,
WhatsAppIncomingMessage,
defaultSessionExpiryTimeout,
} from '@typebot.io/schemas/features/whatsapp'
import { isInputBlock, isNotDefined } from '@typebot.io/lib/utils'
Expand Down Expand Up @@ -73,47 +72,50 @@ export const startWhatsAppSession = async ({

if (isNotDefined(publicTypebot)) return

let session = await startSession({
const sessionExpiryTimeoutHours =
publicTypebot.settings.whatsApp?.sessionExpiryTimeout ??
defaultSessionExpiryTimeout

const session = await startSession({
startParams: {
typebot: publicTypebot.typebot.publicId as string,
},
userId: undefined,
initialSessionState: {
whatsApp: {
contact,
},
expiryTimeout: sessionExpiryTimeoutHours * 60 * 60 * 1000,
},
})

let newSessionState: SessionState = session.newSessionState

// If first block is an input block, we can directly continue the bot flow
const firstEdgeId =
session.newSessionState.typebotsQueue[0].typebot.groups[0].blocks[0]
.outgoingEdgeId
const nextGroup = await getNextGroup(session.newSessionState)(firstEdgeId)
newSessionState.typebotsQueue[0].typebot.groups[0].blocks[0].outgoingEdgeId
const nextGroup = await getNextGroup(newSessionState)(firstEdgeId)
const firstBlock = nextGroup.group?.blocks.at(0)
if (firstBlock && isInputBlock(firstBlock)) {
const resultId = session.newSessionState.typebotsQueue[0].resultId
const resultId = newSessionState.typebotsQueue[0].resultId
if (resultId)
await upsertResult({
hasStarted: true,
isCompleted: false,
resultId,
typebot: session.newSessionState.typebotsQueue[0].typebot,
typebot: newSessionState.typebotsQueue[0].typebot,
})
session = await continueBotFlow({
...session.newSessionState,
currentBlock: { groupId: firstBlock.groupId, blockId: firstBlock.id },
})(incomingMessage)
newSessionState = (
await continueBotFlow({
...newSessionState,
currentBlock: { groupId: firstBlock.groupId, blockId: firstBlock.id },
})(incomingMessage)
).newSessionState
}

const sessionExpiryTimeoutHours =
publicTypebot.settings.whatsApp?.sessionExpiryTimeout ??
defaultSessionExpiryTimeout

return {
...session,
newSessionState: {
...session.newSessionState,
whatsApp: {
contact,
},
expiryTimeout: sessionExpiryTimeoutHours * 60 * 60 * 1000,
},
newSessionState,
}
}

Expand Down
1 change: 1 addition & 0 deletions packages/schemas/features/blocks/logic/setVariable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { LogicBlockType } from './enums'
export const valueTypes = [
'Custom',
'Empty',
'Environment name',
'User ID',
'Now',
'Today',
Expand Down

4 comments on commit 1ca742f

@vercel
Copy link

@vercel vercel bot commented on 1ca742f Sep 26, 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 1ca742f Sep 26, 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.typebot.io
docs-git-main-typebot-io.vercel.app

@vercel
Copy link

@vercel vercel bot commented on 1ca742f Sep 26, 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-git-main-typebot-io.vercel.app
builder-v2-typebot-io.vercel.app
app.typebot.io

@vercel
Copy link

@vercel vercel bot commented on 1ca742f Sep 26, 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

blazecontrol.com.br
bot.boston-voip.com
bot.cabinpromos.com
bot.carnaval.studio
bot.digitalbled.com
bot.dsignagency.com
bot.enthrallart.com
bot.eventhub.com.au
bot.febredojogo.com
bot.gravityatoms.in
bot.jepierre.com.br
bot.jogodoandre.com
bot.jogomoderno.com
bot.leadgenpod.site
bot.ltmidias.com.br
bot.viralsangat.com
bot.winglabs.com.br
capitaldigital.live
carsalesenquiry.com
casahackeada.online
chat.marius.digital
chat.mosdent.com.tr
chat.sr7digital.com
chatbot.matthesv.de
chatbot.repplai.com
chatwebandreia.site
co.onewebcenter.com
cr.onewebcenter.com
demo.botscientis.us
demo.wemakebots.xyz
feiralimpanomes.com
go.onewebcenter.com
gv.onewebcenter.com
hrbot.robomotion.io
inearephones.cr8.ai
joaomigowski.com.br
kbsub.wpwakanda.com
limitenahora.com.br
live.botscientis.us
mentoria.omelhor.vc
messengerbet.online
noticiariododia.com
nutrisamirbayde.com
online.onlinmey.com
order.maitempah.com
portaldosganhos.com
query.forgetsql.com
quest.wpwakanda.com
se.onewebcenter.com
secretespiao.online
start.belenmotz.com
support.wawplus.com
survey1.digienge.io
surveys.essiell.com
test.botscientis.us
test.getreview.help
test.reventepro.com
typebot.stillio.app
typebot.stillio.com
vg.onewebcenter.com
viewer-v2-typebot-io.vercel.app
mdb.assessoria.desideri.progenbr.com
mdb.assessoria.fernanda.progenbr.com
mdb.assessoria.jbatista.progenbr.com
mdb.assessoria.mauricio.progenbr.com
mdb.evento.autocadastro.progenbr.com
form.shopmercedesbenzsouthorlando.com
mdb.evento.equipeinterna.progenbr.com
bot.studiotecnicoimmobiliaremerelli.it
mdb.assessoria.boaventura.progenbr.com
mdb.assessoria.jtrebesqui.progenbr.com
pesquisa.escolamodacomproposito.com.br
anamnese.clinicaramosodontologia.com.br
gabinete.baleia.formulario.progenbr.com
mdb.assessoria.carreirinha.progenbr.com
chrome-os-inquiry-system.itschromeos.com
mdb.assessoria.paulomarques.progenbr.com
viewer-v2-git-main-typebot-io.vercel.app
main-menu-for-itschromeos.itschromeos.com
mdb.assessoria.qrcode.ademir.progenbr.com
mdb.assessoria.qrcode.arthur.progenbr.com
mdb.assessoria.qrcode.danilo.progenbr.com
mdb.assessoria.qrcode.marcao.progenbr.com
mdb.assessoria.qrcode.marcio.progenbr.com
mdb.assessoria.qrcode.aloisio.progenbr.com
mdb.assessoria.qrcode.girotto.progenbr.com
mdb.assessoria.qrcode.marinho.progenbr.com
mdb.assessoria.qrcode.rodrigo.progenbr.com
mdb.assessoria.carlosalexandre.progenbr.com
mdb.assessoria.qrcode.desideri.progenbr.com
mdb.assessoria.qrcode.fernanda.progenbr.com
mdb.assessoria.qrcode.jbatista.progenbr.com
mdb.assessoria.qrcode.mauricio.progenbr.com
mdb.assessoria.fernanda.regional.progenbr.com
mdb.assessoria.qrcode.boaventura.progenbr.com
mdb.assessoria.qrcode.jtrebesqui.progenbr.com
mdb.assessoria.qrcode.carreirinha.progenbr.com
mdb.assessoria.qrcode.paulomarques.progenbr.com
mdb.assessoria.qrcode.carlosalexandre.progenbr.com
mdb.assessoria.qrcode.fernanda.regional.progenbr.com

Please sign in to comment.