2
0

(editor) Add unpublish and close typebot options

Introducing more menu items on the "Publised" button in the editor. You can now unpublish a typebot and close it to new
responses
This commit is contained in:
Baptiste Arnaud
2022-10-06 08:33:46 +02:00
parent 7ca97d4606
commit bfed599695
80 changed files with 1112 additions and 961 deletions

View File

@@ -1,5 +1,5 @@
import { TypebotViewer } from 'bot-engine'
import { Answer, PublicTypebot, VariableWithValue } from 'models'
import { Answer, PublicTypebot, Typebot, VariableWithValue } from 'models'
import { useRouter } from 'next/router'
import React, { useEffect, useState } from 'react'
import { upsertAnswer } from 'services/answer'
@@ -9,7 +9,9 @@ import { createResult, updateResult } from '../services/result'
import { ErrorPage } from './ErrorPage'
export type TypebotPageProps = {
typebot?: PublicTypebot & { typebot: { name: string } }
publishedTypebot: Omit<PublicTypebot, 'createdAt' | 'updatedAt'> & {
typebot: Pick<Typebot, 'name' | 'isClosed' | 'isArchived'>
}
url: string
isIE: boolean
customHeadCode: string | null
@@ -18,11 +20,11 @@ export type TypebotPageProps = {
const sessionStorageKey = 'resultId'
export const TypebotPage = ({
typebot,
publishedTypebot,
isIE,
url,
customHeadCode,
}: TypebotPageProps & { typebot: PublicTypebot }) => {
}: TypebotPageProps) => {
const { asPath, push } = useRouter()
const [showTypebot, setShowTypebot] = useState(false)
const [predefinedVariables, setPredefinedVariables] = useState<{
@@ -56,7 +58,7 @@ export const TypebotPage = ({
const hasQueryParams = asPath.includes('?')
if (
hasQueryParams &&
typebot.settings.general.isHideQueryParamsEnabled !== false
publishedTypebot.settings.general.isHideQueryParamsEnabled !== false
)
push(asPath.split('?')[0], undefined, { shallow: true })
}
@@ -65,13 +67,15 @@ export const TypebotPage = ({
const resultIdFromSession = getExistingResultFromSession()
if (resultIdFromSession) setResultId(resultIdFromSession)
else {
const { error, data } = await createResult(typebot.typebotId)
const { error, data } = await createResult(publishedTypebot.typebotId)
if (error) return setError(error)
if (data?.hasReachedLimit)
return setError(new Error('This bot is now closed.'))
if (data?.result) {
setResultId(data.result.id)
if (typebot.settings.general.isNewResultOnRefreshEnabled !== true)
if (
publishedTypebot.settings.general.isNewResultOnRefreshEnabled !== true
)
setResultInSession(data.result.id)
}
}
@@ -122,12 +126,12 @@ export const TypebotPage = ({
<div style={{ height: '100vh' }}>
<SEO
url={url}
typebotName={typebot.typebot.name}
metadata={typebot.settings.metadata}
typebotName={publishedTypebot.typebot.name}
metadata={publishedTypebot.settings.metadata}
/>
{showTypebot && (
<TypebotViewer
typebot={typebot}
typebot={publishedTypebot}
resultId={resultId}
predefinedVariables={predefinedVariables}
onNewAnswer={handleNewAnswer}

View File

@@ -42,6 +42,7 @@
"@typescript-eslint/parser": "5.38.1",
"dotenv": "16.0.3",
"emails": "workspace:*",
"encoding": "^0.1.13",
"eslint": "8.24.0",
"eslint-config-next": "12.3.1",
"eslint-plugin-react": "7.31.8",

View File

@@ -1,6 +1,6 @@
import { IncomingMessage } from 'http'
import { ErrorPage } from 'layouts/ErrorPage'
import { NotFoundPage } from 'layouts/NotFoundPage'
import { PublicTypebot } from 'models'
import { GetServerSideProps, GetServerSidePropsContext } from 'next'
import sanitizeHtml from 'sanitize-html'
import { env, getViewerUrl, isDefined, isNotDefined, omit } from 'utils'
@@ -10,7 +10,6 @@ import prisma from '../libs/prisma'
export const getServerSideProps: GetServerSideProps = async (
context: GetServerSidePropsContext
) => {
let typebot: Omit<PublicTypebot, 'createdAt' | 'updatedAt'> | null
const isIE = /MSIE|Trident/.test(context.req.headers['user-agent'] ?? '')
const pathname = context.resolvedUrl.split('?')[0]
const { host, forwardedHost } = getHost(context.req)
@@ -31,19 +30,19 @@ export const getServerSideProps: GetServerSideProps = async (
const customDomain = `${forwardedHost ?? host}${
pathname === '/' ? '' : pathname
}`
typebot = isMatchingViewerUrl
const publishedTypebot = isMatchingViewerUrl
? await getTypebotFromPublicId(context.query.publicId?.toString())
: await getTypebotFromCustomDomain(customDomain)
if (!typebot)
if (!publishedTypebot)
console.log(
isMatchingViewerUrl
? `Couldn't find publicId: ${context.query.publicId?.toString()}`
: `Couldn't find customDomain: ${customDomain}`
)
const headCode = typebot?.settings.metadata.customHeadCode
const headCode = publishedTypebot?.settings.metadata.customHeadCode
return {
props: {
typebot,
publishedTypebot,
isIE,
url: `https://${forwardedHost ?? host}${pathname}`,
customHeadCode:
@@ -63,23 +62,39 @@ export const getServerSideProps: GetServerSideProps = async (
}
}
const getTypebotFromPublicId = async (publicId?: string) => {
const getTypebotFromPublicId = async (
publicId?: string
): Promise<TypebotPageProps['publishedTypebot'] | null> => {
if (!publicId) return null
const typebot = await prisma.publicTypebot.findFirst({
const publishedTypebot = await prisma.publicTypebot.findFirst({
where: { typebot: { publicId } },
include: { typebot: { select: { name: true } } },
include: {
typebot: { select: { name: true, isClosed: true, isArchived: true } },
},
})
if (isNotDefined(typebot)) return null
return omit(typebot as unknown as PublicTypebot, 'createdAt', 'updatedAt')
if (isNotDefined(publishedTypebot)) return null
return omit(
publishedTypebot,
'createdAt',
'updatedAt'
) as TypebotPageProps['publishedTypebot']
}
const getTypebotFromCustomDomain = async (customDomain: string) => {
const typebot = await prisma.publicTypebot.findFirst({
const getTypebotFromCustomDomain = async (
customDomain: string
): Promise<TypebotPageProps['publishedTypebot'] | null> => {
const publishedTypebot = await prisma.publicTypebot.findFirst({
where: { typebot: { customDomain } },
include: { typebot: { select: { name: true } } },
include: {
typebot: { select: { name: true, isClosed: true, isArchived: true } },
},
})
if (isNotDefined(typebot)) return null
return omit(typebot as unknown as PublicTypebot, 'createdAt', 'updatedAt')
if (isNotDefined(publishedTypebot)) return null
return omit(
publishedTypebot,
'createdAt',
'updatedAt'
) as TypebotPageProps['publishedTypebot']
}
const getHost = (
@@ -89,11 +104,12 @@ const getHost = (
forwardedHost: req?.headers['x-forwarded-host'] as string | undefined,
})
const App = ({ typebot, ...props }: TypebotPageProps) =>
isDefined(typebot) ? (
<TypebotPage typebot={typebot} {...props} />
) : (
<NotFoundPage />
)
const App = ({ publishedTypebot, ...props }: TypebotPageProps) => {
if (!publishedTypebot || publishedTypebot.typebot.isArchived)
return <NotFoundPage />
if (publishedTypebot.typebot.isClosed)
return <ErrorPage error={new Error('This bot is now closed')} />
return <TypebotPage publishedTypebot={publishedTypebot} {...props} />
}
export default App

View File

@@ -1,5 +1,5 @@
import { FullConfig } from '@playwright/test'
import { setupDatabase, teardownDatabase } from './services/database'
import { setupDatabase, teardownDatabase } from 'utils/playwright/databaseSetup'
async function globalSetup(config: FullConfig) {
const { baseURL } = config.projects[0].use

View File

@@ -1,12 +0,0 @@
import { Page } from '@playwright/test'
export const mockSessionResponsesToOtherUser = async (page: Page) =>
page.route('/api/auth/session', (route) => {
if (route.request().method() === 'GET') {
return route.fulfill({
status: 200,
body: '{"user":{"id":"otherUserId","name":"James Doe","email":"other-user@email.com","emailVerified":null,"image":"https://avatars.githubusercontent.com/u/16015833?v=4","stripeId":null,"graphNavigation": "TRACKPAD"}}',
})
}
return route.continue()
})

View File

@@ -1,239 +0,0 @@
import {
CredentialsType,
defaultSettings,
defaultTheme,
PublicTypebot,
SmtpCredentialsData,
Block,
Typebot,
Webhook,
} from 'models'
import { GraphNavigation, Plan, PrismaClient, WorkspaceRole } from 'db'
import { readFileSync } from 'fs'
import { injectFakeResults } from 'utils'
import { encrypt } from 'utils/api'
const prisma = new PrismaClient()
const userId = 'userId'
export const freeWorkspaceId = 'freeWorkspace'
export const starterWorkspaceId = 'starterWorkspace'
export const limitTestWorkspaceId = 'limitTestWorkspace'
export const apiToken = 'jirowjgrwGREHE'
export const teardownDatabase = async () => {
await prisma.workspace.deleteMany({
where: {
members: {
some: { userId },
},
},
})
await prisma.user.deleteMany({
where: { id: userId },
})
return prisma.webhook.deleteMany()
}
export const setupDatabase = async () => {
await createWorkspaces()
await createUser()
}
export const createWorkspaces = async () =>
prisma.workspace.createMany({
data: [
{
id: freeWorkspaceId,
name: 'Free workspace',
plan: Plan.FREE,
},
{
id: starterWorkspaceId,
name: 'Starter workspace',
plan: Plan.STARTER,
},
{
id: limitTestWorkspaceId,
name: 'Limit test workspace',
plan: Plan.FREE,
},
],
})
export const createUser = async () => {
await prisma.user.create({
data: {
id: userId,
email: 'user@email.com',
name: 'John Doe',
graphNavigation: GraphNavigation.TRACKPAD,
apiTokens: {
createMany: {
data: [
{
name: 'Token',
token: apiToken,
createdAt: new Date(2022, 1, 1),
},
],
},
},
},
})
await prisma.memberInWorkspace.createMany({
data: [
{ role: WorkspaceRole.ADMIN, userId, workspaceId: freeWorkspaceId },
{ role: WorkspaceRole.ADMIN, userId, workspaceId: starterWorkspaceId },
{ role: WorkspaceRole.ADMIN, userId, workspaceId: limitTestWorkspaceId },
],
})
}
export const createWebhook = (typebotId: string, webhook?: Partial<Webhook>) =>
prisma.webhook.create({
data: {
id: 'webhook1',
typebotId,
method: 'GET',
...webhook,
},
})
export const createTypebots = async (partialTypebots: Partial<Typebot>[]) => {
await prisma.typebot.createMany({
data: partialTypebots.map(parseTestTypebot),
})
return prisma.publicTypebot.createMany({
data: partialTypebots.map((t) =>
parseTypebotToPublicTypebot(t.id + '-published', parseTestTypebot(t))
),
})
}
export const updateTypebot = async (
partialTypebot: Partial<Typebot> & { id: string }
) => {
await prisma.typebot.updateMany({
where: { id: partialTypebot.id },
data: partialTypebot,
})
return prisma.publicTypebot.updateMany({
where: { typebotId: partialTypebot.id },
data: partialTypebot,
})
}
const parseTypebotToPublicTypebot = (
id: string,
typebot: Typebot
): PublicTypebot => ({
id,
groups: typebot.groups,
typebotId: typebot.id,
theme: typebot.theme,
settings: typebot.settings,
variables: typebot.variables,
edges: typebot.edges,
createdAt: typebot.createdAt,
updatedAt: typebot.updatedAt,
})
const parseTestTypebot = (partialTypebot: Partial<Typebot>): Typebot => ({
id: partialTypebot.id ?? 'typebot',
folderId: null,
name: 'My typebot',
workspaceId: freeWorkspaceId,
icon: null,
theme: defaultTheme,
settings: defaultSettings,
publicId: partialTypebot.id + '-public',
publishedTypebotId: null,
updatedAt: new Date().toISOString(),
createdAt: new Date().toISOString(),
customDomain: null,
variables: [{ id: 'var1', name: 'var1' }],
...partialTypebot,
edges: [
{
id: 'edge1',
from: { groupId: 'group0', blockId: 'block0' },
to: { groupId: 'group1' },
},
],
groups: [
{
id: 'group0',
title: 'Group #0',
blocks: [
{
id: 'block0',
type: 'start',
groupId: 'group0',
label: 'Start',
outgoingEdgeId: 'edge1',
},
],
graphCoordinates: { x: 0, y: 0 },
},
...(partialTypebot.groups ?? []),
],
})
export const parseDefaultGroupWithBlock = (
block: Partial<Block>
): Pick<Typebot, 'groups'> => ({
groups: [
{
graphCoordinates: { x: 200, y: 200 },
id: 'group1',
blocks: [
{
id: 'block1',
groupId: 'group1',
...block,
} as Block,
],
title: 'Group #1',
},
],
})
export const importTypebotInDatabase = async (
path: string,
updates?: Partial<Typebot>
) => {
const typebot: Typebot = {
...JSON.parse(readFileSync(path).toString()),
workspaceId: starterWorkspaceId,
...updates,
}
await prisma.typebot.create({
data: typebot,
})
return prisma.publicTypebot.create({
data: parseTypebotToPublicTypebot(
updates?.id ? `${updates?.id}-public` : 'publicBot',
typebot
),
})
}
export const createResults = injectFakeResults(prisma)
export const createSmtpCredentials = (
id: string,
smtpData: SmtpCredentialsData
) => {
const { encryptedData, iv } = encrypt(smtpData)
return prisma.credentials.create({
data: {
id,
data: encryptedData,
iv,
name: smtpData.from.email as string,
type: CredentialsType.SMTP,
workspaceId: freeWorkspaceId,
},
})
}

View File

@@ -0,0 +1,23 @@
import { CredentialsType, SmtpCredentialsData } from 'models'
import { PrismaClient } from 'db'
import { encrypt } from 'utils/api'
import { freeWorkspaceId } from 'utils/playwright/databaseSetup'
const prisma = new PrismaClient()
export const createSmtpCredentials = (
id: string,
smtpData: SmtpCredentialsData
) => {
const { encryptedData, iv } = encrypt(smtpData)
return prisma.credentials.create({
data: {
id,
data: encryptedData,
iv,
name: smtpData.from.email as string,
type: CredentialsType.SMTP,
workspaceId: freeWorkspaceId,
},
})
}

View File

@@ -1,4 +0,0 @@
import { Page } from '@playwright/test'
export const typebotViewer = (page: Page) =>
page.frameLocator('#typebot-iframe')

View File

@@ -1,11 +1,11 @@
import test, { expect } from '@playwright/test'
import {
apiToken,
createResults,
createWebhook,
importTypebotInDatabase,
} from '../services/database'
import path from 'path'
import {
importTypebotInDatabase,
createWebhook,
injectFakeResults,
} from 'utils/playwright/databaseActions'
import { apiToken } from 'utils/playwright/databaseSetup'
const typebotId = 'webhook-flow'
test.beforeAll(async () => {
@@ -15,7 +15,7 @@ test.beforeAll(async () => {
{ id: typebotId }
)
await createWebhook(typebotId)
await createResults({ typebotId, count: 20 })
await injectFakeResults({ typebotId, count: 20 })
} catch (err) {
console.log(err)
}

View File

@@ -2,10 +2,10 @@ import test, { expect } from '@playwright/test'
import cuid from 'cuid'
import path from 'path'
import { parse } from 'papaparse'
import { typebotViewer } from '../services/selectorUtils'
import { createResults, importTypebotInDatabase } from '../services/database'
import { readFileSync } from 'fs'
import { isDefined } from 'utils'
import { importTypebotInDatabase } from 'utils/playwright/databaseActions'
import { typebotViewer } from 'utils/playwright/testHelpers'
const THREE_GIGABYTES = 3 * 1024 * 1024 * 1024

View File

@@ -1,8 +1,8 @@
import test, { expect } from '@playwright/test'
import path from 'path'
import { importTypebotInDatabase } from '../services/database'
import { typebotViewer } from '../services/selectorUtils'
import cuid from 'cuid'
import { importTypebotInDatabase } from 'utils/playwright/databaseActions'
import { typebotViewer } from 'utils/playwright/testHelpers'
test('should work as expected', async ({ page }) => {
const typebotId = cuid()

View File

@@ -1,9 +1,4 @@
import test, { expect } from '@playwright/test'
import {
createResults,
importTypebotInDatabase,
limitTestWorkspaceId,
} from '../services/database'
import cuid from 'cuid'
import path from 'path'

View File

@@ -1,16 +1,14 @@
import test, { expect } from '@playwright/test'
import {
createTypebots,
parseDefaultGroupWithBlock,
} from '../services/database'
import {
defaultSettings,
defaultTextInputOptions,
InputBlockType,
Metadata,
} from 'models'
import { typebotViewer } from '../services/selectorUtils'
import cuid from 'cuid'
import { createTypebots } from 'utils/playwright/databaseActions'
import { parseDefaultGroupWithBlock } from 'utils/playwright/databaseHelpers'
import { typebotViewer } from 'utils/playwright/testHelpers'
test('Should correctly parse metadata', async ({ page }) => {
const typebotId = cuid()

View File

@@ -1,8 +1,8 @@
import test, { expect } from '@playwright/test'
import { importTypebotInDatabase } from '../services/database'
import cuid from 'cuid'
import path from 'path'
import { typebotViewer } from '../services/selectorUtils'
import { importTypebotInDatabase } from 'utils/playwright/databaseActions'
import { typebotViewer } from 'utils/playwright/testHelpers'
test('should correctly be injected', async ({ page }) => {
const typebotId = cuid()

View File

@@ -1,12 +1,10 @@
import test, { expect } from '@playwright/test'
import {
createSmtpCredentials,
importTypebotInDatabase,
} from '../services/database'
import { createSmtpCredentials } from '../services/databaseActions'
import cuid from 'cuid'
import path from 'path'
import { typebotViewer } from '../services/selectorUtils'
import { SmtpCredentialsData } from 'models'
import { importTypebotInDatabase } from 'utils/playwright/databaseActions'
import { typebotViewer } from 'utils/playwright/testHelpers'
const mockSmtpCredentials: SmtpCredentialsData = {
from: {

View File

@@ -1,15 +1,12 @@
import test, { expect } from '@playwright/test'
import {
createTypebots,
parseDefaultGroupWithBlock,
updateTypebot,
} from '../services/database'
import cuid from 'cuid'
import {
defaultSettings,
defaultTextInputOptions,
InputBlockType,
} from 'models'
import { createTypebots, updateTypebot } from 'utils/playwright/databaseActions'
import { parseDefaultGroupWithBlock } from 'utils/playwright/databaseHelpers'
test('Result should be in storage by default', async ({ page }) => {
const typebotId = cuid()
@@ -107,3 +104,19 @@ test('Hide query params', async ({ page }) => {
`http://localhost:3001/${typebotId}-public?Name=John`
)
})
test('Show close message', async ({ page }) => {
const typebotId = cuid()
await createTypebots([
{
id: typebotId,
...parseDefaultGroupWithBlock({
type: InputBlockType.TEXT,
options: defaultTextInputOptions,
}),
isClosed: true,
},
])
await page.goto(`/${typebotId}-public`)
await expect(page.locator('text=This bot is now closed')).toBeVisible()
})

View File

@@ -1,7 +1,7 @@
import test, { expect } from '@playwright/test'
import path from 'path'
import { importTypebotInDatabase } from '../services/database'
import { typebotViewer } from '../services/selectorUtils'
import { importTypebotInDatabase } from 'utils/playwright/databaseActions'
import { typebotViewer } from 'utils/playwright/testHelpers'
test('should work as expected', async ({ page }) => {
const typebotId = 'cl0ibhi7s0018n21aarlmg0cm'

View File

@@ -1,9 +1,12 @@
import test, { expect } from '@playwright/test'
import { createWebhook, importTypebotInDatabase } from '../services/database'
import cuid from 'cuid'
import path from 'path'
import { typebotViewer } from '../services/selectorUtils'
import { HttpMethod } from 'models'
import {
createWebhook,
importTypebotInDatabase,
} from 'utils/playwright/databaseActions'
import { typebotViewer } from 'utils/playwright/testHelpers'
test('should execute webhooks properly', async ({ page }) => {
const typebotId = cuid()