2
0

🐛 (limits) Fix storage limit trigger and e2e tests

This commit is contained in:
Baptiste Arnaud
2022-09-24 08:58:23 +02:00
committed by Baptiste Arnaud
parent 1e26703ad4
commit 30dff2d5d7
52 changed files with 1024 additions and 2205 deletions

View File

@@ -76,6 +76,7 @@ const checkStorageLimit = async (typebotId: string) => {
})
if (!typebot?.workspace) throw new Error('Workspace not found')
const { workspace } = typebot
console.log(typebot.workspaceId)
const {
_sum: { storageUsed: totalStorageUsed },
} = await prisma.answer.aggregate({
@@ -94,26 +95,27 @@ const checkStorageLimit = async (typebotId: string) => {
if (!totalStorageUsed) return false
const hasSentFirstEmail = workspace.storageLimitFirstEmailSentAt !== null
const hasSentSecondEmail = workspace.storageLimitSecondEmailSentAt !== null
const storageLimit = getStorageLimit(typebot.workspace) * 1024 * 1024 * 1024
const storageLimit = getStorageLimit(typebot.workspace)
const storageLimitBytes = storageLimit * 1024 * 1024 * 1024
if (
totalStorageUsed >= storageLimit * LIMIT_EMAIL_TRIGGER_PERCENT &&
totalStorageUsed >= storageLimitBytes * LIMIT_EMAIL_TRIGGER_PERCENT &&
!hasSentFirstEmail &&
env('E2E_TEST') !== 'true'
)
sendAlmostReachStorageLimitEmail({
await sendAlmostReachStorageLimitEmail({
workspaceId: workspace.id,
storageLimit,
})
if (
totalStorageUsed >= storageLimit &&
totalStorageUsed >= storageLimitBytes &&
!hasSentSecondEmail &&
env('E2E_TEST') !== 'true'
)
sendReachStorageLimitEmail({
await sendReachStorageLimitEmail({
workspaceId: workspace.id,
storageLimit,
})
return (totalStorageUsed ?? 0) >= getStorageLimit(typebot?.workspace)
return totalStorageUsed >= storageLimitBytes
}
const sendAlmostReachStorageLimitEmail = async ({

View File

@@ -69,8 +69,8 @@ const checkChatsUsage = async (
| 'chatsLimitSecondEmailSentAt'
>
) => {
const chatLimit = getChatsLimit(workspace)
if (chatLimit === -1) return
const chatsLimit = getChatsLimit(workspace)
if (chatsLimit === -1) return
const now = new Date()
const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0)
@@ -91,26 +91,26 @@ const checkChatsUsage = async (
workspace.chatsLimitSecondEmailSentAt < firstDayOfNextMonth &&
workspace.chatsLimitSecondEmailSentAt > firstDayOfMonth
if (
chatsCount >= chatLimit * LIMIT_EMAIL_TRIGGER_PERCENT &&
chatsCount >= chatsLimit * LIMIT_EMAIL_TRIGGER_PERCENT &&
!hasSentFirstEmail &&
env('E2E_TEST') !== 'true'
)
await sendAlmostReachChatsLimitEmail({
workspaceId: workspace.id,
chatLimit,
chatLimit: chatsLimit,
firstDayOfNextMonth,
})
if (
chatsCount >= chatLimit &&
chatsCount >= chatsLimit &&
!hasSentSecondEmail &&
env('E2E_TEST') !== 'true'
)
await sendReachedAlertEmail({
workspaceId: workspace.id,
chatLimit,
chatLimit: chatsLimit,
firstDayOfNextMonth,
})
return chatsCount >= chatLimit
return chatsCount >= chatsLimit
}
const sendAlmostReachChatsLimitEmail = async ({

View File

@@ -1,11 +1,11 @@
import { Page } from '@playwright/test'
export const mockSessionApiCalls = (page: Page) =>
page.route(`${process.env.BUILDER_URL}/api/auth/session`, (route) => {
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":"proUser","name":"Pro user","email":"pro-user@email.com","emailVerified":null,"image":"https://avatars.githubusercontent.com/u/16015833?v=4","stripeId":null,"graphNavigation": "TRACKPAD"}}',
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

@@ -18,6 +18,8 @@ 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({
@@ -51,6 +53,11 @@ export const createWorkspaces = async () =>
name: 'Starter workspace',
plan: Plan.STARTER,
},
{
id: limitTestWorkspaceId,
name: 'Limit test workspace',
plan: Plan.FREE,
},
],
})
@@ -65,20 +72,10 @@ export const createUser = async () => {
createMany: {
data: [
{
name: 'Token 1',
token: 'jirowjgrwGREHEtoken1',
name: 'Token',
token: apiToken,
createdAt: new Date(2022, 1, 1),
},
{
name: 'Github',
token: 'jirowjgrwGREHEgdrgithub',
createdAt: new Date(2022, 1, 2),
},
{
name: 'N8n',
token: 'jirowjgrwGREHrgwhrwn8n',
createdAt: new Date(2022, 1, 3),
},
],
},
},
@@ -88,6 +85,7 @@ export const createUser = async () => {
data: [
{ role: WorkspaceRole.ADMIN, userId, workspaceId: freeWorkspaceId },
{ role: WorkspaceRole.ADMIN, userId, workspaceId: starterWorkspaceId },
{ role: WorkspaceRole.ADMIN, userId, workspaceId: limitTestWorkspaceId },
],
})
}
@@ -207,8 +205,8 @@ export const importTypebotInDatabase = async (
) => {
const typebot: Typebot = {
...JSON.parse(readFileSync(path).toString()),
...updates,
workspaceId: starterWorkspaceId,
...updates,
}
await prisma.typebot.create({
data: typebot,

View File

@@ -1,5 +1,6 @@
import test, { expect } from '@playwright/test'
import {
apiToken,
createResults,
createWebhook,
importTypebotInDatabase,
@@ -23,7 +24,7 @@ test.beforeAll(async () => {
test('can list typebots', async ({ request }) => {
expect((await request.get(`/api/typebots`)).status()).toBe(401)
const response = await request.get(`/api/typebots`, {
headers: { Authorization: 'Bearer userToken' },
headers: { Authorization: `Bearer ${apiToken}` },
})
const { typebots } = await response.json()
expect(typebots).toHaveLength(1)
@@ -41,7 +42,7 @@ test('can get webhook blocks', async ({ request }) => {
const response = await request.get(
`/api/typebots/${typebotId}/webhookBlocks`,
{
headers: { Authorization: 'Bearer userToken' },
headers: { Authorization: `Bearer ${apiToken}` },
}
)
const { blocks } = await response.json()
@@ -65,7 +66,7 @@ test('can subscribe webhook', async ({ request }) => {
`/api/typebots/${typebotId}/blocks/webhookBlock/subscribeWebhook`,
{
headers: {
Authorization: 'Bearer userToken',
Authorization: `Bearer ${apiToken}`,
},
data: { url: 'https://test.com' },
}
@@ -87,7 +88,7 @@ test('can unsubscribe webhook', async ({ request }) => {
const response = await request.post(
`/api/typebots/${typebotId}/blocks/webhookBlock/unsubscribeWebhook`,
{
headers: { Authorization: 'Bearer userToken' },
headers: { Authorization: `Bearer ${apiToken}` },
}
)
const body = await response.json()
@@ -107,7 +108,7 @@ test('can get a sample result', async ({ request }) => {
const response = await request.get(
`/api/typebots/${typebotId}/blocks/webhookBlock/sampleResult`,
{
headers: { Authorization: 'Bearer userToken' },
headers: { Authorization: `Bearer ${apiToken}` },
}
)
const data = await response.json()
@@ -128,7 +129,7 @@ test('can list results', async ({ request }) => {
const response = await request.get(
`/api/typebots/${typebotId}/results?limit=10`,
{
headers: { Authorization: 'Bearer userToken' },
headers: { Authorization: `Bearer ${apiToken}` },
}
)
const { results } = await response.json()

View File

@@ -6,7 +6,6 @@ import { typebotViewer } from '../services/selectorUtils'
import { createResults, importTypebotInDatabase } from '../services/database'
import { readFileSync } from 'fs'
import { isDefined } from 'utils'
import { describe } from 'node:test'
const THREE_GIGABYTES = 3 * 1024 * 1024 * 1024
@@ -49,7 +48,7 @@ test('should work as expected', async ({ page, browser }) => {
page.locator('text="Export"').click(),
])
const downloadPath = await download.path()
expect(path).toBeDefined()
expect(downloadPath).toBeDefined()
const file = readFileSync(downloadPath as string).toString()
const { data } = parse(file)
expect(data).toHaveLength(2)
@@ -86,7 +85,7 @@ test('should work as expected', async ({ page, browser }) => {
).toBeVisible()
})
describe('Storage limit is reached', () => {
test.describe('Storage limit is reached', () => {
const typebotId = cuid()
test.beforeAll(async () => {

View File

@@ -3,9 +3,6 @@ import path from 'path'
import { importTypebotInDatabase } from '../services/database'
import { typebotViewer } from '../services/selectorUtils'
import cuid from 'cuid'
import { mockSessionApiCalls } from 'playwright/services/browser'
test.beforeEach(({ page }) => mockSessionApiCalls(page))
test('should work as expected', async ({ page }) => {
const typebotId = cuid()

View File

@@ -1,8 +1,8 @@
import test, { expect } from '@playwright/test'
import {
createResults,
freeWorkspaceId,
importTypebotInDatabase,
limitTestWorkspaceId,
} from '../services/database'
import cuid from 'cuid'
import path from 'path'
@@ -14,7 +14,7 @@ test('should not start if chat limit is reached', async ({ page }) => {
{
id: typebotId,
publicId: `${typebotId}-public`,
workspaceId: freeWorkspaceId,
workspaceId: limitTestWorkspaceId,
}
)
await createResults({ typebotId, count: 320 })

View File

@@ -11,9 +11,6 @@ import {
} from 'models'
import { typebotViewer } from '../services/selectorUtils'
import cuid from 'cuid'
import { mockSessionApiCalls } from 'playwright/services/browser'
test.beforeEach(({ page }) => mockSessionApiCalls(page))
test('Should correctly parse metadata', async ({ page }) => {
const typebotId = cuid()
@@ -37,20 +34,20 @@ test('Should correctly parse metadata', async ({ page }) => {
},
])
await page.goto(`/${typebotId}-public`)
await expect(
expect(
await page.evaluate(`document.querySelector('title').textContent`)
).toBe(customMetadata.title)
await expect(
expect(
await page.evaluate(
() => (document.querySelector('meta[name="description"]') as any).content
)
).toBe(customMetadata.description)
await expect(
expect(
await page.evaluate(
() => (document.querySelector('meta[property="og:image"]') as any).content
)
).toBe(customMetadata.imageUrl)
await expect(
expect(
await page.evaluate(() =>
(document.querySelector('link[rel="icon"]') as any).getAttribute('href')
)

View File

@@ -3,9 +3,6 @@ import { importTypebotInDatabase } from '../services/database'
import cuid from 'cuid'
import path from 'path'
import { typebotViewer } from '../services/selectorUtils'
import { mockSessionApiCalls } from 'playwright/services/browser'
test.beforeEach(({ page }) => mockSessionApiCalls(page))
test('should correctly be injected', async ({ page }) => {
const typebotId = cuid()

View File

@@ -7,9 +7,6 @@ import cuid from 'cuid'
import path from 'path'
import { typebotViewer } from '../services/selectorUtils'
import { SmtpCredentialsData } from 'models'
import { mockSessionApiCalls } from 'playwright/services/browser'
test.beforeEach(({ page }) => mockSessionApiCalls(page))
const mockSmtpCredentials: SmtpCredentialsData = {
from: {

View File

@@ -10,9 +10,6 @@ import {
defaultTextInputOptions,
InputBlockType,
} from 'models'
import { mockSessionApiCalls } from 'playwright/services/browser'
test.beforeEach(({ page }) => mockSessionApiCalls(page))
test('Result should be in storage by default', async ({ page }) => {
const typebotId = cuid()

View File

@@ -2,9 +2,6 @@ import test, { expect } from '@playwright/test'
import path from 'path'
import { importTypebotInDatabase } from '../services/database'
import { typebotViewer } from '../services/selectorUtils'
import { mockSessionApiCalls } from 'playwright/services/browser'
test.beforeEach(({ page }) => mockSessionApiCalls(page))
test('should work as expected', async ({ page }) => {
const typebotId = 'cl0ibhi7s0018n21aarlmg0cm'

View File

@@ -4,9 +4,6 @@ import cuid from 'cuid'
import path from 'path'
import { typebotViewer } from '../services/selectorUtils'
import { HttpMethod } from 'models'
import { mockSessionApiCalls } from 'playwright/services/browser'
test.beforeEach(({ page }) => mockSessionApiCalls(page))
test('should execute webhooks properly', async ({ page }) => {
const typebotId = cuid()