2023-01-16 12:13:21 +01:00
|
|
|
import { TRPCError } from '@trpc/server'
|
2023-03-15 08:35:16 +01:00
|
|
|
import { ChatReply, SessionState } from '@typebot.io/schemas'
|
2022-11-29 10:02:40 +01:00
|
|
|
import { executeGroup } from './executeGroup'
|
|
|
|
|
import { getNextGroup } from './getNextGroup'
|
|
|
|
|
|
2023-10-06 10:14:26 +02:00
|
|
|
type Props = {
|
|
|
|
|
version: 1 | 2
|
|
|
|
|
state: SessionState
|
2023-01-16 12:13:21 +01:00
|
|
|
startGroupId?: string
|
2023-10-06 10:14:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const startBotFlow = async ({
|
|
|
|
|
version,
|
|
|
|
|
state,
|
|
|
|
|
startGroupId,
|
|
|
|
|
}: Props): Promise<ChatReply & { newSessionState: SessionState }> => {
|
2023-09-29 11:23:04 +02:00
|
|
|
let newSessionState = state
|
2023-01-16 12:13:21 +01:00
|
|
|
if (startGroupId) {
|
2023-08-24 07:48:30 +02:00
|
|
|
const group = state.typebotsQueue[0].typebot.groups.find(
|
2023-01-16 12:13:21 +01:00
|
|
|
(group) => group.id === startGroupId
|
|
|
|
|
)
|
|
|
|
|
if (!group)
|
|
|
|
|
throw new TRPCError({
|
|
|
|
|
code: 'BAD_REQUEST',
|
|
|
|
|
message: "startGroupId doesn't exist",
|
|
|
|
|
})
|
2023-10-06 10:14:26 +02:00
|
|
|
return executeGroup(group, { version, state: newSessionState })
|
2023-01-16 12:13:21 +01:00
|
|
|
}
|
2023-08-24 07:48:30 +02:00
|
|
|
const firstEdgeId =
|
2023-09-29 11:23:04 +02:00
|
|
|
newSessionState.typebotsQueue[0].typebot.groups[0].blocks[0].outgoingEdgeId
|
|
|
|
|
if (!firstEdgeId) return { messages: [], newSessionState }
|
|
|
|
|
const nextGroup = await getNextGroup(newSessionState)(firstEdgeId)
|
|
|
|
|
newSessionState = nextGroup.newSessionState
|
|
|
|
|
if (!nextGroup.group) return { messages: [], newSessionState }
|
2023-10-06 10:14:26 +02:00
|
|
|
return executeGroup(nextGroup.group, { version, state: newSessionState })
|
2022-11-29 10:02:40 +01:00
|
|
|
}
|