Skip to content

Commit

Permalink
🐛 Fix delete session with client side actions
Browse files Browse the repository at this point in the history
  • Loading branch information
baptisteArno committed Aug 29, 2023
1 parent b852b4a commit 013c7a6
Show file tree
Hide file tree
Showing 10 changed files with 55 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ export const sendWhatsAppInitialMessage = authenticatedProcedure
async ({ input: { to, typebotId, startGroupId }, ctx: { user } }) => {
const apiToken = await prisma.apiToken.findFirst({
where: { ownerId: user.id },
select: {
token: true,
},
})
if (!apiToken)
throw new TRPCError({
Expand Down
6 changes: 2 additions & 4 deletions apps/builder/src/features/preview/components/RuntimeMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
Text,
} from '@chakra-ui/react'
import { runtimes } from '../data'
import { getFeatureFlags } from '@/features/telemetry/posthog'
import { isWhatsAppAvailable } from '@/features/telemetry/posthog'

type Runtime = (typeof runtimes)[number]

Expand Down Expand Up @@ -38,9 +38,7 @@ export const RuntimeMenu = ({ selectedRuntime, onSelectRuntime }: Props) => {
{runtimes
.filter((runtime) => runtime.name !== selectedRuntime.name)
.filter((runtime) =>
runtime.name === 'WhatsApp'
? getFeatureFlags().includes('whatsApp')
: true
runtime.name === 'WhatsApp' ? isWhatsAppAvailable() : true
)
.map((runtime) => (
<MenuItem
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ import { NextjsModal } from './modals/Nextjs/NextjsModal'
import { WhatsAppLogo } from '@/components/logos/WhatsAppLogo'
import { WhatsAppModal } from './modals/WhatsAppModal/WhatsAppModal'
import { ParentModalProvider } from '@/features/graph/providers/ParentModalProvider'
import { getFeatureFlags } from '@/features/telemetry/posthog'
import { isWhatsAppAvailable } from '@/features/telemetry/posthog'

export type ModalProps = {
publicId: string
Expand Down Expand Up @@ -84,7 +84,7 @@ export const EmbedButton = ({

export const integrationsList = [
(props: Pick<ModalProps, 'publicId' | 'isPublished'>) => {
if (getFeatureFlags().includes('whatsApp'))
if (isWhatsAppAvailable())
return (
<ParentModalProvider>
<EmbedButton
Expand Down
12 changes: 7 additions & 5 deletions apps/builder/src/features/telemetry/posthog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ export const identifyUser = (userId: string) => {
posthog.identify(userId)
}

export const getFeatureFlags = () => {
return posthog.__loaded &&
posthog.isFeatureEnabled('whatsApp', { send_event: false })
? ['whatsApp']
: []
export const isWhatsAppAvailable = () => {
if (!env.NEXT_PUBLIC_POSTHOG_KEY || !posthog) return true
const isWhatsAppEnabled = posthog.getFeatureFlag('whatsApp', {
send_event: false,
})
if (isWhatsAppEnabled === undefined) return true
return posthog.__loaded && isWhatsAppEnabled
}

export { posthog }
8 changes: 7 additions & 1 deletion apps/viewer/src/features/chat/api/sendMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
chatReplySchema,
sendMessageInputSchema,
} from '@typebot.io/schemas/features/chat/schema'
import { TRPCError } from '@trpc/server'

export const sendMessage = publicProcedure
.meta({
Expand All @@ -30,6 +31,11 @@ export const sendMessage = publicProcedure
const session = sessionId ? await getSession(sessionId) : null

if (!session) {
if (!startParams)
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'Missing startParams',
})
const {
typebot,
messages,
Expand All @@ -39,7 +45,7 @@ export const sendMessage = publicProcedure
logs,
clientSideActions,
newSessionState,
} = await startSession(startParams, user?.id)
} = await startSession({ startParams, userId: user?.id })

const allLogs = clientLogs ? [...(logs ?? []), ...clientLogs] : logs

Expand Down
5 changes: 4 additions & 1 deletion apps/viewer/src/features/chat/helpers/saveStateToDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ export const saveStateToDatabase = async ({
clientSideActions,
}: Props) => {
const containsSetVariableClientSideAction = clientSideActions?.some(
(action) => 'setVariable' in action
(action) =>
'setVariable' in action ||
'webhookToExecute' in action ||
'streamOpenAiChatCompletion' in action
)

const isCompleted = Boolean(!input && !containsSetVariableClientSideAction)
Expand Down
13 changes: 9 additions & 4 deletions apps/viewer/src/features/chat/helpers/startSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,15 @@ import parse, { NodeType } from 'node-html-parser'
import { parseDynamicTheme } from './parseDynamicTheme'
import { env } from '@typebot.io/env'

export const startSession = async (
startParams?: StartParams,
userId?: string
): Promise<ChatReply & { newSessionState: SessionState }> => {
type Props = {
startParams: StartParams
userId: string | undefined
}

export const startSession = async ({
startParams,
userId,
}: Props): Promise<ChatReply & { newSessionState: SessionState }> => {
if (!startParams)
throw new TRPCError({
code: 'BAD_REQUEST',
Expand Down
11 changes: 7 additions & 4 deletions apps/viewer/src/features/whatsApp/api/startWhatsAppPreview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,13 @@ export const startWhatsAppPreview = publicProcedure

const { newSessionState, messages, input, clientSideActions, logs } =
await startSession({
isOnlyRegistering: !canSendDirectMessagesToUser,
typebot: typebotId,
isPreview: true,
startGroupId,
startParams: {
isOnlyRegistering: !canSendDirectMessagesToUser,
typebot: typebotId,
isPreview: true,
startGroupId,
},
userId: user.id,
})

if (canSendDirectMessagesToUser) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,10 @@ export const startWhatsAppSession = async ({
if (credentials.phoneNumberId !== phoneNumberId) return

const session = await startSession({
typebot: publicTypebot.typebot.publicId as string,
startParams: {
typebot: publicTypebot.typebot.publicId as string,
},
userId: undefined,
})

return {
Expand Down
14 changes: 10 additions & 4 deletions apps/viewer/src/helpers/server/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,18 @@ const getAuthenticatedUser = async (
}

const authenticateByToken = async (
apiToken: string
token: string
): Promise<User | undefined> => {
if (typeof window !== 'undefined') return
return (await prisma.user.findFirst({
where: { apiTokens: { some: { token: apiToken } } },
})) as User
const apiToken = await prisma.apiToken.findFirst({
where: {
token,
},
select: {
owner: true,
},
})
return apiToken?.owner
}

const extractBearerToken = (req: NextApiRequest) =>
Expand Down

4 comments on commit 013c7a6

@vercel
Copy link

@vercel vercel bot commented on 013c7a6 Aug 29, 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-git-main-typebot-io.vercel.app
docs-typebot-io.vercel.app
docs.typebot.io

@vercel
Copy link

@vercel vercel bot commented on 013c7a6 Aug 29, 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 013c7a6 Aug 29, 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 013c7a6 Aug 29, 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

panther.cr7.ai
panther.cr8.ai
pay.sifuim.com
penguin.cr8.ai
segredomeu.com
talk.gocare.io
test.bot.gives
ticketfute.com
unicorn.cr8.ai
whats-app.chat
apo.nigerias.io
apr.nigerias.io
ov2.wpwakanda.com
ov3.wpwakanda.com
pcb.drapamela.com
redeemchatgpt.com
softwarelucra.com
support.triplo.ai
test.eqfeqfeq.com
viewer.typebot.io
welcome.triplo.ai
www.thegymgame.it
zeropendencia.com
1988.bouclidom.com
a.onewebcenter.com
amancarseat.online
amostra-safe.click
andreimayer.com.br
bebesemcolicas.com
bot.innovacion.fun
bot.lucide.contact
bot.neferlopez.com
bot.photonative.de
bot.samplehunt.com
bot.sinalcerto.com
bot.wphelpchat.com
bots.robomotion.io
cadu.uninta.edu.br
chat.hand-made.one
chat.tuanpakya.com
chat.webisharp.com
chatbotforthat.com
descobrindotudo.me
dicanatural.online
digitalhelp.com.au
draraquelnutri.com
drcarlosyoshi.site
goalsettingbot.com
leads.gecoelho.com
noticiasnet.online
novoappespiao.site
omarcodosanjos.com
pant.maxbot.com.br
pantherview.cr8.ai
positivobra.com.br
rollingball.cr8.ai
speciallife.com.br
sub.yolozeeeer.com
survey.digienge.io
tribe.ezbooking.ai
w.onewebcenter.com
zap.techadviser.in
viewer-v2-typebot-io.vercel.app
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.