📈 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Added transfer project route
Yevhenii Kulisidid076a7597d23
diff --git a/migrations/mysql/2023_03_28.sql b/migrations/mysql/2023_03_28.sqlnew file mode 100644index 000000000..30cd5a283--- /dev/null+++ b/migrations/mysql/2023_03_28.sql@@ -0,0 +1 @@+alter table action_token modify column `action` enum('0', '1', '2', '3', '4', '5') default null after newValue;diff --git a/src/action-tokens/action-token.entity.ts b/src/action-tokens/action-token.entity.tsindex 777b3523a..27dd5ed1a 100644--- a/src/action-tokens/action-token.entity.ts+++ b/src/action-tokens/action-token.entity.ts@@ -14,6 +14,7 @@ export enum ActionTokenType {EMAIL_CHANGE,PROJECT_SHARE,ADDING_PROJECT_SUBSCRIBER,+ TRANSFER_PROJECT,}@Entity()diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.tsindex 78d901054..c30fdc141 100644--- a/src/analytics/analytics.controller.ts+++ b/src/analytics/analytics.controller.ts@@ -707,7 +707,9 @@ export class AnalyticsController {await Promise.all(keyCountPromises).catch(reason => {this.logger.error(`[@Get('/hb')] ${reason}`)- throw new InternalServerErrorException('An error occured while calculating heartbeat statistics')+ throw new InternalServerErrorException(+ 'An error occured while calculating heartbeat statistics',+ )})return resultdiff --git a/src/mailer/letter.ts b/src/mailer/letter.tsindex 343bfcf96..9e3623924 100644--- a/src/mailer/letter.ts+++ b/src/mailer/letter.ts@@ -14,4 +14,5 @@ export enum LetterTemplate {TrialExpired = 'trial-expired',TrialEndsTomorrow = 'trial-ends-tomorrow',ProjectSubscriberInvitation = 'project-subscriber-invitation',+ ProjectTransfer = 'project-transfer',}diff --git a/src/mailer/mailer.service.ts b/src/mailer/mailer.service.tsindex 45c03de6f..69e087c51 100644--- a/src/mailer/mailer.service.ts+++ b/src/mailer/mailer.service.ts@@ -86,6 +86,11 @@ const metaInfoJson = {en: () => 'You have been invited to join the project.',},},+ [LetterTemplate.ProjectTransfer]: {+ subject: {+ en: () => 'You have been invited to join the project.',+ },+ },}interface Params {diff --git a/src/project/dto/index.ts b/src/project/dto/index.tsindex 32a01a79f..29558f3cc 100644--- a/src/project/dto/index.ts+++ b/src/project/dto/index.ts@@ -3,3 +3,4 @@ export * from './confirm-subscriber-invite.dto'export * from './get-subscribers.dto'export * from './update-subscriber.dto'export * from './remove-subscriber.dto'+export * from './transfer-project.dto'diff --git a/src/project/dto/transfer-project.dto.ts b/src/project/dto/transfer-project.dto.tsnew file mode 100644index 000000000..de0184b84--- /dev/null+++ b/src/project/dto/transfer-project.dto.ts@@ -0,0 +1,11 @@+import { IsEmail, Matches } from 'class-validator'++export class TransferProjectParamsDto {+ @Matches(/^(?!.*--)[a-zA-Z0-9-]{12}$/)+ readonly projectId: string+}++export class TransferProjectBodyDto {+ @IsEmail()+ readonly email: string+}diff --git a/src/project/project.controller.ts b/src/project/project.controller.tsindex e2b72dad5..e6b3ff9b2 100644--- a/src/project/project.controller.ts+++ b/src/project/project.controller.ts@@ -16,6 +16,7 @@ import {NotImplementedException,Patch,HttpStatus,+ ConflictException,} from '@nestjs/common'import { ApiTags, ApiQuery, ApiResponse } from '@nestjs/swagger'import * as _isEmpty from 'lodash/isEmpty'@@ -80,6 +81,8 @@ import {UpdateSubscriberParamsDto,UpdateSubscriberBodyDto,RemoveSubscriberParamsDto,+ TransferProjectParamsDto,+ TransferProjectBodyDto,} from './dto'const PROJECTS_MAXIMUM = ACCOUNT_PLANS[PlanCode.free].maxProjects@@ -799,8 +802,20 @@ export class ProjectController {}@Delete('/partially/:pid')- @ApiQuery({ name: 'from', required: true, description: 'Date in ISO format', example: '2020-01-01T00:00:00.000Z', type: 'string' })- @ApiQuery({ name: 'to', required: true, description: 'Date in ISO format', example: '2020-01-01T00:00:00.000Z', type: 'string' })+ @ApiQuery({+ name: 'from',+ required: true,+ description: 'Date in ISO format',+ example: '2020-01-01T00:00:00.000Z',+ type: 'string',+ })+ @ApiQuery({+ name: 'to',+ required: true,+ description: 'Date in ISO format',+ example: '2020-01-01T00:00:00.000Z',+ type: 'string',+ })@ApiResponse({ status: 200 })@UseGuards(JwtAccessTokenGuard, RolesGuard)@Auth([UserType.ADMIN, UserType.CUSTOMER])@@ -813,18 +828,20 @@ export class ProjectController {this.logger.log({ from, to, pid }, 'DELETE /partially/:id')if (!isValidPID(pid)) {- throw new BadRequestException('The provided Project ID (pid) is incorrect')+ throw new BadRequestException(+ 'The provided Project ID (pid) is incorrect',+ )}from = _head(_split(from, 'T'))to = _head(_split(to, 'T'))if (!isValidDate(from)) {- throw new BadRequestException('The provided \'from\' date is incorrect',)+ throw new BadRequestException("The provided 'from' date is incorrect")}if (!isValidDate(to)) {- throw new BadRequestException('The provided \'to\' date is incorrect',)+ throw new BadRequestException("The provided 'to' date is incorrect")}const project = await this.projectService.findOne(pid, {@@ -1249,4 +1266,40 @@ export class ProjectController {params.subscriberId,)}++ @Post(':projectId/transfer')+ @Auth([UserType.ADMIN, UserType.CUSTOMER])+ async transferProject(+ @Param() params: TransferProjectParamsDto,+ @Body() body: TransferProjectBodyDto,+ @CurrentUserId() userId: string,+ @Headers() headers: { origin: string },+ ) {+ const project = await this.projectService.getOwnProject(+ params.projectId,+ userId,+ )++ if (!project) {+ throw new NotFoundException('Project not found.')+ }++ const user = await this.userService.getUserByEmail(body.email)++ if (!user) {+ throw new NotFoundException('User not found.')+ }++ if (user.id === userId) {+ throw new ConflictException('You cannot transfer project to yourself.')+ }++ await this.projectService.transferProject(+ params.projectId,+ project.name,+ user.id,+ user.email,+ headers.origin,+ )+ }}diff --git a/src/project/project.service.ts b/src/project/project.service.tsindex e70bd5fd8..152fd2005 100644--- a/src/project/project.service.ts+++ b/src/project/project.service.ts@@ -44,6 +44,8 @@ import {ORIGINS_REGEX,getRedisProjectKey,redisProjectCacheTimeout,+ isDevelopment,+ PRODUCTION_ORIGIN,} from '../common/constants'import { getProjectsClickhouse } from '../common/utils'import { ProjectSubscriber } from './entity'@@ -347,13 +349,22 @@ export class ProjectService {}}- async removeDataFromClickhouse(pid: string, from: string, to: string): Promise<void> {- const queryAnalytics = 'ALTER TABLE analytics DELETE WHERE pid = {pid:FixedString(12)} AND created BETWEEN {from:String} AND {to:String}'- const queryCustomEvents = 'ALTER TABLE customEV DELETE WHERE pid = {pid:FixedString(12)} AND created BETWEEN {from:String} AND {to:String}'- const queryPerformance = 'ALTER TABLE performance DELETE WHERE pid = {pid:FixedString(12)} AND created BETWEEN {from:String} AND {to:String}'+ async removeDataFromClickhouse(+ pid: string,+ from: string,+ to: string,+ ): Promise<void> {+ const queryAnalytics =+ 'ALTER TABLE analytics DELETE WHERE pid = {pid:FixedString(12)} AND created BETWEEN {from:String} AND {to:String}'+ const queryCustomEvents =+ 'ALTER TABLE customEV DELETE WHERE pid = {pid:FixedString(12)} AND created BETWEEN {from:String} AND {to:String}'+ const queryPerformance =+ 'ALTER TABLE performance DELETE WHERE pid = {pid:FixedString(12)} AND created BETWEEN {from:String} AND {to:String}'const params = {params: {- pid, from, to,+ pid,+ from,+ to,},}@@ -613,4 +624,33 @@ export class ProjectService {})return projects.map(project => project.project)}++ async getOwnProject(projectId: string, userId: string) {+ return this.projectsRepository.findOne({+ where: { id: projectId, admin: { id: userId } },+ })+ }++ async transferProject(+ projectId: string,+ name: string,+ userId: string,+ email: string,+ origin: string,+ ) {+ const actionToken = await this.actionTokens.createActionToken(+ userId,+ ActionTokenType.TRANSFER_PROJECT,+ projectId,+ )++ const url = `${+ isDevelopment ? origin : PRODUCTION_ORIGIN+ }/projects/${projectId}/transfer?token=${actionToken.id}`++ await this.mailerService.sendEmail(email, LetterTemplate.ProjectTransfer, {+ url,+ name,+ })+ }}diff --git a/src/user/user.service.ts b/src/user/user.service.tsindex 83ab245c0..14704aedc 100644--- a/src/user/user.service.ts+++ b/src/user/user.service.ts@@ -210,4 +210,8 @@ export class UserService {async getUser(id: string) {return this.usersRepository.findOne({ id })}++ async getUserByEmail(email: string) {+ return this.usersRepository.findOne({ where: { email } })+ }}