Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

(feature) Predefined funnels (#199)

Andrii Romasiun14325095aa5c
diff --git a/apps/production/src/analytics/analytics.controller.ts b/apps/production/src/analytics/analytics.controller.ts
index e1965fc2e..59a227788 100644
--- a/apps/production/src/analytics/analytics.controller.ts
+++ b/apps/production/src/analytics/analytics.controller.ts
@@ -4,9 +4,6 @@ import * as _toNumber from 'lodash/toNumber'
import * as _pick from 'lodash/pick'
import * as _includes from 'lodash/includes'
import * as _keys from 'lodash/keys'
-import * as _size from 'lodash/size'
-import * as _some from 'lodash/some'
-import * as _isString from 'lodash/isString'
import * as _values from 'lodash/values'
import * as _map from 'lodash/map'
import * as _uniqBy from 'lodash/uniqBy'
@@ -64,8 +61,6 @@ import {
REDIS_PROJECTS_COUNT_KEY,
REDIS_EVENTS_COUNT_KEY,
REDIS_SESSION_SALT_KEY,
- MIN_PAGES_IN_FUNNEL,
- MAX_PAGES_IN_FUNNEL,
clickhouse,
} from '../common/constants'
import { getGeoDetails, getIPFromHeaders } from '../common/utils'
@@ -279,44 +274,6 @@ const getPIDsArray = (pids, pid) => {
return pids
}
-const getPagesArray = (rawPages: string): string[] => {
- try {
- const pages = JSON.parse(rawPages)
-
- if (!_isArray(pages)) {
- throw new UnprocessableEntityException(
- 'An array of pages has to be provided as a pages param',
- )
- }
-
- const size = _size(pages)
-
- if (size < MIN_PAGES_IN_FUNNEL) {
- throw new UnprocessableEntityException(
- `A minimum of ${MIN_PAGES_IN_FUNNEL} pages or events has to be provided`,
- )
- }
-
- if (size > MAX_PAGES_IN_FUNNEL) {
- throw new UnprocessableEntityException(
- `A maximum of ${MAX_PAGES_IN_FUNNEL} pages or events can be provided`,
- )
- }
-
- if (_some(pages, page => !_isString(page))) {
- throw new UnprocessableEntityException(
- 'Pages array must contain string values only',
- )
- }
-
- return pages
- } catch (e) {
- throw new UnprocessableEntityException(
- 'Cannot process the provided array of pages',
- )
- }
-}
-
// needed for serving 1x1 px GIF
const TRANSPARENT_GIF_BUFFER = Buffer.from(
'R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=',
@@ -477,21 +434,33 @@ export class AnalyticsController {
@CurrentUserId() uid: string,
@Headers() headers: { 'x-password'?: string },
): Promise<IGetFunnel> {
- const { pid, period, from, to, timezone = DEFAULT_TIMEZONE, pages } = data
+ const {
+ pid,
+ period,
+ from,
+ to,
+ timezone = DEFAULT_TIMEZONE,
+ pages,
+ funnelId,
+ } = data
this.analyticsService.validatePID(pid)
if (!_isEmpty(period)) {
this.analyticsService.validatePeriod(period)
}
- const pagesArr = getPagesArray(pages)
-
await this.analyticsService.checkProjectAccess(
pid,
uid,
headers['x-password'],
)
+ const pagesArr = await this.analyticsService.getPagesArray(
+ pages,
+ funnelId,
+ pid,
+ )
+
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(
from,
diff --git a/apps/production/src/analytics/analytics.service.ts b/apps/production/src/analytics/analytics.service.ts
index adc3f0e29..7e4ff7995 100644
--- a/apps/production/src/analytics/analytics.service.ts
+++ b/apps/production/src/analytics/analytics.service.ts
@@ -47,8 +47,11 @@ import {
clickhouse,
REDIS_SESSION_SALT_KEY,
TRAFFIC_COLUMNS,
+ ALL_COLUMNS,
CAPTCHA_COLUMNS,
PERFORMANCE_COLUMNS,
+ MIN_PAGES_IN_FUNNEL,
+ MAX_PAGES_IN_FUNNEL,
} from '../common/constants'
import {
calculateRelativePercentage,
@@ -659,6 +662,60 @@ export class AnalyticsService {
}
}
+ async getPagesArray(
+ rawPages?: string,
+ funnelId?: string,
+ projectId?: string,
+ ): Promise<string[]> {
+ if (funnelId && projectId) {
+ const funnel = await this.projectService.getFunnel(funnelId, projectId)
+
+ if (!funnel || _isEmpty(funnel)) {
+ throw new UnprocessableEntityException(
+ 'The provided funnelId is incorrect',
+ )
+ }
+
+ return funnel.steps
+ }
+
+ try {
+ const pages = JSON.parse(rawPages)
+
+ if (!_isArray(pages)) {
+ throw new UnprocessableEntityException(
+ 'An array of pages has to be provided as a pages param',
+ )
+ }
+
+ const size = _size(pages)
+
+ if (size < MIN_PAGES_IN_FUNNEL) {
+ throw new UnprocessableEntityException(
+ `A minimum of ${MIN_PAGES_IN_FUNNEL} pages or events has to be provided`,
+ )
+ }
+
+ if (size > MAX_PAGES_IN_FUNNEL) {
+ throw new UnprocessableEntityException(
+ `A maximum of ${MAX_PAGES_IN_FUNNEL} pages or events can be provided`,
+ )
+ }
+
+ if (_some(pages, page => !_isString(page))) {
+ throw new UnprocessableEntityException(
+ 'Pages array must contain string values only',
+ )
+ }
+
+ return pages
+ } catch (e) {
+ throw new UnprocessableEntityException(
+ 'Cannot process the provided array of pages',
+ )
+ }
+ }
+
async getTimeBucketForAllTime(
pid: string,
period: string,
@@ -866,7 +923,7 @@ export class AnalyticsService {
let dropoff = 0
let eventsPerc = 100
let eventsPercStep = 100
- let dropoffPerc = 0
+ let dropoffPercStep = 0
if (index > 0) {
const prev = data[index - 1]
@@ -874,7 +931,7 @@ export class AnalyticsService {
dropoff = prev.c - row.c
eventsPerc = _round((row.c / data[0].c) * 100, 2)
eventsPercStep = _round((row.c / prev.c) * 100, 2)
- dropoffPerc = _round((dropoff / prev.c) * 100, 2)
+ dropoffPercStep = _round((dropoff / prev.c) * 100, 2)
}
return {
@@ -883,7 +940,7 @@ export class AnalyticsService {
eventsPerc,
eventsPercStep,
dropoff,
- dropoffPerc,
+ dropoffPercStep,
}
})
@@ -1133,13 +1190,18 @@ export class AnalyticsService {
}
async getFilters(pid: string, type: string): Promise<Array<string>> {
- if (!_includes(TRAFFIC_COLUMNS, type)) {
+ if (!_includes(ALL_COLUMNS, type)) {
throw new UnprocessableEntityException(
`The provided type (${type}) is incorrect`,
)
}
- const query = `SELECT ${type} FROM analytics WHERE pid={pid:FixedString(12)} AND ${type} IS NOT NULL GROUP BY ${type}`
+ let query = `SELECT ${type} FROM analytics WHERE pid={pid:FixedString(12)} AND ${type} IS NOT NULL GROUP BY ${type}`
+
+ if (type === 'ev') {
+ query = `SELECT ${type} FROM customEV WHERE pid={pid:FixedString(12)} AND ${type} IS NOT NULL GROUP BY ${type}`
+ }
+
const results = await clickhouse
.query(query, { params: { pid } })
.toPromise()
diff --git a/apps/production/src/analytics/dto/getFunnels.dto.ts b/apps/production/src/analytics/dto/getFunnels.dto.ts
index afde79179..f7617cf8d 100644
--- a/apps/production/src/analytics/dto/getFunnels.dto.ts
+++ b/apps/production/src/analytics/dto/getFunnels.dto.ts
@@ -26,5 +26,10 @@ export class GetFunnelsDTO {
@ApiProperty({
description: 'A stringified array of pages to generate funnel for',
})
- pages: string
+ pages?: string
+
+ @ApiProperty({
+ description: 'Funnel ID',
+ })
+ funnelId?: string
}
diff --git a/apps/production/src/analytics/interfaces/index.ts b/apps/production/src/analytics/interfaces/index.ts
index 66084f88e..fd7732776 100644
--- a/apps/production/src/analytics/interfaces/index.ts
+++ b/apps/production/src/analytics/interfaces/index.ts
@@ -111,7 +111,7 @@ export interface IFunnel {
eventsPerc: number
eventsPercStep: number
dropoff: number
- dropoffPerc: number
+ dropoffPercStep: number
}
export interface IGetFunnel {
diff --git a/apps/production/src/common/constants.ts b/apps/production/src/common/constants.ts
index a03777dbb..dd4c841f3 100644
--- a/apps/production/src/common/constants.ts
+++ b/apps/production/src/common/constants.ts
@@ -134,6 +134,8 @@ const TRAFFIC_COLUMNS = [
'ca',
]
+const ALL_COLUMNS = [...TRAFFIC_COLUMNS, 'ev']
+
const CAPTCHA_COLUMNS = ['cc', 'br', 'os', 'dv']
const PERFORMANCE_COLUMNS = ['cc', 'rg', 'ct', 'pg', 'dv', 'br']
@@ -174,6 +176,8 @@ const sentryIgnoreErrors: (string | RegExp)[] = [
const NUMBER_JWT_REFRESH_TOKEN_LIFETIME = Number(JWT_REFRESH_TOKEN_LIFETIME)
const NUMBER_JWT_ACCESS_TOKEN_LIFETIME = Number(JWT_ACCESS_TOKEN_LIFETIME)
+const MAX_FUNNELS = 100
+
export {
clickhouse,
redis,
@@ -222,4 +226,6 @@ export {
BLOG_POSTS_PATH,
MIN_PAGES_IN_FUNNEL,
MAX_PAGES_IN_FUNNEL,
+ MAX_FUNNELS,
+ ALL_COLUMNS,
}
diff --git a/apps/production/src/project/dto/funnel-create.dto.ts b/apps/production/src/project/dto/funnel-create.dto.ts
new file mode 100644
index 000000000..6d2ab4440
--- /dev/null
+++ b/apps/production/src/project/dto/funnel-create.dto.ts
@@ -0,0 +1,38 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsNotEmpty, Length, ArrayMinSize, ArrayMaxSize } from 'class-validator'
+import {
+ MAX_PAGES_IN_FUNNEL,
+ MIN_PAGES_IN_FUNNEL,
+} from '../../common/constants'
+
+export class FunnelCreateDTO {
+ @ApiProperty({
+ example: 'User sign up funnel',
+ required: true,
+ description: 'A display name for your funnel',
+ })
+ @IsNotEmpty()
+ @Length(1, 50)
+ name: string
+
+ @ApiProperty({
+ example: 'aUn1quEid-3',
+ required: true,
+ description: 'Funnel project ID',
+ })
+ @IsNotEmpty()
+ pid: string
+
+ @ApiProperty({
+ example: ['/', '/signup', '/dashboard'],
+ required: true,
+ description: 'Steps of the funnel',
+ })
+ @ArrayMinSize(MIN_PAGES_IN_FUNNEL, {
+ message: `A funnel must have at least ${MIN_PAGES_IN_FUNNEL} steps`,
+ })
+ @ArrayMaxSize(MAX_PAGES_IN_FUNNEL, {
+ message: `A funnel must have no more than ${MAX_PAGES_IN_FUNNEL} steps`,
+ })
+ steps: string[] | null
+}
diff --git a/apps/production/src/project/dto/funnel-update.dto.ts b/apps/production/src/project/dto/funnel-update.dto.ts
new file mode 100644
index 000000000..31a7a3c3c
--- /dev/null
+++ b/apps/production/src/project/dto/funnel-update.dto.ts
@@ -0,0 +1,47 @@
+import { ApiProperty } from '@nestjs/swagger'
+import {
+ IsNotEmpty,
+ Length,
+ ArrayMinSize,
+ ArrayMaxSize,
+ IsUUID,
+} from 'class-validator'
+import {
+ MAX_PAGES_IN_FUNNEL,
+ MIN_PAGES_IN_FUNNEL,
+} from '../../common/constants'
+
+export class FunnelUpdateDTO {
+ @IsUUID('4')
+ id: string
+
+ @ApiProperty({
+ example: 'aUn1quEid-3',
+ required: true,
+ description: 'Funnel project ID',
+ })
+ @IsNotEmpty()
+ pid: string
+
+ @ApiProperty({
+ example: 'User sign up funnel',
+ required: true,
+ description: 'A display name for your funnel',
+ })
+ @IsNotEmpty()
+ @Length(1, 50)
+ name: string
+
+ @ApiProperty({
+ example: ['/', '/signup', '/dashboard'],
+ required: true,
+ description: 'Steps of the funnel',
+ })
+ @ArrayMinSize(MIN_PAGES_IN_FUNNEL, {
+ message: `A funnel must have at least ${MIN_PAGES_IN_FUNNEL} steps`,
+ })
+ @ArrayMaxSize(MAX_PAGES_IN_FUNNEL, {
+ message: `A funnel must have no more than ${MAX_PAGES_IN_FUNNEL} steps`,
+ })
+ steps: string[] | null
+}
diff --git a/apps/production/src/project/dto/index.ts b/apps/production/src/project/dto/index.ts
index c1f1e3be2..9141d4c67 100644
--- a/apps/production/src/project/dto/index.ts
+++ b/apps/production/src/project/dto/index.ts
@@ -12,3 +12,5 @@ export * from './create-project.dto'
export * from './project.dto'
export * from './share.dto'
export * from './share-update.dto'
+export * from './funnel-create.dto'
+export * from './funnel-update.dto'
diff --git a/apps/production/src/project/entity/funnel.entity.ts b/apps/production/src/project/entity/funnel.entity.ts
new file mode 100644
index 000000000..ce71c71a2
--- /dev/null
+++ b/apps/production/src/project/entity/funnel.entity.ts
@@ -0,0 +1,30 @@
+import {
+ Column,
+ CreateDateColumn,
+ Entity,
+ JoinColumn,
+ ManyToOne,
+ PrimaryGeneratedColumn,
+} from 'typeorm'
+import { Project } from './project.entity'
+
+@Entity()
+export class Funnel {
+ @PrimaryGeneratedColumn('uuid')
+ id: string
+
+ @Column('varchar', { length: 50 })
+ name: string
+
+ @Column({
+ type: 'simple-array',
+ })
+ steps: string[]
+
+ @CreateDateColumn()
+ created: Date
+
+ @ManyToOne(() => Project, project => project.funnels)
+ @JoinColumn()
+ project: Project
+}
diff --git a/apps/production/src/project/entity/index.ts b/apps/production/src/project/entity/index.ts
index c01847b61..32e7cd311 100644
--- a/apps/production/src/project/entity/index.ts
+++ b/apps/production/src/project/entity/index.ts
@@ -1 +1,4 @@
export * from './project-subscriber.entity'
+export * from './funnel.entity'
+export * from './project.entity'
+export * from './project-share.entity'
diff --git a/apps/production/src/project/entity/project.entity.ts b/apps/production/src/project/entity/project.entity.ts
index ed7b02204..17803f6b3 100644
--- a/apps/production/src/project/entity/project.entity.ts
+++ b/apps/production/src/project/entity/project.entity.ts
@@ -13,6 +13,7 @@ import { User } from '../../user/entities/user.entity'
import { ProjectShare } from './project-share.entity'
import { ExtensionToProject } from '../../marketplace/extensions/entities/extension-to-project.entity'
import { ProjectSubscriber } from './project-subscriber.entity'
+import { Funnel } from './funnel.entity'
import { CAPTCHA_SECRET_KEY_LENGTH } from '../../common/constants'
// In case of modifying some properties here add them to the GDPR data export email template
@@ -96,6 +97,10 @@ export class Project {
})
subscribers: ProjectSubscriber[]
+ @ApiProperty({ type: () => Funnel })
+ @OneToMany(() => Funnel, funnel => funnel.project)
+ funnels: Funnel[]
+
@Column('varchar', {
default: null,
length: 60,
diff --git a/apps/production/src/project/project.controller.ts b/apps/production/src/project/project.controller.ts
index 091a74ded..b2a7073cb 100644
--- a/apps/production/src/project/project.controller.ts
+++ b/apps/production/src/project/project.controller.ts
@@ -66,6 +66,7 @@ import {
CAPTCHA_SECRET_KEY_LENGTH,
isDevelopment,
PRODUCTION_ORIGIN,
+ MAX_FUNNELS,
} from '../common/constants'
import { generateRandomString } from '../common/utils'
import {
@@ -86,6 +87,8 @@ import {
ProjectDTO,
ShareDTO,
ShareUpdateDTO,
+ FunnelCreateDTO,
+ FunnelUpdateDTO,
} from './dto'
const PROJECTS_MAXIMUM = 50
@@ -447,6 +450,183 @@ export class ProjectController {
}
}
+ @Post('/funnel')
+ @ApiResponse({ status: 201 })
+ @Auth([], true)
+ async createFunnel(
+ @Body() funnelDTO: FunnelCreateDTO,
+ @CurrentUserId() userId: string,
+ ): Promise<any> {
+ this.logger.log({ funnelDTO, userId }, 'POST /project/funnel')
+
+ if (!userId) {
+ throw new UnauthorizedException('Please auth first')
+ }
+
+ const user = await this.userService.findOneWithRelations(userId, [
+ 'projects',
+ ])
+
+ if (!user.isActive) {
+ throw new ForbiddenException('Please, verify your email address first')
+ }
+
+ if (user.planCode === PlanCode.none) {
+ throw new HttpException(
+ 'You cannot create new funnels due to no active subscription. Please upgrade your account plan to continue.',
+ HttpStatus.PAYMENT_REQUIRED,
+ )
+ }
+
+ const project = await this.projectService.findOneWhere(
+ {
+ id: funnelDTO.pid,
+ admin: userId,
+ },
+ {
+ relations: ['admin', 'share'],
+ },
+ )
+
+ if (!project) {
+ throw new NotFoundException('Project not found.')
+ }
+
+ this.projectService.allowedToManage(project, userId, user.roles)
+
+ return this.projectService.createFunnel(project.id, funnelDTO)
+ }
+
+ @Patch('/funnel')
+ @ApiResponse({ status: 200 })
+ @Auth([], true)
+ async updateFunnel(
+ @Body() funnelDTO: FunnelUpdateDTO,
+ @CurrentUserId() userId: string,
+ ): Promise<any> {
+ this.logger.log({ funnelDTO, userId }, 'PATCH /project/funnel')
+
+ if (!userId) {
+ throw new UnauthorizedException('Please auth first')
+ }
+
+ const user = await this.userService.findOneWithRelations(userId, [
+ 'projects',
+ ])
+
+ if (!user.isActive) {
+ throw new ForbiddenException('Please, verify your email address first')
+ }
+
+ if (user.planCode === PlanCode.none) {
+ throw new HttpException(
+ 'You cannot update funnels due to no active subscription. Please upgrade your account plan to continue.',
+ HttpStatus.PAYMENT_REQUIRED,
+ )
+ }
+
+ const project = await this.projectService.findOneWhere(
+ {
+ id: funnelDTO.pid,
+ admin: userId,
+ },
+ {
+ relations: ['admin', 'share', 'funnels'],
+ },
+ )
+
+ if (!project) {
+ throw new NotFoundException('Project not found.')
+ }
+
+ this.projectService.allowedToManage(project, userId, user.roles)
+
+ if (_size(project.funnels) >= MAX_FUNNELS) {
+ throw new ForbiddenException(
+ `You cannot create more than ${MAX_FUNNELS}. Please contact us to increase the limit.`,
+ )
+ }
+
+ const oldFunnel = await this.projectService.getFunnel(
+ funnelDTO.id,
+ project.id,
+ )
+
+ if (!oldFunnel) {
+ throw new NotFoundException('Funnel not found.')
+ }
+
+ return this.projectService.updateFunnel({
+ id: funnelDTO.id,
+ name: funnelDTO.name,
+ steps: funnelDTO.steps,
+ } as FunnelUpdateDTO)
+ }
+
+ @Delete('/funnel/:id/:pid')
+ @ApiResponse({ status: 200 })
+ @Auth([], true)
+ async deleteFunnel(
+ @Param('id') id: string,
+ @Param('pid') pid: string,
+ @CurrentUserId() userId: string,
+ ): Promise<void> {
+ this.logger.log({ id, userId }, 'PATCH /project/funnel')
+
+ if (!userId) {
+ throw new UnauthorizedException('Please auth first')
+ }
+
+ const project = await this.projectService.findOneWhere(
+ {
+ id: pid,
+ admin: userId,
+ },
+ {
+ relations: ['admin', 'share'],
+ },
+ )
+
+ if (!project) {
+ throw new NotFoundException('Project not found.')
+ }
+
+ this.projectService.allowedToManage(project, userId)
+
+ const oldFunnel = await this.projectService.getFunnel(id, project.id)
+
+ if (!oldFunnel) {
+ throw new NotFoundException('Funnel not found.')
+ }
+
+ await this.projectService.deleteFunnel(id)
+ }
+
+ @Get('/funnels/:pid')
+ @ApiResponse({ status: 200 })
+ @Auth([], true)
+ async getFunnels(
+ @Param('pid') pid: string,
+ @CurrentUserId() userId: string,
+ @Headers() headers: { 'x-password'?: string },
+ ): Promise<any> {
+ this.logger.log({ pid, userId }, 'PATCH /project/funnel')
+
+ if (!userId) {
+ throw new UnauthorizedException('Please auth first')
+ }
+
+ const project = await this.projectService.getProject(pid, userId)
+
+ if (!project) {
+ throw new NotFoundException('Project not found.')
+ }
+
+ this.projectService.allowedToView(project, userId, headers['x-password'])
+
+ return this.projectService.getFunnels(project.id)
+ }
+
@Delete('/reset/:id')
@HttpCode(204)
@UseGuards(JwtAccessTokenGuard, RolesGuard)
@@ -1521,7 +1701,7 @@ export class ProjectController {
}
const project = await this.projectService.findOne(id, {
- relations: ['admin', 'share', 'share.user'],
+ relations: ['admin', 'share', 'share.user', 'funnels'],
})
if (_isEmpty(project)) {
diff --git a/apps/production/src/project/project.module.ts b/apps/production/src/project/project.module.ts
index daf6c819c..06516b762 100644
--- a/apps/production/src/project/project.module.ts
+++ b/apps/production/src/project/project.module.ts
@@ -1,19 +1,22 @@
import { Module, forwardRef } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
-import { Project } from './entity/project.entity'
-import { ProjectShare } from './entity/project-share.entity'
import { ProjectService } from './project.service'
import { ProjectController } from './project.controller'
import { UserModule } from '../user/user.module'
import { ActionTokensModule } from '../action-tokens/action-tokens.module'
import { MailerModule } from '../mailer/mailer.module'
import { AppLoggerModule } from '../logger/logger.module'
-import { ProjectSubscriber } from './entity'
+import { Project, ProjectSubscriber, Funnel, ProjectShare } from './entity'
@Module({
imports: [
- TypeOrmModule.forFeature([Project, ProjectShare, ProjectSubscriber]),
+ TypeOrmModule.forFeature([
+ Project,
+ ProjectShare,
+ ProjectSubscriber,
+ Funnel,
+ ]),
forwardRef(() => UserModule),
AppLoggerModule,
ActionTokensModule,
diff --git a/apps/production/src/project/project.service.ts b/apps/production/src/project/project.service.ts
index bf61a4303..20a5eb0c5 100644
--- a/apps/production/src/project/project.service.ts
+++ b/apps/production/src/project/project.service.ts
@@ -52,13 +52,15 @@ import {
TRAFFIC_COLUMNS,
} from '../common/constants'
import { IUsageInfoRedis } from '../user/interfaces'
-import { ProjectSubscriber } from './entity'
+import { ProjectSubscriber, Funnel } from './entity'
import { AddSubscriberType } from './types'
import {
CreateProjectDTO,
GetSubscribersQueriesDto,
UpdateProjectDto,
UpdateSubscriberBodyDto,
+ FunnelCreateDTO,
+ FunnelUpdateDTO,
} from './dto'
import { ReportFrequency } from './enums'
import { nFormatter } from '../common/utils'
@@ -275,6 +277,8 @@ export class ProjectService {
private userService: UserService,
@InjectRepository(ProjectSubscriber)
private readonly projectSubscriberRepository: Repository<ProjectSubscriber>,
+ @InjectRepository(Funnel)
+ private readonly funnelRepository: Repository<Funnel>,
private readonly actionTokens: ActionTokensService,
private readonly mailerService: MailerService,
) {}
@@ -342,7 +346,7 @@ export class ProjectService {
order: {
name: 'ASC',
},
- relations: ['share', 'share.user'],
+ relations: ['share', 'share.user', 'funnels'],
})
return new Pagination<Project>({
@@ -430,8 +434,11 @@ export class ProjectService {
return this.projectShareRepository.findOne(id, params)
}
- findOneWithRelations(id: string): Promise<Project | null> {
- return this.projectsRepository.findOne(id, { relations: ['admin'] })
+ findOneWithRelations(
+ id: string,
+ relations = ['admin'],
+ ): Promise<Project | null> {
+ return this.projectsRepository.findOne(id, { relations })
}
findOne(id: string, params: object = {}): Promise<Project | null> {
@@ -869,6 +876,34 @@ export class ProjectService {
return { subscribers, count }
}
+ async createFunnel(projectId: string, data: FunnelCreateDTO) {
+ const funnel = await this.funnelRepository.save({
+ ...data,
+ project: { id: projectId },
+ })
+ return funnel
+ }
+
+ async getFunnels(projectId: string) {
+ return this.funnelRepository.find({
+ where: { project: { id: projectId } },
+ })
+ }
+
+ async getFunnel(funnelId: string, projectId: string) {
+ return this.funnelRepository.findOne({
+ where: { id: funnelId, project: { id: projectId } },
+ })
+ }
+
+ async updateFunnel(data: FunnelUpdateDTO) {
+ return this.funnelRepository.update({ id: data.id }, data)
+ }
+
+ async deleteFunnel(id: string) {
+ return this.funnelRepository.delete({ id })
+ }
+
async updateSubscriber(
projectId: string,
subscriberId: string,
diff --git a/migrations/mysql/2023_10_20.sql b/migrations/mysql/2023_10_20.sql
new file mode 100644
index 000000000..d4db4bcd2
--- /dev/null
+++ b/migrations/mysql/2023_10_20.sql
@@ -0,0 +1,8 @@
+CREATE TABLE `funnel` (
+ `id` varchar(36) NOT NULL,
+ `name` varchar(50) NOT NULL,
+ `steps` text NOT NULL,
+ `created` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
+ `projectId` varchar(12) DEFAULT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;