feat(editor): ✨ Add send email integration
This commit is contained in:
@ -339,3 +339,10 @@ export const EyeIcon = (props: IconProps) => (
|
||||
<circle cx="12" cy="12" r="3"></circle>
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const SendEmailIcon = (props: IconProps) => (
|
||||
<Icon viewBox="0 0 24 24" {...featherIconsBaseProps} {...props}>
|
||||
<line x1="22" y1="2" x2="11" y2="13"></line>
|
||||
<polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
|
||||
</Icon>
|
||||
)
|
||||
|
@ -13,6 +13,7 @@ import {
|
||||
ImageIcon,
|
||||
NumberIcon,
|
||||
PhoneIcon,
|
||||
SendEmailIcon,
|
||||
TextIcon,
|
||||
WebhookIcon,
|
||||
} from 'assets/icons'
|
||||
@ -61,7 +62,9 @@ export const StepIcon = ({ type, ...props }: StepIconProps) => {
|
||||
case IntegrationStepType.GOOGLE_ANALYTICS:
|
||||
return <GoogleAnalyticsLogo {...props} />
|
||||
case IntegrationStepType.WEBHOOK:
|
||||
return <WebhookIcon />
|
||||
return <WebhookIcon {...props} />
|
||||
case IntegrationStepType.EMAIL:
|
||||
return <SendEmailIcon {...props} />
|
||||
case 'start':
|
||||
return <FlagIcon {...props} />
|
||||
default:
|
||||
|
@ -51,6 +51,8 @@ export const StepTypeLabel = ({ type }: Props) => {
|
||||
)
|
||||
case IntegrationStepType.WEBHOOK:
|
||||
return <Text>Webhook</Text>
|
||||
case IntegrationStepType.EMAIL:
|
||||
return <Text>Email</Text>
|
||||
default:
|
||||
return <></>
|
||||
}
|
||||
|
@ -11,14 +11,15 @@ import {
|
||||
import { ChevronLeftIcon, PlusIcon } from 'assets/icons'
|
||||
import React, { useEffect, useMemo } from 'react'
|
||||
import { useUser } from 'contexts/UserContext'
|
||||
import { CredentialsType } from 'db'
|
||||
import { useRouter } from 'next/router'
|
||||
import { CredentialsType } from 'models'
|
||||
|
||||
type Props = Omit<MenuButtonProps, 'type'> & {
|
||||
type: CredentialsType
|
||||
currentCredentialsId?: string
|
||||
onCredentialsSelect: (credentialId: string) => void
|
||||
onCreateNewClick: () => void
|
||||
defaultCredentialLabel?: string
|
||||
}
|
||||
|
||||
export const CredentialsDropdown = ({
|
||||
@ -26,11 +27,14 @@ export const CredentialsDropdown = ({
|
||||
currentCredentialsId,
|
||||
onCredentialsSelect,
|
||||
onCreateNewClick,
|
||||
defaultCredentialLabel,
|
||||
...props
|
||||
}: Props) => {
|
||||
const router = useRouter()
|
||||
const { credentials } = useUser()
|
||||
|
||||
const defaultCredentialsLabel = defaultCredentialLabel ?? `Select an account`
|
||||
|
||||
const credentialsList = useMemo(() => {
|
||||
return credentials.filter((credential) => credential.type === type)
|
||||
}, [type, credentials])
|
||||
@ -70,11 +74,22 @@ export const CredentialsDropdown = ({
|
||||
{...props}
|
||||
>
|
||||
<Text isTruncated overflowY="visible" h="20px">
|
||||
{currentCredential ? currentCredential.name : 'Select an account'}
|
||||
{currentCredential ? currentCredential.name : defaultCredentialsLabel}
|
||||
</Text>
|
||||
</MenuButton>
|
||||
<MenuList maxW="500px">
|
||||
<Stack maxH={'35vh'} overflowY="scroll" spacing="0">
|
||||
{defaultCredentialLabel && (
|
||||
<MenuItem
|
||||
maxW="500px"
|
||||
overflow="hidden"
|
||||
whiteSpace="nowrap"
|
||||
textOverflow="ellipsis"
|
||||
onClick={handleMenuItemClick('default')}
|
||||
>
|
||||
{defaultCredentialLabel}
|
||||
</MenuItem>
|
||||
)}
|
||||
{credentialsList.map((credentials) => (
|
||||
<MenuItem
|
||||
key={credentials.id}
|
||||
|
@ -34,6 +34,7 @@ import { GoogleAnalyticsSettings } from './bodies/GoogleAnalyticsSettings'
|
||||
import { GoogleSheetsSettingsBody } from './bodies/GoogleSheetsSettingsBody'
|
||||
import { PhoneNumberSettingsBody } from './bodies/PhoneNumberSettingsBody'
|
||||
import { RedirectSettings } from './bodies/RedirectSettings'
|
||||
import { SendEmailSettings } from './bodies/SendEmailSettings/SendEmailSettings'
|
||||
import { SetVariableSettings } from './bodies/SetVariableSettings'
|
||||
import { WebhookSettings } from './bodies/WebhookSettings'
|
||||
|
||||
@ -213,6 +214,14 @@ export const StepSettings = ({
|
||||
/>
|
||||
)
|
||||
}
|
||||
case IntegrationStepType.EMAIL: {
|
||||
return (
|
||||
<SendEmailSettings
|
||||
options={step.options}
|
||||
onOptionsChange={handleOptionsChange}
|
||||
/>
|
||||
)
|
||||
}
|
||||
default: {
|
||||
return <></>
|
||||
}
|
||||
|
@ -3,9 +3,9 @@ import { CredentialsDropdown } from 'components/shared/CredentialsDropdown'
|
||||
import { DropdownList } from 'components/shared/DropdownList'
|
||||
import { TableList, TableListItemProps } from 'components/shared/TableList'
|
||||
import { useTypebot } from 'contexts/TypebotContext'
|
||||
import { CredentialsType } from 'db'
|
||||
import {
|
||||
Cell,
|
||||
CredentialsType,
|
||||
ExtractingCell,
|
||||
GoogleSheetsAction,
|
||||
GoogleSheetsGetOptions,
|
||||
|
@ -0,0 +1,92 @@
|
||||
import { Stack, useDisclosure, Text } from '@chakra-ui/react'
|
||||
import { CredentialsDropdown } from 'components/shared/CredentialsDropdown'
|
||||
import {
|
||||
InputWithVariableButton,
|
||||
TextareaWithVariableButton,
|
||||
} from 'components/shared/TextboxWithVariableButton'
|
||||
import { CredentialsType, SendEmailOptions } from 'models'
|
||||
import React from 'react'
|
||||
import { SmtpConfigModal } from './SmtpConfigModal'
|
||||
|
||||
type Props = {
|
||||
options: SendEmailOptions
|
||||
onOptionsChange: (options: SendEmailOptions) => void
|
||||
}
|
||||
|
||||
export const SendEmailSettings = ({ options, onOptionsChange }: Props) => {
|
||||
const { isOpen, onOpen, onClose } = useDisclosure()
|
||||
const handleCredentialsSelect = (credentialsId: string) =>
|
||||
onOptionsChange({
|
||||
...options,
|
||||
credentialsId,
|
||||
})
|
||||
|
||||
const handleToChange = (recipientsStr: string) => {
|
||||
const recipients: string[] = recipientsStr
|
||||
.split(',')
|
||||
.map((str) => str.trim())
|
||||
onOptionsChange({
|
||||
...options,
|
||||
recipients,
|
||||
})
|
||||
}
|
||||
|
||||
const handleSubjectChange = (subject: string) =>
|
||||
onOptionsChange({
|
||||
...options,
|
||||
subject,
|
||||
})
|
||||
|
||||
const handleBodyChange = (body: string) =>
|
||||
onOptionsChange({
|
||||
...options,
|
||||
body,
|
||||
})
|
||||
|
||||
return (
|
||||
<Stack spacing={4}>
|
||||
<Stack>
|
||||
<Text>From: </Text>
|
||||
<CredentialsDropdown
|
||||
type={CredentialsType.SMTP}
|
||||
currentCredentialsId={options.credentialsId}
|
||||
onCredentialsSelect={handleCredentialsSelect}
|
||||
onCreateNewClick={onOpen}
|
||||
defaultCredentialLabel={
|
||||
process.env.NEXT_PUBLIC_EMAIL_NOTIFICATIONS_FROM_EMAIL
|
||||
}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack>
|
||||
<Text>To: </Text>
|
||||
<InputWithVariableButton
|
||||
onChange={handleToChange}
|
||||
initialValue={options.recipients.join(', ')}
|
||||
placeholder="email1@gmail.com, email2@gmail.com"
|
||||
/>
|
||||
</Stack>
|
||||
<Stack>
|
||||
<Text>Subject: </Text>
|
||||
<InputWithVariableButton
|
||||
data-testid="subject-input"
|
||||
onChange={handleSubjectChange}
|
||||
initialValue={options.subject ?? ''}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack>
|
||||
<Text>Body: </Text>
|
||||
<TextareaWithVariableButton
|
||||
data-testid="body-input"
|
||||
minH="300px"
|
||||
onChange={handleBodyChange}
|
||||
initialValue={options.body ?? ''}
|
||||
/>
|
||||
</Stack>
|
||||
<SmtpConfigModal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
onNewCredentials={handleCredentialsSelect}
|
||||
/>
|
||||
</Stack>
|
||||
)
|
||||
}
|
@ -0,0 +1,88 @@
|
||||
import { FormControl, FormLabel, HStack, Stack } from '@chakra-ui/react'
|
||||
import { isDefined } from '@udecode/plate-common'
|
||||
import { DebouncedInput } from 'components/shared/DebouncedInput'
|
||||
import { SmartNumberInput } from 'components/shared/SmartNumberInput'
|
||||
import { SwitchWithLabel } from 'components/shared/SwitchWithLabel'
|
||||
import { SmtpCredentialsData } from 'models'
|
||||
import React from 'react'
|
||||
|
||||
type Props = {
|
||||
config: SmtpCredentialsData
|
||||
onConfigChange: (config: SmtpCredentialsData) => void
|
||||
}
|
||||
|
||||
export const SmtpConfigForm = ({ config, onConfigChange }: Props) => {
|
||||
const handleFromEmailChange = (email: string) =>
|
||||
onConfigChange({ ...config, from: { ...config.from, email } })
|
||||
const handleFromNameChange = (name: string) =>
|
||||
onConfigChange({ ...config, from: { ...config.from, name } })
|
||||
const handleHostChange = (host: string) => onConfigChange({ ...config, host })
|
||||
const handleUsernameChange = (username: string) =>
|
||||
onConfigChange({ ...config, username })
|
||||
const handlePasswordChange = (password: string) =>
|
||||
onConfigChange({ ...config, password })
|
||||
const handleTlsCheck = (isTlsEnabled: boolean) =>
|
||||
onConfigChange({ ...config, isTlsEnabled })
|
||||
const handlePortNumberChange = (port?: number) =>
|
||||
isDefined(port) && onConfigChange({ ...config, port })
|
||||
|
||||
return (
|
||||
<Stack as="form" spacing={4}>
|
||||
<FormControl isRequired>
|
||||
<FormLabel>From email:</FormLabel>
|
||||
<DebouncedInput
|
||||
initialValue={config.from.email ?? ''}
|
||||
onChange={handleFromEmailChange}
|
||||
placeholder="notifications@provider.com"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormControl isRequired>
|
||||
<FormLabel>From name:</FormLabel>
|
||||
<DebouncedInput
|
||||
initialValue={config.from.name ?? ''}
|
||||
onChange={handleFromNameChange}
|
||||
placeholder="John Smith"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormControl isRequired>
|
||||
<FormLabel>Host:</FormLabel>
|
||||
<DebouncedInput
|
||||
initialValue={config.host ?? ''}
|
||||
onChange={handleHostChange}
|
||||
placeholder="mail.provider.com"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormControl isRequired>
|
||||
<FormLabel>Username / Email:</FormLabel>
|
||||
<DebouncedInput
|
||||
type="email"
|
||||
initialValue={config.username ?? ''}
|
||||
onChange={handleUsernameChange}
|
||||
placeholder="user@provider.com"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormControl isRequired>
|
||||
<FormLabel>Password:</FormLabel>
|
||||
<DebouncedInput
|
||||
type="password"
|
||||
initialValue={config.password ?? ''}
|
||||
onChange={handlePasswordChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<SwitchWithLabel
|
||||
id="Tls"
|
||||
label={'Use TLS?'}
|
||||
initialValue={config.isTlsEnabled ?? false}
|
||||
onCheckChange={handleTlsCheck}
|
||||
/>
|
||||
<FormControl as={HStack} justifyContent="space-between">
|
||||
<FormLabel mb="0">Port number:</FormLabel>
|
||||
<SmartNumberInput
|
||||
placeholder="25"
|
||||
value={config.port}
|
||||
onValueChange={handlePortNumberChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</Stack>
|
||||
)
|
||||
}
|
@ -0,0 +1,88 @@
|
||||
import {
|
||||
Modal,
|
||||
ModalOverlay,
|
||||
ModalContent,
|
||||
ModalHeader,
|
||||
ModalCloseButton,
|
||||
ModalBody,
|
||||
ModalFooter,
|
||||
Button,
|
||||
useToast,
|
||||
} from '@chakra-ui/react'
|
||||
import { useUser } from 'contexts/UserContext'
|
||||
import { CredentialsType, SmtpCredentialsData } from 'models'
|
||||
import React, { useState } from 'react'
|
||||
import { createCredentials } from 'services/credentials'
|
||||
import { isNotDefined } from 'utils'
|
||||
import { SmtpConfigForm } from './SmtpConfigForm'
|
||||
|
||||
type Props = {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onNewCredentials: (id: string) => void
|
||||
}
|
||||
|
||||
export const SmtpConfigModal = ({
|
||||
isOpen,
|
||||
onNewCredentials,
|
||||
onClose,
|
||||
}: Props) => {
|
||||
const { user, mutateCredentials } = useUser()
|
||||
const [isCreating, setIsCreating] = useState(false)
|
||||
const toast = useToast({
|
||||
position: 'top-right',
|
||||
status: 'error',
|
||||
})
|
||||
const [smtpConfig, setSmtpConfig] = useState<SmtpCredentialsData>({
|
||||
from: {},
|
||||
port: 25,
|
||||
})
|
||||
|
||||
const handleCreateClick = async () => {
|
||||
if (!user) return
|
||||
setIsCreating(true)
|
||||
const { data, error } = await createCredentials(user.id, {
|
||||
data: smtpConfig,
|
||||
name: smtpConfig.from.email as string,
|
||||
type: CredentialsType.SMTP,
|
||||
})
|
||||
await mutateCredentials()
|
||||
setIsCreating(false)
|
||||
if (error) return toast({ title: error.name, description: error.message })
|
||||
if (!data?.credentials)
|
||||
return toast({ description: "Credentials wasn't created" })
|
||||
onNewCredentials(data.credentials.id)
|
||||
onClose()
|
||||
}
|
||||
return (
|
||||
<Modal isOpen={isOpen} onClose={onClose}>
|
||||
<ModalOverlay />
|
||||
<ModalContent>
|
||||
<ModalHeader>Create SMTP config</ModalHeader>
|
||||
<ModalCloseButton />
|
||||
<ModalBody>
|
||||
<SmtpConfigForm config={smtpConfig} onConfigChange={setSmtpConfig} />
|
||||
</ModalBody>
|
||||
|
||||
<ModalFooter>
|
||||
<Button
|
||||
colorScheme="blue"
|
||||
mr={3}
|
||||
onClick={handleCreateClick}
|
||||
isDisabled={
|
||||
isNotDefined(smtpConfig.from.email) ||
|
||||
isNotDefined(smtpConfig.from.name) ||
|
||||
isNotDefined(smtpConfig.host) ||
|
||||
isNotDefined(smtpConfig.username) ||
|
||||
isNotDefined(smtpConfig.password)
|
||||
}
|
||||
isLoading={isCreating}
|
||||
>
|
||||
Create
|
||||
</Button>
|
||||
<Button variant="ghost">Close</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
)
|
||||
}
|
@ -0,0 +1 @@
|
||||
export { SendEmailSettings } from './SendEmailSettings'
|
@ -20,6 +20,7 @@ import {
|
||||
import { ConfigureContent } from './contents/ConfigureContent'
|
||||
import { ImageBubbleContent } from './contents/ImageBubbleContent'
|
||||
import { PlaceholderContent } from './contents/PlaceholderContent'
|
||||
import { SendEmailContent } from './contents/SendEmailContent'
|
||||
|
||||
type Props = {
|
||||
step: Step | StartStep
|
||||
@ -101,6 +102,9 @@ export const StepNodeContent = ({ step, indices }: Props) => {
|
||||
case IntegrationStepType.WEBHOOK: {
|
||||
return <WebhookContent step={step} />
|
||||
}
|
||||
case IntegrationStepType.EMAIL: {
|
||||
return <SendEmailContent step={step} />
|
||||
}
|
||||
case 'start': {
|
||||
return <Text>Start</Text>
|
||||
}
|
||||
|
@ -0,0 +1,23 @@
|
||||
import { Tag, Text, Wrap, WrapItem } from '@chakra-ui/react'
|
||||
import { SendEmailStep } from 'models'
|
||||
|
||||
type Props = {
|
||||
step: SendEmailStep
|
||||
}
|
||||
|
||||
export const SendEmailContent = ({ step }: Props) => {
|
||||
if (step.options.recipients.length === 0)
|
||||
return <Text color="gray.500">Configure...</Text>
|
||||
return (
|
||||
<Wrap isTruncated pr="6">
|
||||
<WrapItem>
|
||||
<Text>Send email to</Text>
|
||||
</WrapItem>
|
||||
{step.options.recipients.map((to) => (
|
||||
<WrapItem key={to}>
|
||||
<Tag>{to}</Tag>
|
||||
</WrapItem>
|
||||
))}
|
||||
</Wrap>
|
||||
)
|
||||
}
|
@ -107,7 +107,6 @@ export const SearchableDropdown = ({
|
||||
<PopoverContent
|
||||
maxH="35vh"
|
||||
overflowY="scroll"
|
||||
spacing="0"
|
||||
role="menu"
|
||||
w="inherit"
|
||||
shadow="lg"
|
||||
|
@ -36,7 +36,7 @@ export const TextBoxWithVariableButton = ({
|
||||
const [carretPosition, setCarretPosition] = useState<number>(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (value !== initialValue) onChange(value)
|
||||
onChange(value)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [value])
|
||||
|
||||
|
@ -123,7 +123,6 @@ export const VariableSearchInput = ({
|
||||
<PopoverContent
|
||||
maxH="35vh"
|
||||
overflowY="scroll"
|
||||
spacing="0"
|
||||
role="menu"
|
||||
w="inherit"
|
||||
shadow="lg"
|
||||
|
@ -13,7 +13,9 @@ import { updateUser as updateUserInDb } from 'services/user'
|
||||
import { useToast } from '@chakra-ui/react'
|
||||
import { deepEqual } from 'fast-equals'
|
||||
import { useCredentials } from 'services/credentials'
|
||||
import { Credentials, User } from 'db'
|
||||
import { User } from 'db'
|
||||
import { KeyedMutator } from 'swr'
|
||||
import { Credentials } from 'models'
|
||||
|
||||
const userContext = createContext<{
|
||||
user?: User
|
||||
@ -24,6 +26,9 @@ const userContext = createContext<{
|
||||
credentials: Credentials[]
|
||||
updateUser: (newUser: Partial<User>) => void
|
||||
saveUser: () => void
|
||||
mutateCredentials: KeyedMutator<{
|
||||
credentials: Credentials[]
|
||||
}>
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
//@ts-ignore
|
||||
}>({})
|
||||
@ -32,7 +37,7 @@ export const UserContext = ({ children }: { children: ReactNode }) => {
|
||||
const router = useRouter()
|
||||
const { data: session, status } = useSession()
|
||||
const [user, setUser] = useState<User | undefined>()
|
||||
const { credentials } = useCredentials({
|
||||
const { credentials, mutate } = useCredentials({
|
||||
userId: user?.id,
|
||||
onError: (error) =>
|
||||
toast({ title: error.name, description: error.message }),
|
||||
@ -94,6 +99,7 @@ export const UserContext = ({ children }: { children: ReactNode }) => {
|
||||
hasUnsavedChanges,
|
||||
isOAuthProvider,
|
||||
credentials: credentials ?? [],
|
||||
mutateCredentials: mutate,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
@ -1,5 +1,7 @@
|
||||
import { Prisma, Credentials as CredentialsFromDb } from 'db'
|
||||
import { OAuth2Client, Credentials } from 'google-auth-library'
|
||||
import { Credentials as CredentialsFromDb } from 'db'
|
||||
import { OAuth2Client } from 'google-auth-library'
|
||||
import { GoogleSheetsCredentialsData } from 'models'
|
||||
import { decrypt, encrypt } from 'utils'
|
||||
import prisma from './prisma'
|
||||
|
||||
export const oauth2Client = new OAuth2Client(
|
||||
@ -15,14 +17,21 @@ export const getAuthenticatedGoogleClient = async (
|
||||
const credentials = (await prisma.credentials.findFirst({
|
||||
where: { id: credentialsId, ownerId: userId },
|
||||
})) as CredentialsFromDb
|
||||
oauth2Client.setCredentials(credentials.data as Credentials)
|
||||
const data = decrypt(
|
||||
credentials.data,
|
||||
credentials.iv
|
||||
) as GoogleSheetsCredentialsData
|
||||
oauth2Client.setCredentials(data)
|
||||
oauth2Client.on('tokens', updateTokens(credentialsId))
|
||||
return oauth2Client
|
||||
}
|
||||
|
||||
const updateTokens =
|
||||
(credentialsId: string) => async (credentials: Credentials) =>
|
||||
prisma.credentials.update({
|
||||
(credentialsId: string) =>
|
||||
async (credentials: GoogleSheetsCredentialsData) => {
|
||||
const { encryptedData, iv } = encrypt(credentials)
|
||||
return prisma.credentials.update({
|
||||
where: { id: credentialsId },
|
||||
data: { data: credentials as Prisma.InputJsonValue },
|
||||
data: { data: encryptedData, iv },
|
||||
})
|
||||
}
|
||||
|
@ -11,14 +11,14 @@ import { NextApiRequest, NextApiResponse } from 'next'
|
||||
const providers: Provider[] = [
|
||||
EmailProvider({
|
||||
server: {
|
||||
host: process.env.EMAIL_SERVER_HOST,
|
||||
port: Number(process.env.EMAIL_SERVER_PORT),
|
||||
host: process.env.AUTH_EMAIL_SERVER_HOST,
|
||||
port: Number(process.env.AUTH_EMAIL_SERVER_PORT),
|
||||
auth: {
|
||||
user: process.env.EMAIL_SERVER_USER,
|
||||
pass: process.env.EMAIL_SERVER_PASSWORD,
|
||||
user: process.env.AUTH_EMAIL_SERVER_USER,
|
||||
pass: process.env.AUTH_EMAIL_SERVER_PASSWORD,
|
||||
},
|
||||
},
|
||||
from: process.env.EMAIL_FROM,
|
||||
from: `"${process.env.AUTH_EMAIL_FROM_NAME}" <${process.env.AUTH_EMAIL_FROM_EMAIL}>`,
|
||||
}),
|
||||
]
|
||||
|
||||
|
@ -1,10 +1,12 @@
|
||||
import { oauth2Client } from 'libs/google-sheets'
|
||||
import { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { getSession } from 'next-auth/react'
|
||||
import { CredentialsType, Prisma, User } from 'db'
|
||||
import { Prisma, User } from 'db'
|
||||
import prisma from 'libs/prisma'
|
||||
import { googleSheetsScopes } from './consent-url'
|
||||
import { stringify } from 'querystring'
|
||||
import { CredentialsType } from 'models'
|
||||
import { encrypt } from 'utils'
|
||||
import { oauth2Client } from 'libs/google-sheets'
|
||||
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
const session = await getSession({ req })
|
||||
@ -35,12 +37,14 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
return res
|
||||
.status(400)
|
||||
.send({ message: "User didn't accepted required scopes" })
|
||||
const { encryptedData, iv } = encrypt(tokens)
|
||||
const credentials = {
|
||||
name: email,
|
||||
type: CredentialsType.GOOGLE_SHEETS,
|
||||
ownerId: user.id,
|
||||
data: tokens as Prisma.InputJsonValue,
|
||||
}
|
||||
data: encryptedData,
|
||||
iv,
|
||||
} as Prisma.CredentialsUncheckedCreateInput
|
||||
const { id: credentialsId } = await prisma.credentials.upsert({
|
||||
create: credentials,
|
||||
update: credentials,
|
||||
|
@ -47,17 +47,17 @@ const executeWebhook = async (
|
||||
const contentType = headers ? headers['Content-Type'] : undefined
|
||||
try {
|
||||
const response = await got(
|
||||
parseVariables({ text: webhook.url + `?${queryParams}`, variables }),
|
||||
parseVariables(variables)(webhook.url + `?${queryParams}`),
|
||||
{
|
||||
method: webhook.method as Method,
|
||||
headers,
|
||||
json:
|
||||
contentType !== 'x-www-form-urlencoded' && webhook.body
|
||||
? JSON.parse(parseVariables({ text: webhook.body, variables }))
|
||||
? JSON.parse(parseVariables(variables)(webhook.body))
|
||||
: undefined,
|
||||
form:
|
||||
contentType === 'x-www-form-urlencoded' && webhook.body
|
||||
? JSON.parse(parseVariables({ text: webhook.body, variables }))
|
||||
? JSON.parse(parseVariables(variables)(webhook.body))
|
||||
: undefined,
|
||||
}
|
||||
)
|
||||
@ -96,7 +96,7 @@ const convertKeyValueTableToObject = (
|
||||
if (!item.key) return {}
|
||||
return {
|
||||
...object,
|
||||
[item.key]: parseVariables({ text: item.value, variables }),
|
||||
[item.key]: parseVariables(variables)(item.value ?? ''),
|
||||
}
|
||||
}, {})
|
||||
}
|
||||
|
@ -1,8 +1,9 @@
|
||||
import { User } from 'db'
|
||||
import { Prisma, User } from 'db'
|
||||
import prisma from 'libs/prisma'
|
||||
import { Credentials } from 'models'
|
||||
import { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { getSession } from 'next-auth/react'
|
||||
import { methodNotAllowed } from 'utils'
|
||||
import { encrypt, methodNotAllowed } from 'utils'
|
||||
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
const session = await getSession({ req })
|
||||
@ -16,6 +17,20 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
if (req.method === 'GET') {
|
||||
const credentials = await prisma.credentials.findMany({
|
||||
where: { ownerId: user.id },
|
||||
select: { name: true, type: true, ownerId: true, id: true },
|
||||
})
|
||||
return res.send({ credentials })
|
||||
}
|
||||
if (req.method === 'POST') {
|
||||
const data = JSON.parse(req.body) as Omit<Credentials, 'ownerId'>
|
||||
const { encryptedData, iv } = encrypt(data.data)
|
||||
const credentials = await prisma.credentials.create({
|
||||
data: {
|
||||
...data,
|
||||
data: encryptedData,
|
||||
iv,
|
||||
ownerId: user.id,
|
||||
} as Prisma.CredentialsUncheckedCreateInput,
|
||||
})
|
||||
return res.send({ credentials })
|
||||
}
|
||||
|
@ -9,7 +9,7 @@ const config: PlaywrightTestConfig = {
|
||||
timeout: 5000,
|
||||
},
|
||||
retries: process.env.NO_RETRIES ? 0 : 2,
|
||||
workers: process.env.CI ? 1 : 3,
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
reporter: 'html',
|
||||
maxFailures: process.env.CI ? 10 : undefined,
|
||||
use: {
|
||||
|
@ -2,4 +2,11 @@ PLAYWRIGHT_BUILDER_TEST_BASE_URL=http://localhost:3000
|
||||
|
||||
# For auth
|
||||
GITHUB_EMAIL=
|
||||
GITHUB_PASSWORD=
|
||||
GITHUB_PASSWORD=
|
||||
|
||||
# SMTP Credentials (Generated on https://ethereal.email/)
|
||||
SMTP_HOST=smtp.ethereal.email
|
||||
SMTP_PORT=587
|
||||
SMTP_SECURE=true
|
||||
SMTP_USERNAME=tobin.tillman65@ethereal.email
|
||||
SMTP_PASSWORD=Ty9BcwCBrK6w8AG2hx
|
@ -0,0 +1,112 @@
|
||||
{
|
||||
"id": "ckzcj4tfu1686gg1ae4fdj8uv",
|
||||
"createdAt": "2022-02-07T10:06:35.274Z",
|
||||
"updatedAt": "2022-02-07T10:06:35.274Z",
|
||||
"name": "My typebot",
|
||||
"ownerId": "ckz6t9iep0006k31a22j05fwq",
|
||||
"publishedTypebotId": null,
|
||||
"folderId": null,
|
||||
"blocks": [
|
||||
{
|
||||
"id": "kSDJqC9TmM25eAM3a2yn3o",
|
||||
"steps": [
|
||||
{
|
||||
"id": "phSmjJU2gYq7b11hpima8b",
|
||||
"type": "start",
|
||||
"label": "Start",
|
||||
"blockId": "kSDJqC9TmM25eAM3a2yn3o",
|
||||
"outgoingEdgeId": "vKtpPmbmqgeGC4vwCfPEdv"
|
||||
}
|
||||
],
|
||||
"title": "Start",
|
||||
"graphCoordinates": { "x": 0, "y": 0 }
|
||||
},
|
||||
{
|
||||
"id": "b5r2MMyftV1nv9vyr6VkZh",
|
||||
"graphCoordinates": { "x": 242, "y": 174 },
|
||||
"title": "Block #2",
|
||||
"steps": [
|
||||
{
|
||||
"id": "sb7ibhNAKfvs8yy8fz3XRMT",
|
||||
"blockId": "b5r2MMyftV1nv9vyr6VkZh",
|
||||
"type": "text",
|
||||
"content": {
|
||||
"html": "<div>Send email</div>",
|
||||
"richText": [
|
||||
{ "type": "p", "children": [{ "text": "Send email" }] }
|
||||
],
|
||||
"plainText": "Send email"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "svM58drFcdtdJ7DaJCfTLXm",
|
||||
"blockId": "b5r2MMyftV1nv9vyr6VkZh",
|
||||
"type": "choice input",
|
||||
"options": { "buttonLabel": "Send", "isMultipleChoice": false },
|
||||
"items": [
|
||||
{
|
||||
"id": "nxQEmdaQXc9eFjrbrVBavH",
|
||||
"stepId": "svM58drFcdtdJ7DaJCfTLXm",
|
||||
"type": 0,
|
||||
"content": "Go"
|
||||
}
|
||||
],
|
||||
"outgoingEdgeId": "ioB4s1iRBb8wXiRam8Pp4s"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "6jr7XM9GbVkJ2Ru1WyL45v",
|
||||
"graphCoordinates": { "x": 609, "y": 429 },
|
||||
"title": "Block #2",
|
||||
"steps": [
|
||||
{
|
||||
"id": "sr2sdAzN5dGao1gCiDWCG8i",
|
||||
"blockId": "6jr7XM9GbVkJ2Ru1WyL45v",
|
||||
"type": "Email",
|
||||
"options": { "credentialsId": "default", "recipients": [] }
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"variables": [],
|
||||
"edges": [
|
||||
{
|
||||
"from": {
|
||||
"blockId": "kSDJqC9TmM25eAM3a2yn3o",
|
||||
"stepId": "phSmjJU2gYq7b11hpima8b"
|
||||
},
|
||||
"to": { "blockId": "b5r2MMyftV1nv9vyr6VkZh" },
|
||||
"id": "vKtpPmbmqgeGC4vwCfPEdv"
|
||||
},
|
||||
{
|
||||
"from": {
|
||||
"blockId": "b5r2MMyftV1nv9vyr6VkZh",
|
||||
"stepId": "svM58drFcdtdJ7DaJCfTLXm"
|
||||
},
|
||||
"to": { "blockId": "6jr7XM9GbVkJ2Ru1WyL45v" },
|
||||
"id": "ioB4s1iRBb8wXiRam8Pp4s"
|
||||
}
|
||||
],
|
||||
"theme": {
|
||||
"chat": {
|
||||
"inputs": {
|
||||
"color": "#303235",
|
||||
"backgroundColor": "#FFFFFF",
|
||||
"placeholderColor": "#9095A0"
|
||||
},
|
||||
"buttons": { "color": "#FFFFFF", "backgroundColor": "#0042DA" },
|
||||
"hostBubbles": { "color": "#303235", "backgroundColor": "#F7F8FF" },
|
||||
"guestBubbles": { "color": "#FFFFFF", "backgroundColor": "#FF8E21" }
|
||||
},
|
||||
"general": { "font": "Open Sans", "background": { "type": "None" } }
|
||||
},
|
||||
"settings": {
|
||||
"general": { "isBrandingEnabled": true },
|
||||
"metadata": {
|
||||
"description": "Build beautiful conversational forms and embed them directly in your applications without a line of code. Triple your response rate and collect answers that has more value compared to a traditional form."
|
||||
},
|
||||
"typingEmulation": { "speed": 300, "enabled": true, "maxDelay": 1.5 }
|
||||
},
|
||||
"publicId": null
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 1.4 MiB |
@ -1,5 +1,6 @@
|
||||
import {
|
||||
Block,
|
||||
CredentialsType,
|
||||
defaultSettings,
|
||||
defaultTheme,
|
||||
PublicBlock,
|
||||
@ -7,8 +8,9 @@ import {
|
||||
Step,
|
||||
Typebot,
|
||||
} from 'models'
|
||||
import { CredentialsType, DashboardFolder, PrismaClient, User } from 'db'
|
||||
import { DashboardFolder, PrismaClient, User } from 'db'
|
||||
import { readFileSync } from 'fs'
|
||||
import { encrypt } from 'utils'
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
@ -48,24 +50,27 @@ export const createFolders = (partialFolders: Partial<DashboardFolder>[]) =>
|
||||
})),
|
||||
})
|
||||
|
||||
const createCredentials = () =>
|
||||
prisma.credentials.createMany({
|
||||
const createCredentials = () => {
|
||||
const { encryptedData, iv } = encrypt({
|
||||
expiry_date: 1642441058842,
|
||||
access_token:
|
||||
'ya29.A0ARrdaM--PV_87ebjywDJpXKb77NBFJl16meVUapYdfNv6W6ZzqqC47fNaPaRjbDbOIIcp6f49cMaX5ndK9TAFnKwlVqz3nrK9nLKqgyDIhYsIq47smcAIZkK56SWPx3X3DwAFqRu2UPojpd2upWwo-3uJrod',
|
||||
// This token is linked to a mock Google account (typebot.test.user@gmail.com)
|
||||
refresh_token:
|
||||
'1//0379tIHBxszeXCgYIARAAGAMSNwF-L9Ir0zhkzhblwXqn3_jYqRP3pajcUpqkjRU3fKZZ_eQakOa28amUHSQ-Q9fMzk89MpRTvkc',
|
||||
})
|
||||
return prisma.credentials.createMany({
|
||||
data: [
|
||||
{
|
||||
name: 'test2@gmail.com',
|
||||
ownerId: process.env.PLAYWRIGHT_USER_ID as string,
|
||||
type: CredentialsType.GOOGLE_SHEETS,
|
||||
data: {
|
||||
expiry_date: 1642441058842,
|
||||
access_token:
|
||||
'ya29.A0ARrdaM--PV_87ebjywDJpXKb77NBFJl16meVUapYdfNv6W6ZzqqC47fNaPaRjbDbOIIcp6f49cMaX5ndK9TAFnKwlVqz3nrK9nLKqgyDIhYsIq47smcAIZkK56SWPx3X3DwAFqRu2UPojpd2upWwo-3uJrod',
|
||||
// This token is linked to a mock Google account (typebot.test.user@gmail.com)
|
||||
refresh_token:
|
||||
'1//0379tIHBxszeXCgYIARAAGAMSNwF-L9Ir0zhkzhblwXqn3_jYqRP3pajcUpqkjRU3fKZZ_eQakOa28amUHSQ-Q9fMzk89MpRTvkc',
|
||||
},
|
||||
data: encryptedData,
|
||||
iv,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
export const updateUser = (data: Partial<User>) =>
|
||||
prisma.user.update({
|
||||
|
80
apps/builder/playwright/tests/integrations/sendEmail.spec.ts
Normal file
80
apps/builder/playwright/tests/integrations/sendEmail.spec.ts
Normal file
@ -0,0 +1,80 @@
|
||||
import test, { expect } from '@playwright/test'
|
||||
import { importTypebotInDatabase } from '../../services/database'
|
||||
import path from 'path'
|
||||
import { generate } from 'short-uuid'
|
||||
import { typebotViewer } from '../../services/selectorUtils'
|
||||
|
||||
const typebotId = generate()
|
||||
|
||||
test.describe('Send email step', () => {
|
||||
test('its configuration should work', async ({ page }) => {
|
||||
if (
|
||||
!process.env.SMTP_USERNAME ||
|
||||
!process.env.SMTP_PORT ||
|
||||
!process.env.SMTP_SECURE ||
|
||||
!process.env.SMTP_HOST ||
|
||||
!process.env.SMTP_PASSWORD
|
||||
)
|
||||
throw new Error('SMTP_ env vars are missing')
|
||||
await importTypebotInDatabase(
|
||||
path.join(
|
||||
__dirname,
|
||||
'../../fixtures/typebots/integrations/sendEmail.json'
|
||||
),
|
||||
{
|
||||
id: typebotId,
|
||||
}
|
||||
)
|
||||
|
||||
await page.goto(`/typebots/${typebotId}/edit`)
|
||||
await page.click('text=Configure...')
|
||||
await page.click(
|
||||
`text=${process.env.NEXT_PUBLIC_EMAIL_NOTIFICATIONS_FROM_EMAIL}`
|
||||
)
|
||||
await page.click('text=Connect new')
|
||||
const createButton = page.locator('button >> text=Create')
|
||||
await expect(createButton).toBeDisabled()
|
||||
await page.fill(
|
||||
'[placeholder="notifications@provider.com"]',
|
||||
process.env.SMTP_USERNAME
|
||||
)
|
||||
await page.fill('[placeholder="John Smith"]', 'John Smith')
|
||||
await page.fill('[placeholder="mail.provider.com"]', process.env.SMTP_HOST)
|
||||
await page.fill(
|
||||
'[placeholder="user@provider.com"]',
|
||||
process.env.SMTP_USERNAME
|
||||
)
|
||||
await page.fill('[type="password"]', process.env.SMTP_PASSWORD)
|
||||
if (process.env.SMTP_SECURE === 'true') await page.click('text=Use TLS?')
|
||||
await page.fill('input[role="spinbutton"]', process.env.SMTP_PORT)
|
||||
await expect(createButton).toBeEnabled()
|
||||
await createButton.click()
|
||||
|
||||
await expect(
|
||||
page.locator(`button >> text=${process.env.SMTP_USERNAME}`)
|
||||
).toBeVisible()
|
||||
|
||||
await page.fill(
|
||||
'[placeholder="email1@gmail.com, email2@gmail.com"]',
|
||||
'email1@gmail.com, email2@gmail.com'
|
||||
)
|
||||
await expect(page.locator('span >> text=email1@gmail.com')).toBeVisible()
|
||||
await expect(page.locator('span >> text=email2@gmail.com')).toBeVisible()
|
||||
|
||||
await page.fill(
|
||||
'[placeholder="email1@gmail.com, email2@gmail.com"]',
|
||||
'email1@gmail.com, email2@gmail.com'
|
||||
)
|
||||
await page.fill('[data-testid="subject-input"]', 'Email subject')
|
||||
await page.fill('[data-testid="body-input"]', 'Here is my email')
|
||||
|
||||
await page.click('text=Preview')
|
||||
await typebotViewer(page).locator('text=Go').click()
|
||||
await page.waitForResponse(
|
||||
(resp) =>
|
||||
resp.request().url().includes('/api/integrations/email') &&
|
||||
resp.status() === 200 &&
|
||||
resp.request().method() === 'POST'
|
||||
)
|
||||
})
|
||||
})
|
@ -1,5 +1,6 @@
|
||||
import { Credentials } from 'db'
|
||||
import { Credentials } from 'models'
|
||||
import useSWR from 'swr'
|
||||
import { sendRequest } from 'utils'
|
||||
import { fetcher } from './utils'
|
||||
|
||||
export const useCredentials = ({
|
||||
@ -20,3 +21,15 @@ export const useCredentials = ({
|
||||
mutate,
|
||||
}
|
||||
}
|
||||
|
||||
export const createCredentials = async (
|
||||
userId: string,
|
||||
credentials: Omit<Credentials, 'ownerId' | 'id' | 'iv'>
|
||||
) =>
|
||||
sendRequest<{
|
||||
credentials: Credentials
|
||||
}>({
|
||||
url: `/api/users/${userId}/credentials`,
|
||||
method: 'POST',
|
||||
body: credentials,
|
||||
})
|
||||
|
@ -34,6 +34,7 @@ import {
|
||||
Item,
|
||||
ItemType,
|
||||
defaultConditionContent,
|
||||
defaultSendEmailOptions,
|
||||
} from 'models'
|
||||
import shortId, { generate } from 'short-uuid'
|
||||
import { Typebot } from 'models'
|
||||
@ -207,6 +208,8 @@ const parseDefaultStepOptions = (type: StepWithOptionsType): StepOptions => {
|
||||
return defaultGoogleAnalyticsOptions
|
||||
case IntegrationStepType.WEBHOOK:
|
||||
return defaultWebhookOptions
|
||||
case IntegrationStepType.EMAIL:
|
||||
return defaultSendEmailOptions
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,5 +1,7 @@
|
||||
import { Prisma, Credentials as CredentialsFromDb } from 'db'
|
||||
import { Credentials as CredentialsFromDb } from 'db'
|
||||
import { OAuth2Client, Credentials } from 'google-auth-library'
|
||||
import { GoogleSheetsCredentialsData } from 'models'
|
||||
import { decrypt, encrypt } from 'utils'
|
||||
import prisma from './prisma'
|
||||
|
||||
export const oauth2Client = new OAuth2Client(
|
||||
@ -14,14 +16,20 @@ export const getAuthenticatedGoogleClient = async (
|
||||
const credentials = (await prisma.credentials.findFirst({
|
||||
where: { id: credentialsId },
|
||||
})) as CredentialsFromDb
|
||||
oauth2Client.setCredentials(credentials.data as Credentials)
|
||||
const data = decrypt(
|
||||
credentials.data,
|
||||
credentials.iv
|
||||
) as GoogleSheetsCredentialsData
|
||||
oauth2Client.setCredentials(data)
|
||||
oauth2Client.on('tokens', updateTokens(credentialsId))
|
||||
return oauth2Client
|
||||
}
|
||||
|
||||
const updateTokens =
|
||||
(credentialsId: string) => async (credentials: Credentials) =>
|
||||
prisma.credentials.update({
|
||||
(credentialsId: string) => async (credentials: Credentials) => {
|
||||
const { encryptedData, iv } = encrypt(credentials)
|
||||
return prisma.credentials.update({
|
||||
where: { id: credentialsId },
|
||||
data: { data: credentials as Prisma.InputJsonValue },
|
||||
data: { data: encryptedData, iv },
|
||||
})
|
||||
}
|
||||
|
@ -15,6 +15,7 @@
|
||||
"google-spreadsheet": "^3.2.0",
|
||||
"models": "*",
|
||||
"next": "^12.0.7",
|
||||
"nodemailer": "^6.7.2",
|
||||
"react": "^17.0.2",
|
||||
"react-dom": "^17.0.2",
|
||||
"utils": "*"
|
||||
@ -23,6 +24,7 @@
|
||||
"@types/cors": "^2.8.12",
|
||||
"@types/google-spreadsheet": "^3.1.5",
|
||||
"@types/node": "^17.0.4",
|
||||
"@types/nodemailer": "^6.4.4",
|
||||
"@types/react": "^17.0.38",
|
||||
"@typescript-eslint/eslint-plugin": "^5.9.0",
|
||||
"eslint": "<8.0.0",
|
||||
|
68
apps/viewer/pages/api/integrations/email.ts
Normal file
68
apps/viewer/pages/api/integrations/email.ts
Normal file
@ -0,0 +1,68 @@
|
||||
import prisma from 'libs/prisma'
|
||||
import { SendEmailOptions, SmtpCredentialsData } from 'models'
|
||||
import { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { createTransport } from 'nodemailer'
|
||||
import { Options } from 'nodemailer/lib/smtp-transport'
|
||||
import { decrypt, initMiddleware } from 'utils'
|
||||
|
||||
import Cors from 'cors'
|
||||
|
||||
const cors = initMiddleware(Cors())
|
||||
|
||||
const defaultTransportOptions: Options = {
|
||||
host: process.env.EMAIL_NOTIFICATIONS_SERVER_HOST,
|
||||
port: Number(process.env.EMAIL_NOTIFICATIONS_SERVER_PORT),
|
||||
secure: false,
|
||||
auth: {
|
||||
user: process.env.EMAIL_NOTIFICATIONS_SERVER_USER,
|
||||
pass: process.env.EMAIL_NOTIFICATIONS_SERVER_PASSWORD,
|
||||
},
|
||||
}
|
||||
|
||||
const defaultFrom = `"${process.env.NEXT_PUBLIC_EMAIL_NOTIFICATIONS_FROM_NAME}" <${process.env.NEXT_PUBLIC_EMAIL_NOTIFICATIONS_FROM_EMAIL}>`
|
||||
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
await cors(req, res)
|
||||
if (req.method === 'POST') {
|
||||
const { credentialsId, recipients, body, subject } = JSON.parse(
|
||||
req.body
|
||||
) as SendEmailOptions
|
||||
const credentials = await prisma.credentials.findUnique({
|
||||
where: { id: credentialsId },
|
||||
})
|
||||
|
||||
if (!credentials)
|
||||
return res.status(404).send({ message: "Couldn't find credentials" })
|
||||
const { host, port, isTlsEnabled, username, password, from } = decrypt(
|
||||
credentials.data,
|
||||
credentials.iv
|
||||
) as SmtpCredentialsData
|
||||
|
||||
const transporter = createTransport(
|
||||
credentialsId === 'default'
|
||||
? defaultTransportOptions
|
||||
: {
|
||||
host,
|
||||
port,
|
||||
secure: isTlsEnabled ?? undefined,
|
||||
auth: {
|
||||
user: username,
|
||||
pass: password,
|
||||
},
|
||||
}
|
||||
)
|
||||
const info = await transporter.sendMail({
|
||||
from:
|
||||
credentialsId === 'default'
|
||||
? defaultFrom
|
||||
: `"${from.name}" <${from.email}>`,
|
||||
to: recipients.join(', '),
|
||||
subject,
|
||||
text: body,
|
||||
})
|
||||
|
||||
res.status(200).send({ message: 'Email sent!', info })
|
||||
}
|
||||
}
|
||||
|
||||
export default handler
|
Reference in New Issue
Block a user