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!

Kill affiliate program

Blue Mouse3c9c2baf7b26
diff --git a/backend/.env.example b/backend/.env.example
index f8a9bd298..ab8a43909 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -85,10 +85,6 @@ SENTRY_DSN=''
# Cloudflare Proxy
CLOUDFLARE_PROXY_ENABLED=false
-# Paypal (used for payouts to referrers)
-PAYPAL_CLIENT_ID=
-PAYPAL_CLIENT_SECRET=
-
# Load balancing
IS_PRIMARY_NODE=true
diff --git a/backend/apps/cloud/src/auth/auth.controller.ts b/backend/apps/cloud/src/auth/auth.controller.ts
index 72dad1e12..157fb3767 100644
--- a/backend/apps/cloud/src/auth/auth.controller.ts
+++ b/backend/apps/cloud/src/auth/auth.controller.ts
@@ -116,19 +116,15 @@ export class AuthController {
throw new ConflictException(i18n.t('auth.passwordSameAsEmail'))
}
- const referrerID = await this.authService.getReferrerId(body.refCode)
-
const newUser = await this.authService.createUnverifiedUser(
body.email,
body.password,
- referrerID,
)
trackCustom(ip, headers['user-agent'], {
ev: 'SIGNUP',
meta: {
method: 'email',
- isReferred: !!referrerID,
},
})
@@ -491,15 +487,9 @@ export class AuthController {
): Promise<any> {
const ip = getIPFromHeaders(headers) || reqIP || ''
- const { hash, provider, refCode } = body
+ const { hash, provider } = body
- return this.authService.authenticateSSO(
- hash,
- headers,
- ip,
- provider,
- refCode,
- )
+ return this.authService.authenticateSSO(hash, headers, ip, provider)
}
@ApiBearerAuth()
diff --git a/backend/apps/cloud/src/auth/auth.service.ts b/backend/apps/cloud/src/auth/auth.service.ts
index fa5a83923..4fbd88d4a 100644
--- a/backend/apps/cloud/src/auth/auth.service.ts
+++ b/backend/apps/cloud/src/auth/auth.service.ts
@@ -171,14 +171,12 @@ export class AuthService {
public async createUnverifiedUser(
email: string,
password: string,
- referrerID?: string,
): Promise<User> {
const hashedPassword = await this.hashPassword(password)
const user = await this.userService.createUser({
email,
password: hashedPassword, // Using the password field is incorrect.
- referrerID,
})
await this.sendVerificationEmail(user.id, user.email)
@@ -569,7 +567,7 @@ export class AuthService {
}
}
- async registerUserGoogle(sub: string, email: string, referrerId?: string) {
+ async registerUserGoogle(sub: string, email: string) {
const query: UserGoogleDTO = {
googleId: sub,
trialEndDate: dayjs
@@ -580,7 +578,6 @@ export class AuthService {
isActive: true,
emailRequests: 0,
email,
- referrerId,
}
const userWithSameEmail = await this.userService.findOne({
@@ -647,48 +644,20 @@ export class AuthService {
return payload
}
- async getReferrerId(refCode?: string): Promise<string | undefined> {
- if (!refCode) {
- return undefined
- }
-
- try {
- let referrerID
-
- if (refCode) {
- const referrer = await this.userService.findOne({
- where: { refCode },
- })
-
- if (referrer) {
- referrerID = referrer.id
- }
- }
-
- return referrerID
- } catch (reason) {
- console.error(
- `[ERROR][AuthService -> getReferrerId]: ${reason} - ${refCode}`,
- )
- return undefined
- }
- }
-
async authenticateSSO(
ssoHash: string,
headers: Record<string, string>,
ip: string,
provider: SSOProviders,
- refCode?: string,
) {
this.assertSSOProviderMatchesHash(provider, ssoHash)
if (provider === SSOProviders.GOOGLE) {
- return this.authenticateGoogle(ssoHash, headers, ip, refCode)
+ return this.authenticateGoogle(ssoHash, headers, ip)
}
if (provider === SSOProviders.GITHUB) {
- return this.authenticateGithub(ssoHash, headers, ip, refCode)
+ return this.authenticateGithub(ssoHash, headers, ip)
}
throw new BadRequestException('Unknown SSO provider supplied')
@@ -698,7 +667,6 @@ export class AuthService {
ssoHash: string,
headers: Record<string, string>,
ip: string,
- refCode?: string,
) {
const { sub, email } = await this.processHash(ssoHash)
@@ -715,15 +683,12 @@ export class AuthService {
})
if (!user) {
- const referrerId = await this.getReferrerId(refCode)
-
- const data = await this.registerUserGoogle(sub, email, referrerId)
+ const data = await this.registerUserGoogle(sub, email)
trackCustom(ip, headers['user-agent'], {
ev: 'SIGNUP',
meta: {
method: 'google',
- isReferred: !!referrerId,
},
})
@@ -1002,7 +967,7 @@ export class AuthService {
)
}
- async registerUserGithub(id: number, email: string, referrerId?: string) {
+ async registerUserGithub(id: number, email: string) {
const query: UserGithubDTO = {
githubId: id,
trialEndDate: dayjs
@@ -1013,7 +978,6 @@ export class AuthService {
isActive: true,
emailRequests: 0,
email,
- referrerId,
}
const userWithSameEmail = await this.userService.findOne({
@@ -1133,7 +1097,6 @@ export class AuthService {
ssoHash: string,
headers: Record<string, string>,
ip: string,
- refCode?: string,
) {
const { id, email } = await this.processHash(ssoHash)
@@ -1150,15 +1113,12 @@ export class AuthService {
})
if (!user) {
- const referrerId = await this.getReferrerId(refCode)
-
- const data = await this.registerUserGithub(id, email, referrerId)
+ const data = await this.registerUserGithub(id, email)
trackCustom(ip, headers['user-agent'], {
ev: 'SIGNUP',
meta: {
method: 'github',
- isReferred: !!referrerId,
},
})
diff --git a/backend/apps/cloud/src/auth/dtos/register.dto.ts b/backend/apps/cloud/src/auth/dtos/register.dto.ts
index bf4e9b35b..4684b580b 100644
--- a/backend/apps/cloud/src/auth/dtos/register.dto.ts
+++ b/backend/apps/cloud/src/auth/dtos/register.dto.ts
@@ -5,7 +5,6 @@ import {
IsBoolean,
MaxLength,
MinLength,
- IsOptional,
} from 'class-validator'
export class RegisterRequestDto {
@@ -35,13 +34,6 @@ export class RegisterRequestDto {
@IsNotEmpty({ message: 'This field is required.' })
@IsBoolean({ message: 'Please enter the valid value (true or false).' })
public readonly checkIfLeaked: boolean
-
- @ApiProperty({
- description: 'Affiliate code',
- example: 'ABCDEFGH',
- })
- @IsOptional()
- public readonly refCode?: string
}
export class RegisterResponseDto {
diff --git a/backend/apps/cloud/src/auth/dtos/sso-get-jwt-by-hash.dto.ts b/backend/apps/cloud/src/auth/dtos/sso-get-jwt-by-hash.dto.ts
index 20e914303..cc75d45e4 100644
--- a/backend/apps/cloud/src/auth/dtos/sso-get-jwt-by-hash.dto.ts
+++ b/backend/apps/cloud/src/auth/dtos/sso-get-jwt-by-hash.dto.ts
@@ -1,5 +1,5 @@
import { ApiProperty } from '@nestjs/swagger'
-import { IsEnum, IsString, IsOptional, Matches } from 'class-validator'
+import { IsEnum, IsString, Matches } from 'class-validator'
import { SSOProviders } from './sso-generate.dto'
@@ -23,11 +23,4 @@ export class SSOGetJWTByHashDto {
})
@IsEnum(SSOProviders)
provider: SSOProviders
-
- @ApiProperty({
- description: 'Affiliate code',
- example: 'ABCDEFGH',
- })
- @IsOptional()
- refCode?: string
}
diff --git a/backend/apps/cloud/src/common/constants.ts b/backend/apps/cloud/src/common/constants.ts
index c514abee4..045c4ff22 100644
--- a/backend/apps/cloud/src/common/constants.ts
+++ b/backend/apps/cloud/src/common/constants.ts
@@ -4,8 +4,7 @@ import _toNumber from 'lodash/toNumber'
import 'dotenv/config'
import { deriveKey, hash } from './utils'
-const { PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET, EMAIL_ACTION_ENCRYPTION_KEY } =
- process.env
+const { EMAIL_ACTION_ENCRYPTION_KEY } = process.env
const redis = new Redis(
_toNumber(process.env.REDIS_PORT),
@@ -63,8 +62,6 @@ const redisUserUsageinfoCacheTimeout = 300
// 30 minues -> the amount of time analytics requests within one session are counted as non-unique
const UNIQUE_SESSION_LIFE_TIME = 1800
-const AFFILIATE_CUT = 0.2
-
// send email warning when 85% of events in tier are used
const SEND_WARNING_AT_PERC = 85
@@ -207,14 +204,11 @@ export {
PERFORMANCE_COLUMNS,
sentryIgnoreErrors,
isProxiedByCloudflare,
- PAYPAL_CLIENT_ID,
- PAYPAL_CLIENT_SECRET,
BLOG_POSTS_PATH,
MIN_PAGES_IN_FUNNEL,
MAX_PAGES_IN_FUNNEL,
MAX_FUNNELS,
ALL_COLUMNS,
TRAFFIC_SPIKE_ALLOWED_PERCENTAGE,
- AFFILIATE_CUT,
PID_REGEX,
}
diff --git a/backend/apps/cloud/src/common/templates/en/paypal-email-update.html b/backend/apps/cloud/src/common/templates/en/paypal-email-update.html
deleted file mode 100644
index f8204f738..000000000
--- a/backend/apps/cloud/src/common/templates/en/paypal-email-update.html
+++ /dev/null
@@ -1,4 +0,0 @@
-Your affiliate payout (PayPal) email address has been changed.
-<br/>
-<br/>
-If you have not done so, please reply to this email.
diff --git a/backend/apps/cloud/src/common/utils.ts b/backend/apps/cloud/src/common/utils.ts
index be0c435ab..7e18b42c3 100644
--- a/backend/apps/cloud/src/common/utils.ts
+++ b/backend/apps/cloud/src/common/utils.ts
@@ -206,13 +206,6 @@ export const generateRecoveryCode = () =>
capitalization: 'uppercase',
})
-export const generateRefCode = () =>
- randomstring.generate({
- length: 8,
- charset: 'alphanumeric',
- capitalization: 'uppercase',
- })
-
export const millisecondsToSeconds = (milliseconds: number) =>
milliseconds / 1000
diff --git a/backend/apps/cloud/src/experiment/experiment.service.ts b/backend/apps/cloud/src/experiment/experiment.service.ts
index fb60cb10a..ca043888e 100644
--- a/backend/apps/cloud/src/experiment/experiment.service.ts
+++ b/backend/apps/cloud/src/experiment/experiment.service.ts
@@ -1,6 +1,11 @@
import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
-import { FindManyOptions, FindOneOptions, Repository, EntityManager } from 'typeorm'
+import {
+ FindManyOptions,
+ FindOneOptions,
+ Repository,
+ EntityManager,
+} from 'typeorm'
import { Pagination, PaginationOptionsInterface } from '../common/pagination'
import { Experiment } from './entity/experiment.entity'
import { ExperimentVariant } from './entity/experiment-variant.entity'
diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.service.ts b/backend/apps/cloud/src/feature-flag/feature-flag.service.ts
index ba4dec0f7..566b2095a 100644
--- a/backend/apps/cloud/src/feature-flag/feature-flag.service.ts
+++ b/backend/apps/cloud/src/feature-flag/feature-flag.service.ts
@@ -1,6 +1,11 @@
import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
-import { FindManyOptions, FindOneOptions, Repository, EntityManager } from 'typeorm'
+import {
+ FindManyOptions,
+ FindOneOptions,
+ Repository,
+ EntityManager,
+} from 'typeorm'
import { Pagination, PaginationOptionsInterface } from '../common/pagination'
import { FeatureFlag } from './entity/feature-flag.entity'
import {
diff --git a/backend/apps/cloud/src/mailer/letter.ts b/backend/apps/cloud/src/mailer/letter.ts
index 2b4102f30..ae0b59577 100644
--- a/backend/apps/cloud/src/mailer/letter.ts
+++ b/backend/apps/cloud/src/mailer/letter.ts
@@ -14,7 +14,6 @@ export enum LetterTemplate {
TrialEndsTomorrow = 'trial-ends-tomorrow',
ProjectSubscriberInvitation = 'project-subscriber-invitation',
ProjectTransfer = 'project-transfer',
- PayPalEmailUpdate = 'paypal-email-update',
UsageOverLimit = 'usage-over-limit',
DashboardLockedExceedingLimits = 'dashboard-locked-exceeding-limits',
DashboardLockedPaymentFailure = 'dashboard-locked-payment-failure',
diff --git a/backend/apps/cloud/src/mailer/mailer.service.ts b/backend/apps/cloud/src/mailer/mailer.service.ts
index 098971ea1..713788e06 100644
--- a/backend/apps/cloud/src/mailer/mailer.service.ts
+++ b/backend/apps/cloud/src/mailer/mailer.service.ts
@@ -92,11 +92,6 @@ const metaInfoJson = {
`A Swetrix user offers to transfer ${p.name} project to your account`,
},
},
- [LetterTemplate.PayPalEmailUpdate]: {
- subject: {
- en: () => 'Your PayPal email has been updated',
- },
- },
[LetterTemplate.UsageOverLimit]: {
subject: {
en: () =>
diff --git a/backend/apps/cloud/src/payouts/entities/payouts.entity.ts b/backend/apps/cloud/src/payouts/entities/payouts.entity.ts
deleted file mode 100644
index 9ec95f9a3..000000000
--- a/backend/apps/cloud/src/payouts/entities/payouts.entity.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { Entity, PrimaryGeneratedColumn, ManyToOne, Column } from 'typeorm'
-import { User } from '../../user/entities/user.entity'
-
-export enum PayoutStatus {
- /**
- * The payout is ready to be paid on the next payout date.
- * This status is assigned when we received the next payment for the subscription from the user.
- */
- processing = 'processing',
- /**
- * The payout is pending and will be paid automatically unless user cancels their subscriptions or makes a refund or chargeback.
- */
- pending = 'pending',
- /**
- * The payout was paid to the referrer.
- */
- paid = 'paid',
- /**
- * The payout was suspended for some reason. It won't be paid automatically and will require manual intervention.
- */
- suspended = 'suspended',
-}
-
-@Entity()
-export class Payout {
- @PrimaryGeneratedColumn('uuid')
- id: string
-
- // The date when the payout was created
- @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
- created: Date
-
- // The amount of the payout
- @Column({
- type: 'decimal',
- })
- amount: number
-
- // The currency of the payout
- @Column({
- type: 'varchar',
- length: 3,
- })
- currency: string
-
- // The referral ID (user which was referred)
- @Column('varchar', { length: 36 })
- referralId: string
-
- // The status of the payout
- @Column({
- type: 'enum',
- enum: PayoutStatus,
- default: PayoutStatus.pending,
- })
- status: PayoutStatus
-
- // The date when the payout was paid
- @Column({
- type: 'timestamp',
- nullable: true,
- })
- paidAt: Date
-
- // The transaction ID of the payout
- @Column({
- type: 'varchar',
- length: 50,
- nullable: true,
- })
- transactionId: string
-
- // The referrer (user which receives the payout)
- @ManyToOne(() => User, user => user.payouts)
- user: User
-}
diff --git a/backend/apps/cloud/src/payouts/payouts.module.ts b/backend/apps/cloud/src/payouts/payouts.module.ts
deleted file mode 100644
index 131228fb2..000000000
--- a/backend/apps/cloud/src/payouts/payouts.module.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { Module } from '@nestjs/common'
-import { TypeOrmModule } from '@nestjs/typeorm'
-
-import { PayoutsService } from './payouts.service'
-import { Payout } from './entities/payouts.entity'
-import { AppLoggerModule } from '../logger/logger.module'
-
-@Module({
- imports: [TypeOrmModule.forFeature([Payout]), AppLoggerModule],
- providers: [PayoutsService],
- exports: [PayoutsService],
-})
-export class PayoutsModule {}
diff --git a/backend/apps/cloud/src/payouts/payouts.service.ts b/backend/apps/cloud/src/payouts/payouts.service.ts
deleted file mode 100644
index 4b33229bd..000000000
--- a/backend/apps/cloud/src/payouts/payouts.service.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { Injectable } from '@nestjs/common'
-import { InjectRepository } from '@nestjs/typeorm'
-import { FindManyOptions, Repository } from 'typeorm'
-import { Payout, PayoutStatus } from './entities/payouts.entity'
-import { Pagination, PaginationOptionsInterface } from '../common/pagination'
-
-@Injectable()
-export class PayoutsService {
- constructor(
- @InjectRepository(Payout)
- private payoutsRepository: Repository<Payout>,
- ) {}
-
- async create(
- payout: Pick<Payout, 'amount' | 'currency' | 'referralId' | 'user'>,
- ): Promise<Payout> {
- return this.payoutsRepository.save(payout)
- }
-
- async update(criteria: any, update: Record<string, unknown>): Promise<any> {
- return this.payoutsRepository.update(criteria, update)
- }
-
- async delete(id: string): Promise<any> {
- return this.payoutsRepository.delete(id)
- }
-
- async find(params: any): Promise<Payout[]> {
- return this.payoutsRepository.find(params)
- }
-
- async findOne(where: any, params: any = {}): Promise<Payout> {
- return this.payoutsRepository.findOne({
- where,
- ...params,
- })
- }
-
- async sumAmountByReferrerId(
- referrerId: string,
- status: PayoutStatus,
- ): Promise<number> {
- const result = await this.payoutsRepository
- .createQueryBuilder('payout')
- .select('SUM(payout.amount)', 'sum')
- .where('payout.userId = :referrerId', { referrerId })
- .andWhere('payout.status = :status', { status })
- .getRawOne()
-
- return result.sum
- }
-
- async paginate(
- options: PaginationOptionsInterface,
- where: FindManyOptions<Payout>['where'],
- ): Promise<Pagination<Payout>> {
- const [results, total] = await this.payoutsRepository.findAndCount({
- take: options.take || 100,
- skip: options.skip || 0,
- where,
- order: {
- created: 'DESC',
- },
- })
-
- return new Pagination<Payout>({
- results,
- total,
- })
- }
-}
diff --git a/backend/apps/cloud/src/task-manager/task-manager.module.ts b/backend/apps/cloud/src/task-manager/task-manager.module.ts
index 5f9824083..f889f3df6 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.module.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.module.ts
@@ -7,7 +7,6 @@ import { MailerModule } from '../mailer/mailer.module'
import { UserModule } from '../user/user.module'
import { ProjectModule } from '../project/project.module'
import { AnalyticsModule } from '../analytics/analytics.module'
-import { PayoutsModule } from '../payouts/payouts.module'
import { ActionTokensModule } from '../action-tokens/action-tokens.module'
import { AppLoggerModule } from '../logger/logger.module'
import { Message } from '../integrations/telegram/entities/message.entity'
@@ -26,7 +25,6 @@ import { RevenueModule } from '../revenue/revenue.module'
forwardRef(() => AnalyticsModule),
AppLoggerModule,
TypeOrmModule.forFeature([Message]),
- PayoutsModule,
DiscordModule,
SlackModule,
GoalModule,
diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.ts
index 4b370e285..addaffa19 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts
@@ -2,7 +2,6 @@ import { Injectable } from '@nestjs/common'
import { Cron, CronExpression } from '@nestjs/schedule'
import { IsNull, LessThan, In, Not, Between } from 'typeorm'
import { ConfigService } from '@nestjs/config'
-import Paypal from '@paypal/payouts-sdk'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import _isEmpty from 'lodash/isEmpty'
@@ -28,10 +27,8 @@ import { LetterTemplate } from '../mailer/letter'
import { AnalyticsService } from '../analytics/analytics.service'
import { SaltService } from '../analytics/salt.service'
import { TimeBucketType } from '../analytics/dto/getData.dto'
-import { PayoutsService } from '../payouts/payouts.service'
import { GoalService } from '../goal/goal.service'
import { Goal, GoalType, GoalMatchType } from '../goal/entity/goal.entity'
-import { PayoutStatus } from '../payouts/entities/payouts.entity'
import {
ACCOUNT_PLANS,
PlanCode,
@@ -46,10 +43,7 @@ import {
SEND_WARNING_AT_PERC,
PROJECT_INVITE_EXPIRE,
JWT_REFRESH_TOKEN_LIFETIME,
- PAYPAL_CLIENT_ID,
- PAYPAL_CLIENT_SECRET,
TRAFFIC_SPIKE_ALLOWED_PERCENTAGE,
- isDevelopment,
} from '../common/constants'
import { clickhouse } from '../common/integrations/clickhouse'
import { CHPlanUsage } from './interfaces'
@@ -67,16 +61,6 @@ import { StripeAdapter } from '../revenue/adapters/stripe.adapter'
dayjs.extend(utc)
-let paypalClient
-
-if (PAYPAL_CLIENT_ID && PAYPAL_CLIENT_SECRET) {
- const environment = new Paypal.core.SandboxEnvironment(
- PAYPAL_CLIENT_ID,
- PAYPAL_CLIENT_SECRET,
- )
- paypalClient = new Paypal.core.PayPalHttpClient(environment)
-}
-
const getQueryTime = (time: QueryTime): number => {
if (time === QueryTime.LAST_15_MINUTES) return 15 * 60
if (time === QueryTime.LAST_30_MINUTES) return 30 * 60
@@ -322,7 +306,6 @@ export class TaskManagerService {
private readonly alertService: AlertService,
private readonly logger: AppLoggerService,
private readonly telegramService: TelegramService,
- private readonly payoutsService: PayoutsService,
private readonly configService: ConfigService,
private readonly discordService: DiscordService,
private readonly slackService: SlackService,
@@ -1963,112 +1946,4 @@ export class TaskManagerService {
await this.userService.deleteRefreshTokensWhere(where)
}
-
- @Cron(CronExpression.EVERY_1ST_DAY_OF_MONTH_AT_NOON)
- async payReferrers() {
- if (isDevelopment || !paypalClient) {
- return
- }
-
- const payoutsToProcess = await this.payoutsService.find({
- where: {
- status: PayoutStatus.processing,
- },
- relations: ['user'],
- })
-
- if (_isEmpty(payoutsToProcess)) {
- return
- }
-
- // A map of emails to pay and their amounts
- const payouts: Record<string, { amount: number; payoutsIds: string[] }> =
- Object.create(null)
-
- for (let i = 0; i < _size(payoutsToProcess); ++i) {
- const key = payoutsToProcess[i].user.paypalPaymentsEmail
-
- if (!key) {
- continue
- }
-
- if (!payouts[key]) {
- payouts[key] = {
- amount: 0,
- payoutsIds: [],
- }
- }
-
- payouts[key].amount += _toNumber(payoutsToProcess[i].amount)
- payouts[key].payoutsIds.push(payoutsToProcess[i].id)
- }
-
- const requestBody = {
- sender_batch_header: {
- recipient_type: 'EMAIL',
- email_message: 'Swetrix referral program payout.',
- note: 'Swetrix referral program payout.',
- },
- items: _reduce(
- payouts,
- (acc, value: any, key) => {
- acc.push({
- recipient_type: 'EMAIL',
- amount: {
- value: value.amount.toFixed(2),
- currency: 'USD',
- },
- receiver: key,
- note: `Your Swetrix $${value.amount.toFixed(2)} payout.`,
- })
-
- return acc
- },
- [],
- ),
- }
-
- // Send the request to PayPal
- const request = new Paypal.payouts.PayoutsPostRequest()
- request.requestBody(requestBody)
-
- const response = await paypalClient.execute(request)
-
- if (response.statusCode !== 201) {
- console.error(
- `[CRON](payReferrers) An error occured while executing a request to pay referrers: ${JSON.stringify(
- response,
- null,
- 2,
- )}`,
- )
- console.error(`Payouts: ${JSON.stringify(payouts, null, 2)}`)
-
- // Update the payouts in the DB
- await this.payoutsService.update(
- {
- where: {
- id: In(_map(payoutsToProcess, 'id')),
- },
- },
- {
- status: PayoutStatus.suspended,
- },
- )
- return
- }
-
- // Update the payouts in the DB
- await this.payoutsService.update(
- {
- where: {
- id: In(_map(payoutsToProcess, 'id')),
- },
- },
- {
- status: PayoutStatus.paid,
- transactionId: response.result?.batch_header?.payout_batch_id,
- },
- )
- }
}
diff --git a/backend/apps/cloud/src/user/dto/user-github.dto.ts b/backend/apps/cloud/src/user/dto/user-github.dto.ts
index 91a232fa0..9a205397a 100644
--- a/backend/apps/cloud/src/user/dto/user-github.dto.ts
+++ b/backend/apps/cloud/src/user/dto/user-github.dto.ts
@@ -23,7 +23,4 @@ export class UserGithubDTO {
@ApiProperty({ example: true, required: false })
isActive: boolean
-
- @ApiProperty({ example: 'uuid-of-referrer', required: false })
- referrerId?: string
}
diff --git a/backend/apps/cloud/src/user/dto/user-google.dto.ts b/backend/apps/cloud/src/user/dto/user-google.dto.ts
index 5fb31392c..025fb1e0b 100644
--- a/backend/apps/cloud/src/user/dto/user-google.dto.ts
+++ b/backend/apps/cloud/src/user/dto/user-google.dto.ts
@@ -23,7 +23,4 @@ export class UserGoogleDTO {
@ApiProperty({ example: true, required: false })
isActive: boolean
-
- @ApiProperty({ example: 'uuid-of-referrer', required: false })
- referrerId?: string
}
diff --git a/backend/apps/cloud/src/user/entities/user.entity.ts b/backend/apps/cloud/src/user/entities/user.entity.ts
index 236af5b1a..44ce93e76 100644
--- a/backend/apps/cloud/src/user/entities/user.entity.ts
+++ b/backend/apps/cloud/src/user/entities/user.entity.ts
@@ -9,7 +9,6 @@ import {
import { ActionToken } from '../../action-tokens/action-token.entity'
import { Project } from '../../project/entity/project.entity'
import { ProjectShare } from '../../project/entity/project-share.entity'
-import { Payout } from '../../payouts/entities/payouts.entity'
import { RefreshToken } from './refresh-token.entity'
import { OrganisationMember } from '../../organisation/entity/organisation-member.entity'
@@ -313,21 +312,6 @@ export class User {
@Column({ default: false })
isAccountBillingSuspended: boolean
- /* Affiliate system related fields */
- @Column('varchar', { length: 8, default: null })
- refCode: string | null
-
- @Column('varchar', { default: null })
- referrerID: string | null
-
- @Column('varchar', {
- length: 254,
- unique: true,
- default: null,
- nullable: true,
- })
- paypalPaymentsEmail: string | null
-
@BeforeUpdate()
updateTimestamp() {
this.updated = new Date()
@@ -338,9 +322,6 @@ export class User {
@OneToMany(() => Project, project => project.admin)
projects: Project[]
- @OneToMany(() => Payout, payout => payout.user)
- payouts: Payout[]
-
@OneToMany(() => ProjectShare, sharedProjects => sharedProjects.user)
sharedProjects: ProjectShare[]
diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.ts
index b6c9878be..334ccaa0c 100644
--- a/backend/apps/cloud/src/user/user.controller.ts
+++ b/backend/apps/cloud/src/user/user.controller.ts
@@ -13,7 +13,6 @@ import {
ConflictException,
Headers,
Ip,
- Patch,
NotFoundException,
} from '@nestjs/common'
import { Request } from 'express'
@@ -59,7 +58,6 @@ import {
checkRateLimit,
getGeoDetails,
getIPFromHeaders,
- generateRefCode,
} from '../common/utils'
import { IUsageInfo, IMetaInfo } from './interfaces'
import { ReportFrequency } from '../project/enums'
@@ -141,40 +139,6 @@ export class UserController {
return this.userService.update(userId, { receiveLoginNotifications })
}
- @ApiBearerAuth()
- @Patch('/set-paypal-email')
- async setPaypalEmail(
- @CurrentUserId() userId: string,
- @Body('paypalPaymentsEmail') paypalPaymentsEmail: string,
- @Headers() headers,
- @Ip() reqIP,
- ): Promise<User> {
- this.logger.log(
- { userId, paypalPaymentsEmail },
- 'PATCH /user/set-paypal-email',
- )
-
- const ip = getIPFromHeaders(headers) || reqIP || ''
-
- await checkRateLimit(ip, 'set-paypal-email', 10, 3600)
- await checkRateLimit(userId, 'set-paypal-email', 10, 3600)
-
- const user = await this.userService.findOne({ where: { id: userId } })
-
- if (!user) {
- throw new BadRequestException('User not found')
- }
-
- await this.mailerService.sendEmail(
- user.email,
- LetterTemplate.PayPalEmailUpdate,
- )
-
- return this.userService.update(userId, {
- paypalPaymentsEmail: paypalPaymentsEmail || null,
- })
- }
-
@ApiBearerAuth()
@Post('/api-key')
async generateApiKey(
@@ -688,7 +652,6 @@ export class UserController {
'timezone',
'theme',
'showLiveVisitorsInTitle',
- 'paypalPaymentsEmail',
'slackWebhookUrl',
'discordWebhookUrl',
'telegramChatId',
@@ -716,62 +679,6 @@ export class UserController {
}
}
- @ApiBearerAuth()
- @Get('referrals')
- async getReferralsList(@CurrentUserId() id: string): Promise<any> {
- this.logger.log({ id }, 'GET /user/referrals')
-
- const user = await this.userService.findOne({ where: { id } })
-
- if (!user) {
- throw new BadRequestException('User not found')
- }
-
- return this.userService.getReferralsList(user)
- }
-
- @ApiBearerAuth()
- @Get('payouts/info')
- async getPayoutsInfo(@CurrentUserId() id: string): Promise<any> {
- this.logger.log({ id }, 'GET /user/payouts/info')
-
- const user = await this.userService.findOne({ where: { id } })
-
- if (!user) {
- throw new BadRequestException('User not found')
- }
-
- return this.userService.getPayoutsInfo(user)
- }
-
- @ApiBearerAuth()
- @Post('generate-ref-code')
- async generateRefCode(@CurrentUserId() id: string): Promise<any> {
- this.logger.log({ id }, 'POST /user/generate-ref-code')
-
- const user = await this.userService.findOne({ where: { id } })
-
- if (!user) {
- throw new BadRequestException('User not found')
- }
-
- if (user.refCode) {
- throw new BadRequestException('Referral code already exists')
- }
-
- let refCode = generateRefCode()
-
- while (!(await this.userService.isRefCodeUnique(refCode))) {
- refCode = generateRefCode()
- }
-
- await this.userService.update(id, { refCode })
-
- return {
- refCode,
- }
- }
-
@Get('metainfo')
@Public()
async getMetaInfo(
diff --git a/backend/apps/cloud/src/user/user.module.ts b/backend/apps/cloud/src/user/user.module.ts
index 8e2d8463a..4515c1c41 100644
--- a/backend/apps/cloud/src/user/user.module.ts
+++ b/backend/apps/cloud/src/user/user.module.ts
@@ -9,7 +9,6 @@ import { User } from './entities/user.entity'
import { ActionTokensModule } from '../action-tokens/action-tokens.module'
import { MailerModule } from '../mailer/mailer.module'
import { AuthModule } from '../auth/auth.module'
-import { PayoutsModule } from '../payouts/payouts.module'
import { AppLoggerModule } from '../logger/logger.module'
import { ProjectModule } from '../project/project.module'
import { RefreshToken } from './entities/refresh-token.entity'
@@ -26,7 +25,6 @@ import { OrganisationModule } from '../organisation/organisation.module'
AppLoggerModule,
ProjectModule,
OrganisationModule,
- PayoutsModule,
HttpModule,
],
providers: [UserService, TelegramService],
diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.ts
index 8b3b152e5..ca382442e 100644
--- a/backend/apps/cloud/src/user/user.service.ts
+++ b/backend/apps/cloud/src/user/user.service.ts
@@ -25,7 +25,6 @@ import _isNull from 'lodash/isNull'
import _toNumber from 'lodash/toNumber'
import { Pagination, PaginationOptionsInterface } from '../common/pagination'
-import { PayoutsService } from '../payouts/payouts.service'
import {
User,
ACCOUNT_PLANS,
@@ -33,7 +32,6 @@ import {
BillingFrequency,
PlanCode,
} from './entities/user.entity'
-import { PayoutStatus } from '../payouts/entities/payouts.entity'
import { UserProfileDTO } from './dto/user.dto'
import { RefreshToken } from './entities/refresh-token.entity'
import { DeleteFeedback } from './entities/delete-feedback.entity'
@@ -110,7 +108,6 @@ export class UserService {
private readonly refreshTokenRepository: Repository<RefreshToken>,
@InjectRepository(DeleteFeedback)
private readonly deleteFeedbackRepository: Repository<DeleteFeedback>,
- private readonly payoutsService: PayoutsService,
private readonly organisationService: OrganisationService,
) {}
@@ -223,9 +220,7 @@ export class UserService {
return this.usersRepository.findOne({ where: { email } })
}
- public async createUser(
- user: Pick<User, 'email' | 'password' | 'referrerID'>,
- ) {
+ public async createUser(user: Pick<User, 'email' | 'password'>) {
return this.usersRepository.save({
...user,
trialEndDate: dayjs
@@ -522,18 +517,6 @@ export class UserService {
await this.update(id, updateParams)
}
- async getPayoutsList(user: User, take = 20, skip = 0) {
- return this.payoutsService.paginate(
- {
- take,
- skip,
- },
- {
- user: { id: user.id },
- },
- )
- }
-
createUnsubscribeKey(userId: string): string {
return encodeURIComponent(
CryptoJS.Rabbit.encrypt(userId, EMAIL_ACTION_ENCRYPTION_KEY).toString(),
@@ -548,77 +531,6 @@ export class UserService {
return bytes.toString(CryptoJS.enc.Utf8)
}
- async getReferralsList(user: User): Promise<Partial<User>[]> {
- return this.usersRepository
- .createQueryBuilder('user')
- .select([
- 'user.planCode',
- 'user.created',
- 'user.billingFrequency',
- 'user.tierCurrency',
- ])
- .where('user.referrerID = :id', { id: user.id })
- .andWhere('user.planCode != :none', { none: PlanCode.none })
- .andWhere('user.planCode != :trial', { trial: PlanCode.trial })
- .andWhere('user.planCode != :free', { free: PlanCode.free })
- .orderBy('user.created', 'DESC')
- .getMany()
- }
-
- async getPayoutsInfo(user: User): Promise<any> {
- const { id } = user
-
- const trials = await this.count({
- where: {
- referrerID: id,
- planCode: In([PlanCode.trial, PlanCode.none]),
- },
- })
-
- const subscribers = _toNumber(
- (
- await this.usersRepository
- .createQueryBuilder('user')
- .select('COUNT(user.id)', 'count')
- .where('user.referrerID = :id', { id })
- .andWhere('user.planCode != :none', { none: PlanCode.none })
- .andWhere('user.planCode != :trial', { trial: PlanCode.trial })
- .getRawOne()
- )?.count,
- )
-
- let paid = await this.payoutsService.sumAmountByReferrerId(
- id,
- PayoutStatus.paid,
- )
- let nextPayout = await this.payoutsService.sumAmountByReferrerId(
- id,
- PayoutStatus.processing,
- )
- let pending = await this.payoutsService.sumAmountByReferrerId(
- id,
- PayoutStatus.pending,
- )
-
- paid = paid ?? 0
- nextPayout = nextPayout ?? 0
- pending = pending ?? 0
-
- return {
- trials,
- subscribers,
- paid,
- nextPayout,
- pending,
- }
- }
-
- async isRefCodeUnique(code: string): Promise<boolean> {
- const user = await this.findOne({ where: { refCode: code } })
-
- return !user
- }
-
async getReportUsers(
reportFrequency:
| ReportFrequency.WEEKLY
diff --git a/backend/apps/cloud/src/webhook/webhook.controller.ts b/backend/apps/cloud/src/webhook/webhook.controller.ts
index 0f37fd3fe..bbe95696e 100644
--- a/backend/apps/cloud/src/webhook/webhook.controller.ts
+++ b/backend/apps/cloud/src/webhook/webhook.controller.ts
@@ -13,7 +13,6 @@ import _find from 'lodash/find'
import { ProjectService } from '../project/project.service'
import { getIPFromHeaders } from '../common/utils'
-import { AFFILIATE_CUT } from '../common/constants'
import {
ACCOUNT_PLANS,
BillingFrequency,
@@ -218,11 +217,7 @@ export class WebhookController {
}
case 'subscription_payment_succeeded': {
- const {
- subscription_id: subID,
- balance_earnings: balanceEarnings,
- balance_currency: balanceCurrency,
- } = body
+ const { subscription_id: subID } = body
const subscriber = await this.userService.findOne({
where: { subID },
@@ -249,34 +244,6 @@ export class WebhookController {
await this.projectService.clearProjectsRedisCacheBySubId(subID)
}
- // That user was not referred by anyone
- if (!subscriber.referrerID) {
- return
- }
-
- const referrer = await this.userService.findOne({
- where: { id: subscriber.referrerID },
- })
-
- if (!referrer) {
- this.logger.error(
- `[subscription_payment_succeeded] Cannot find the referrer with ID: ${subscriber.referrerID}`,
- )
- return
- }
-
- await this.webhookService.setReferralPayoutsToProcessing(
- subscriber.id,
- referrer,
- )
-
- await this.webhookService.addPayoutForUser(
- referrer,
- subscriber.id,
- Number(balanceEarnings) * AFFILIATE_CUT,
- balanceCurrency,
- )
-
break
}
diff --git a/backend/apps/cloud/src/webhook/webhook.module.ts b/backend/apps/cloud/src/webhook/webhook.module.ts
index b8d8b6634..3c0de4690 100644
--- a/backend/apps/cloud/src/webhook/webhook.module.ts
+++ b/backend/apps/cloud/src/webhook/webhook.module.ts
@@ -1,7 +1,6 @@
import { Module, forwardRef } from '@nestjs/common'
import { ProjectModule } from '../project/project.module'
-import { PayoutsModule } from '../payouts/payouts.module'
import { WebhookController } from './webhook.controller'
import { UserModule } from '../user/user.module'
import { AppLoggerModule } from '../logger/logger.module'
@@ -12,7 +11,6 @@ import { WebhookService } from './webhook.service'
imports: [
forwardRef(() => UserModule),
ProjectModule,
- PayoutsModule,
AppLoggerModule,
MailerModule,
],
diff --git a/backend/apps/cloud/src/webhook/webhook.service.ts b/backend/apps/cloud/src/webhook/webhook.service.ts
index f3aec3b8a..43d445ade 100644
--- a/backend/apps/cloud/src/webhook/webhook.service.ts
+++ b/backend/apps/cloud/src/webhook/webhook.service.ts
@@ -11,11 +11,8 @@ import _includes from 'lodash/includes'
import _keys from 'lodash/keys'
import _isArray from 'lodash/isArray'
import { AppLoggerService } from '../logger/logger.service'
-import { PayoutsService } from '../payouts/payouts.service'
import { ProjectService } from '../project/project.service'
import { UserService } from '../user/user.service'
-import { PayoutStatus } from '../payouts/entities/payouts.entity'
-import { User } from '../user/entities/user.entity'
import { ReportFrequency } from '../project/enums'
const PADDLE_PUB_KEY = `-----BEGIN PUBLIC KEY-----
@@ -50,7 +47,6 @@ const validator = new Validator()
export class WebhookService {
constructor(
private readonly logger: AppLoggerService,
- private readonly payoutsService: PayoutsService,
private readonly userService: UserService,
private readonly projectService: ProjectService,
) {}
@@ -105,35 +101,6 @@ export class WebhookService {
}
}
- async addPayoutForUser(
- referrer: User,
- referralId: string,
- amount: number,
- currency: string,
- ): Promise<any> {
- return this.payoutsService.create({
- amount,
- currency,
- referralId,
- user: referrer,
- })
- }
-
- async setReferralPayoutsToProcessing(
- referralId: string,
- referrer: User,
- ): Promise<any> {
- return this.payoutsService.update(
- {
- referralId,
- user: referrer,
- },
- {
- status: PayoutStatus.processing,
- },
- )
- }
-
async verifySNSRequest(payload: any): Promise<void> {
try {
await validator.validate(payload)
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index a0e88b2bf..048a42526 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -67,7 +67,10 @@ import { GetSessionDto } from './dto/get-session.dto'
import { ErrorDto } from './dto/error.dto'
import { GetErrorsDto } from './dto/get-errors.dto'
import { GetErrorDto } from './dto/get-error.dto'
-import { GetErrorOverviewDto, GetErrorOverviewOptions } from './dto/get-error-overview.dto'
+import {
+ GetErrorOverviewDto,
+ GetErrorOverviewOptions,
+} from './dto/get-error-overview.dto'
import { PatchStatusDto } from './dto/patch-status.dto'
import {
customEventTransformer,
diff --git a/backend/migrations/mysql/2025_12_21_kill_affiliate_program.sql b/backend/migrations/mysql/2025_12_21_kill_affiliate_program.sql
new file mode 100644
index 000000000..877ee47f3
--- /dev/null
+++ b/backend/migrations/mysql/2025_12_21_kill_affiliate_program.sql
@@ -0,0 +1,5 @@
+ALTER TABLE user DROP COLUMN `paypalPaymentsEmail`;
+ALTER TABLE user DROP COLUMN `refCode`;
+ALTER TABLE user DROP COLUMN `referrerID`;
+
+DROP TABLE IF EXISTS `payout`;
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 81f62341d..23217a291 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -25,7 +25,6 @@
"@nestjs/terminus": "^11.0.0",
"@nestjs/typeorm": "^11.0.0",
"@nestjs/websockets": "^11.1.9",
- "@paypal/payouts-sdk": "^1.1.1",
"@sentry/cli": "^2.58.2",
"@sentry/nestjs": "^10.27.0",
"@sentry/profiling-node": "^10.27.0",
@@ -3677,27 +3676,6 @@
"win32"
]
},
- "node_modules/@paypal/payouts-sdk": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/@paypal/payouts-sdk/-/payouts-sdk-1.1.1.tgz",
- "integrity": "sha512-m8hICfBjrf8WKXYGt84wVS7YLa+exB/HQwItn33ArmDDH1Hno0vqwwE2oY7TNTuKcBpxSE75D9KMrtNlVN9kZQ==",
- "license": "SEE LICENSE IN https://github.com/paypal/Payouts-NodeJS-SDK/blob/master/LICENSE",
- "dependencies": {
- "@paypal/paypalhttp": "^1.0.1"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/@paypal/paypalhttp": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/@paypal/paypalhttp/-/paypalhttp-1.0.1.tgz",
- "integrity": "sha512-DC7AHxTT7drF6dUi3YaFdPVuT15sIkpD5H2eHmdtFgxM4UanS1o1ZDfMhR9mpxd8o+X6pz2r+EZVRRq+n1cssQ==",
- "license": "MIT",
- "engines": {
- "node": ">=4"
- }
- },
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
diff --git a/backend/package.json b/backend/package.json
index 43455efdd..64075a301 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -45,7 +45,6 @@
"@nestjs/terminus": "^11.0.0",
"@nestjs/typeorm": "^11.0.0",
"@nestjs/websockets": "^11.1.9",
- "@paypal/payouts-sdk": "^1.1.1",
"@sentry/cli": "^2.58.2",
"@sentry/nestjs": "^10.27.0",
"@sentry/profiling-node": "^10.27.0",
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index b8089e96c..8eea060a8 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -110,7 +110,7 @@ export const login = (credentials: { email: string; password: string }) =>
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
-export const signup = (data: { email: string; password: string; refCode?: string; checkIfLeaked?: boolean }) =>
+export const signup = (data: { email: string; password: string; checkIfLeaked?: boolean }) =>
api
.post('v1/auth/register', data)
.then((response): Auth => response.data)
@@ -158,52 +158,6 @@ export const setShowLiveVisitorsInTitle = (show: boolean) =>
throw new Error(errorsArray)
})
-export const generateRefCode = () =>
- api
- .post('/user/generate-ref-code')
- .then((response): Partial<User> => response.data)
- .catch((error) => {
- const errorsArray = error.response.data.message
- if (_isArray(errorsArray)) {
- throw errorsArray
- }
- throw new Error(errorsArray)
- })
-
-export const getPayoutsInfo = () =>
- api
- .get('/user/payouts/info')
- .then(
- (
- response,
- ): {
- trials: number
- subscribers: number
- paid: number
- nextPayout: number
- pending: number
- } => response.data,
- )
- .catch((error) => {
- const errorsArray = error.response.data.message
- if (_isArray(errorsArray)) {
- throw errorsArray
- }
- throw new Error(errorsArray)
- })
-
-export const getReferrals = () =>
- api
- .get('/user/referrals')
- .then((response): Partial<User>[] => response.data)
- .catch((error) => {
- const errorsArray = error.response.data.message
- if (_isArray(errorsArray)) {
- throw errorsArray
- }
- throw new Error(errorsArray)
- })
-
export const forgotPassword = (email: { email: string }) =>
api
.post('v1/auth/reset-password', email)
@@ -1892,13 +1846,13 @@ export const generateSSOAuthURL = async (provider: SSOProvider, redirectUrl?: st
})
}
-export const getJWTBySSOHash = async (hash: string, provider: SSOProvider, refCode?: string) => {
+export const getJWTBySSOHash = async (hash: string, provider: SSOProvider) => {
let axiosPost
if (provider === 'openid-connect') {
axiosPost = api.post('v1/auth/oidc/hash', { hash })
} else {
- axiosPost = api.post('v1/auth/sso/hash', { hash, provider, refCode })
+ axiosPost = api.post('v1/auth/sso/hash', { hash, provider })
}
return axiosPost
@@ -2069,14 +2023,6 @@ export const receiveLoginNotification = (receiveLoginNotifications: boolean) =>
throw error
})
-export const setPaypalEmail = (paypalPaymentsEmail: string | null) =>
- api
- .patch('user/set-paypal-email', { paypalPaymentsEmail })
- .then((response) => response.data)
- .catch((error) => {
- throw error
- })
-
export const previewSubscriptionUpdate = (planId: number) =>
api
.post('user/preview-plan', { planId })
diff --git a/web/app/components/marketing/Lines.tsx b/web/app/components/marketing/Lines.tsx
deleted file mode 100644
index 0d489f46e..000000000
--- a/web/app/components/marketing/Lines.tsx
+++ /dev/null
@@ -1,6 +0,0 @@
-export const Lines = () => (
- <div className='pointer-events-none relative'>
- <div className='absolute top-[32rem] right-[-48rem] h-px w-[800%] rotate-6 bg-gradient-to-l from-slate-600 opacity-10 dark:from-slate-400' />
- <div className='absolute top-[22.26rem] -left-60 ml-[-0.5px] h-96 w-[2px] rotate-[96deg] rounded-full bg-gradient-to-t from-emerald-600 opacity-50 xl:top-[23.5rem] dark:from-emerald-700' />
- </div>
-)
diff --git a/web/app/components/pricing/BillingPricing.tsx b/web/app/components/pricing/BillingPricing.tsx
index 413f6e86d..ae6d2a7b8 100644
--- a/web/app/components/pricing/BillingPricing.tsx
+++ b/web/app/components/pricing/BillingPricing.tsx
@@ -15,7 +15,6 @@ import {
CURRENCIES,
CONTACT_EMAIL,
PLAN_LIMITS,
- REFERRAL_DISCOUNT_CODE,
STANDARD_PLANS,
PURCHASABLE_LEGACY_PLANS,
paddleLanguageMapping,
@@ -157,10 +156,6 @@ const BillingPricing = ({ lastEvent }: BillingPricingProps) => {
return
}
- const discountMayBeApplied =
- user.referrerID && (user.planCode === 'trial' || user.planCode === 'none') && !user.cancellationEffectiveDate
- const coupon = discountMayBeApplied ? REFERRAL_DISCOUNT_CODE : undefined
-
window.Paddle.Checkout.open({
product: billingFrequency === BillingFrequency.monthly ? tier.pid : tier.ypid,
email: user.email,
@@ -169,7 +164,6 @@ const BillingPricing = ({ lastEvent }: BillingPricingProps) => {
title: tier.name,
displayModeTheme: theme,
country: metainfo.country,
- coupon,
})
}
diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.ts
index 22356b270..8458fd5c3 100644
--- a/web/app/lib/constants/index.ts
+++ b/web/app/lib/constants/index.ts
@@ -279,7 +279,6 @@ export const TWITTER_USERNAME = '@swetrix'
export const DISCORD_URL = 'https://discord.gg/ZVK8Tw2E8j'
export const STATUSPAGE_URL = 'https://stats.uptimerobot.com/33rvmiXXEz'
export const MAIN_URL = 'https://swetrix.com'
-export const REF_URL_PREFIX = `${MAIN_URL}/ref/`
export const LIVE_DEMO_URL = '/projects/STEzHcB1rALV'
export const BOOK_A_CALL_URL = 'https://cal.com/swetrix'
export const PERFORMANCE_LIVE_DEMO_URL = '/projects/STEzHcB1rALV?tab=performance'
@@ -287,15 +286,6 @@ export const ERROR_TRACKING_LIVE_DEMO_URL = '/projects/STEzHcB1rALV?tab=errors'
export const DOCS_URL = 'https://docs.swetrix.com'
export const INTEGRATIONS_URL = 'https://docs.swetrix.com/integrations'
export const ERROR_TRACKING_DOCS_URL = 'https://docs.swetrix.com/error-tracking'
-export const DOCS_REFERRAL_PROGRAM_URL = `${DOCS_URL}/affiliate/about`
-
-// Referral program
-export const REFERRAL_COOKIE = 'affiliate'
-export const REFERRAL_COOKIE_DAYS = 30
-export const REFERRAL_DISCOUNT = 20
-export const REFERRAL_PENDING_PAYOUT_DAYS = 30
-export const REFERRAL_CUT = 0.2
-export const REFERRAL_DISCOUNT_CODE = 'REFERRAL_DISCOUNT'
export const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'
@@ -477,20 +467,6 @@ export const CURRENCIES: ICurrencies = {
GBP,
}
-export const MERCHANT_FEE = '5% + 50¢'
-
-// Paddle fee is 5% + 50¢
-const calculatePriceAfterFees = (price: number): number => {
- const fee = 0.05 * price + 0.5
- return price - fee
-}
-
-export const calculateReferralCut = (originalTierPrice: number): number => {
- const priceAfterFees = calculatePriceAfterFees(originalTierPrice)
- const referralCut = REFERRAL_CUT * priceAfterFees
- return referralCut
-}
-
export const BillingFrequency = {
monthly: 'monthly',
yearly: 'yearly',
diff --git a/web/app/lib/models/User.ts b/web/app/lib/models/User.ts
index 74e745999..18a64b2a9 100644
--- a/web/app/lib/models/User.ts
+++ b/web/app/lib/models/User.ts
@@ -66,9 +66,6 @@ export interface User {
tierCurrency: 'USD' | 'EUR' | 'GBP' | null
showLiveVisitorsInTitle: boolean
receiveLoginNotifications: boolean
- refCode: string | null
- referrerID: string | null
- paypalPaymentsEmail: string | null
planExceedContactedAt: Date
dashboardBlockReason: DashboardBlockReason
isAccountBillingSuspended: boolean
diff --git a/web/app/pages/Auth/Signin/Signin.tsx b/web/app/pages/Auth/Signin/Signin.tsx
index 335292fa4..4b974af3a 100644
--- a/web/app/pages/Auth/Signin/Signin.tsx
+++ b/web/app/pages/Auth/Signin/Signin.tsx
@@ -12,7 +12,7 @@ import GithubAuth from '~/components/GithubAuth'
import GoogleAuth from '~/components/GoogleAuth'
import OIDCAuth from '~/components/OIDCAuth'
import { withAuthentication, auth } from '~/hoc/protected'
-import { isSelfhosted, REFERRAL_COOKIE, TRIAL_DAYS } from '~/lib/constants'
+import { isSelfhosted, TRIAL_DAYS } from '~/lib/constants'
import { SSOProvider } from '~/lib/models/Auth'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
@@ -21,7 +21,6 @@ import Checkbox from '~/ui/Checkbox'
import Input from '~/ui/Input'
import { Text } from '~/ui/Text'
import { setAccessToken, removeAccessToken } from '~/utils/accessToken'
-import { deleteCookie, getCookie } from '~/utils/cookie'
import { cn, delay, openBrowserWindow } from '~/utils/generic'
import { setRefreshToken, removeRefreshToken } from '~/utils/refreshToken'
import routes from '~/utils/routes'
@@ -144,19 +143,13 @@ const Signin = () => {
// Closing the authorisation window after the session expires
setTimeout(authWindow.close, expiresIn)
- const refCode = getCookie(REFERRAL_COOKIE) as string
-
while (true) {
await delay(HASH_CHECK_FREQUENCY)
try {
- const { accessToken, refreshToken, user, totalMonthlyEvents } = await getJWTBySSOHash(uuid, provider, refCode)
+ const { accessToken, refreshToken, user, totalMonthlyEvents } = await getJWTBySSOHash(uuid, provider)
authWindow.close()
- if (refCode) {
- deleteCookie(REFERRAL_COOKIE)
- }
-
if (user.isTwoFactorAuthenticationEnabled) {
setAccessToken(accessToken, true)
setRefreshToken(refreshToken)
diff --git a/web/app/pages/Auth/Signup/Signup.tsx b/web/app/pages/Auth/Signup/Signup.tsx
index 888fb23f1..ccc05f653 100644
--- a/web/app/pages/Auth/Signup/Signup.tsx
+++ b/web/app/pages/Auth/Signup/Signup.tsx
@@ -11,7 +11,7 @@ import { generateSSOAuthURL, getJWTBySSOHash, signup } from '~/api'
import GithubAuth from '~/components/GithubAuth'
import GoogleAuth from '~/components/GoogleAuth'
import OIDCAuth from '~/components/OIDCAuth'
-import { HAVE_I_BEEN_PWNED_URL, isSelfhosted, REFERRAL_COOKIE, TRIAL_DAYS } from '~/lib/constants'
+import { HAVE_I_BEEN_PWNED_URL, isSelfhosted, TRIAL_DAYS } from '~/lib/constants'
import { SSOProvider } from '~/lib/models/Auth'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
@@ -21,7 +21,6 @@ import Input from '~/ui/Input'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
import { setAccessToken } from '~/utils/accessToken'
-import { deleteCookie, getCookie } from '~/utils/cookie'
import { cn, delay, openBrowserWindow } from '~/utils/generic'
import { setRefreshToken } from '~/utils/refreshToken'
import routes from '~/utils/routes'
@@ -120,19 +119,12 @@ const Signup = () => {
try {
const { dontRemember } = data
- const refCode = getCookie(REFERRAL_COOKIE)
-
const { user, accessToken, refreshToken } = await signup({
email: data.email,
password: data.password,
checkIfLeaked: data.checkIfLeaked,
- refCode: refCode || undefined,
})
- if (refCode) {
- deleteCookie(REFERRAL_COOKIE)
- }
-
setUser(user)
setIsAuthenticated(true)
setAccessToken(accessToken, dontRemember)
@@ -196,19 +188,13 @@ const Signup = () => {
// Closing the authorisation window after the session expires
setTimeout(authWindow.close, expiresIn)
- const refCode = getCookie(REFERRAL_COOKIE) as string
-
while (true) {
await delay(HASH_CHECK_FREQUENCY)
try {
- const { accessToken, refreshToken, user, totalMonthlyEvents } = await getJWTBySSOHash(uuid, provider, refCode)
+ const { accessToken, refreshToken, user, totalMonthlyEvents } = await getJWTBySSOHash(uuid, provider)
authWindow.close()
- if (refCode) {
- deleteCookie(REFERRAL_COOKIE)
- }
-
if (user.isTwoFactorAuthenticationEnabled) {
setAccessToken(accessToken, true)
setRefreshToken(refreshToken)
diff --git a/web/app/pages/ReferralPage/index.tsx b/web/app/pages/ReferralPage/index.tsx
deleted file mode 100644
index af473fe82..000000000
--- a/web/app/pages/ReferralPage/index.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-import { ArrowRightIcon } from '@heroicons/react/20/solid'
-import { useTranslation, Trans } from 'react-i18next'
-import { Link, useParams } from 'react-router'
-
-import Header from '~/components/Header'
-import { Lines } from '~/components/marketing/Lines'
-import { REFERRAL_COOKIE_DAYS, REFERRAL_DISCOUNT } from '~/lib/constants'
-import { useTheme } from '~/providers/ThemeProvider'
-import routes from '~/utils/routes'
-
-const ReferralPage = () => {
- const { t } = useTranslation('common')
- const { theme } = useTheme()
-
- // Referral code
- const { id } = useParams()
-
- return (
- <div className='overflow-hidden'>
- <main className='min-h-[100vh] bg-white dark:bg-slate-900'>
- <div className='relative isolate overflow-x-clip'>
- <svg
- className='absolute inset-0 -z-10 h-full w-full [mask-image:radial-gradient(100%_100%_at_top_right,white,transparent)] stroke-gray-200 dark:stroke-white/10'
- aria-hidden='true'
- >
- <defs>
- <pattern id='rect-pattern' width={200} height={200} x='50%' y={-1} patternUnits='userSpaceOnUse'>
- <path d='M.5 200V.5H200' fill='none' />
- </pattern>
- </defs>
- <svg x='50%' y={-1} className='overflow-visible fill-white dark:fill-gray-800/20'>
- <path
- d='M-200 0h201v201h-201Z M600 0h201v201h-201Z M-400 600h201v201h-201Z M200 800h201v201h-201Z'
- strokeWidth={0}
- />
- </svg>
- <rect width='100%' height='100%' strokeWidth={0} fill='url(#rect-pattern)' />
- </svg>
- <div
- className='absolute top-10 left-[calc(50%-4rem)] -z-10 transform-gpu blur-3xl sm:left-[calc(50%-18rem)] lg:top-[calc(50%-30rem)] lg:left-48 xl:left-[calc(50%-24rem)]'
- aria-hidden='true'
- >
- <div
- className='aspect-[1108/632] w-[69.25rem] bg-gradient-to-r from-[#80caff] to-[#4f46e5] opacity-20'
- style={{
- clipPath:
- 'polygon(73.6% 51.7%, 91.7% 11.8%, 100% 46.4%, 97.4% 82.2%, 92.5% 84.9%, 75.7% 64%, 55.3% 47.5%, 46.5% 49.4%, 45% 62.9%, 50.3% 87.2%, 21.3% 64.1%, 0.1% 100%, 5.4% 51.1%, 21.4% 63.9%, 58.9% 0.2%, 73.6% 51.7%)',
- }}
- />
- </div>
- <Header refPage transparent />
- <div className='relative mx-auto min-h-[740px] pt-10 pb-5 sm:px-3 lg:px-6 lg:pt-24 xl:px-8'>
- <div className='relative z-20 flex flex-row content-between justify-center lg:justify-start 2xl:mr-[14vw] 2xl:justify-center'>
- <div className='relative px-4 text-left lg:mt-0 lg:mr-14'>
- <h1 className='max-w-2xl text-2xl font-extrabold text-slate-900 sm:text-4xl sm:leading-none md:text-5xl xl:leading-[110%] dark:text-white'>
- <Trans
- t={t}
- i18nKey='main.slogan'
- components={{
- span: (
- <span className='bg-gradient-to-r from-indigo-700 to-indigo-700 bg-clip-text text-transparent dark:from-indigo-600 dark:to-indigo-400' />
- ),
- }}
- />
- </h1>
- <p className='mt-5 text-base text-slate-700 sm:text-xl lg:text-lg xl:text-lg dark:text-slate-300'>
- {t('referral.desc')}
- </p>
- <h2 className='mt-10 text-xl font-medium text-slate-900 sm:text-xl sm:leading-none md:text-xl xl:leading-[110%] dark:text-white'>
- {t('referral.buttons', {
- discount: REFERRAL_DISCOUNT,
- })}
- </h2>
- <div className='mt-4 flex flex-col items-center sm:flex-row'>
- <Link
- to={`/ref/${id}${routes.signup}`}
- className='flex h-12 items-center justify-center rounded-md border-2 border-slate-900 bg-slate-900 px-4 text-white transition-all hover:bg-transparent hover:text-slate-900 sm:mr-6 dark:border-slate-50 dark:bg-gray-50 dark:text-slate-900 dark:hover:text-gray-50'
- aria-label={t('titles.signup')}
- >
- <span className='mr-1 text-center text-base font-semibold'>
- {t('main.startAXDayFreeTrial', { amount: 14 })}
- </span>
- <ArrowRightIcon className='mt-[1px] h-4 w-5' />
- </Link>
- <Link
- to={`/ref/${id}/index#core-analytics`}
- className='mt-2 flex h-12 w-full items-center justify-center rounded-md bg-transparent text-slate-900 ring-1 ring-slate-900 transition-all hover:bg-slate-200/60 sm:mt-0 sm:max-w-[210px] dark:text-white dark:ring-white/20 dark:hover:bg-slate-800/60'
- aria-label={t('titles.signup')}
- >
- <span className='text-base font-semibold'>{t('common.learnMore')}</span>
- </Link>
- </div>
- <p className='mt-5 text-base font-medium text-slate-500 dark:text-slate-500'>
- {t('referral.cookieDetails', {
- days: REFERRAL_COOKIE_DAYS,
- discount: REFERRAL_DISCOUNT,
- })}
- </p>
- </div>
- <div className='hidden max-w-md lg:block xl:max-w-lg'>
- <Lines />
- <img
- src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}
- className='relative h-full min-w-[880px] rounded-xl ring-2 ring-gray-900/10 dark:ring-white/10'
- width='100%'
- height='auto'
- alt='Swetrix Analytics dashboard'
- />
- </div>
- </div>
- <div className='relative z-20 my-10 block px-4 md:px-0 lg:hidden'>
- <img
- src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}
- className='relative w-full rounded-xl ring-2 ring-gray-900/10 dark:ring-white/10'
- width='100%'
- height='auto'
- alt='Swetrix Analytics dashboard'
- />
- </div>
- </div>
- </div>
- </main>
- </div>
- )
-}
-
-export default ReferralPage
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index c8994967e..e21ef93b7 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -9,7 +9,7 @@ import _isEmpty from 'lodash/isEmpty'
import _keys from 'lodash/keys'
import _map from 'lodash/map'
import _size from 'lodash/size'
-import { MessageSquareTextIcon, MonitorIcon, UserRoundIcon, MousePointerClickIcon } from 'lucide-react'
+import { MessageSquareTextIcon, MonitorIcon, UserRoundIcon } from 'lucide-react'
import React, { useState, useEffect, memo, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router'
@@ -48,7 +48,6 @@ import NoOrganisations from './components/NoOrganisations'
import NoSharedProjects from './components/NoSharedProjects'
import Organisations from './components/Organisations'
import ProjectList from './components/ProjectList'
-import Referral from './components/Referral'
import Socialisations from './components/Socialisations'
import TwoFA from './components/TwoFA'
@@ -58,7 +57,6 @@ const timeFormatArray = _map(TimeFormat, (key) => key)
const TAB_MAPPING = {
ACCOUNT: 'account',
- REFERRALS: 'referrals',
INTERFACE: 'interface',
COMMUNICATIONS: 'communications',
}
@@ -95,11 +93,6 @@ const getTabs = (t: typeof i18next.t) => {
label: 'Interface settings',
icon: MonitorIcon,
},
- {
- id: TAB_MAPPING.REFERRALS,
- label: t('profileSettings.referral.title'),
- icon: MousePointerClickIcon,
- },
]
}
@@ -809,20 +802,6 @@ const UserSettings = () => {
)
}
- if (activeTab === TAB_MAPPING.REFERRALS) {
- return (
- <>
- <h3
- id='socialisations'
- className='flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'
- >
- {t('profileSettings.referral.title')}
- </h3>
- <Referral />
- </>
- )
- }
-
return null
}}
</ClientOnly>
diff --git a/web/app/pages/UserSettings/components/Referral.tsx b/web/app/pages/UserSettings/components/Referral.tsx
deleted file mode 100644
index 1f5374ecd..000000000
--- a/web/app/pages/UserSettings/components/Referral.tsx
+++ /dev/null
@@ -1,312 +0,0 @@
-import dayjs from 'dayjs'
-import _isEmpty from 'lodash/isEmpty'
-import _map from 'lodash/map'
-import React, { useState, useEffect } from 'react'
-import { useTranslation, Trans } from 'react-i18next'
-import { toast } from 'sonner'
-
-import { generateRefCode, getPayoutsInfo, getReferrals, setPaypalEmail } from '~/api'
-import {
- REF_URL_PREFIX,
- DOCS_REFERRAL_PROGRAM_URL,
- REFERRAL_PENDING_PAYOUT_DAYS,
- calculateReferralCut,
- PLAN_LIMITS,
- CURRENCIES,
- BillingFrequency,
- MERCHANT_FEE,
- REFERRAL_CUT,
-} from '~/lib/constants'
-import { User } from '~/lib/models/User'
-import { useAuth } from '~/providers/AuthProvider'
-import Button from '~/ui/Button'
-import Highlighted from '~/ui/Highlighted'
-import Spin from '~/ui/icons/Spin'
-import Input from '~/ui/Input'
-import Tooltip from '~/ui/Tooltip'
-import { isValidEmail } from '~/utils/validator'
-
-const Referral = () => {
- const { user, mergeUser } = useAuth()
-
- const {
- t,
- i18n: { language },
- } = useTranslation('common')
- const [refCodeGenerating, setRefCodeGenerating] = useState(false)
- const [paypalInputError, setPaypalInputError] = useState<string | null>(null)
- const [isPaypalEmailLoading, setIsPaypalEmailLoading] = useState(false)
- const [paypalEmailAddress, setPaypalEmailAddress] = useState<string | null>(user?.paypalPaymentsEmail || null)
-
- const [referralStatistics, setReferralStatistics] = useState<{
- trials: number
- subscribers: number
- paid: number
- nextPayout: number
- pending: number
- } | null>(null)
- const [activeReferrals, setActiveReferrals] = useState<Partial<User>[]>([])
-
- const [isLoading, setIsLoading] = useState<boolean | null>(null)
-
- const uiIsLoading = isLoading || isLoading === null
-
- const refUrl = `${REF_URL_PREFIX}${user?.refCode}`
-
- const loadStatistics = async () => {
- if (isLoading) {
- return
- }
- setIsLoading(true)
-
- try {
- const [payoutsInfo, referrals] = await Promise.all([getPayoutsInfo(), getReferrals()])
- setReferralStatistics(payoutsInfo)
- setActiveReferrals(referrals)
- } catch (reason: any) {
- console.error('[loadStatistics] Something went wrong whilst requesting referrals info', reason)
- } finally {
- setIsLoading(false)
- }
- }
-
- useEffect(() => {
- loadStatistics()
-
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [])
-
- const onRefCodeGenerate = async () => {
- if (refCodeGenerating || user?.refCode) {
- return
- }
-
- setRefCodeGenerating(true)
-
- try {
- const { refCode } = await generateRefCode()
- mergeUser({
- refCode,
- })
- } catch {
- toast.error(t('apiNotifications.somethingWentWrong'))
- } finally {
- setRefCodeGenerating(false)
- }
- }
-
- const handlePaypalInput = (e: React.ChangeEvent<HTMLInputElement>) => {
- setPaypalInputError(null)
- setPaypalEmailAddress(e.target.value)
- }
-
- const updatePaypalEmail = async () => {
- if (paypalEmailAddress) {
- const isValid = isValidEmail(paypalEmailAddress)
-
- if (!isValid) {
- setPaypalInputError(t('auth.common.badEmailError'))
- return
- }
- }
-
- setIsPaypalEmailLoading(true)
-
- try {
- await setPaypalEmail(paypalEmailAddress)
- mergeUser({
- paypalPaymentsEmail: paypalEmailAddress,
- })
- toast.success(t('profileSettings.referral.payoutEmailUpdated'))
- } catch (reason) {
- console.error('[Referral][updatePaypalEmail] Something went wrong whilst updating paypal email', reason)
- toast.error(t('apiNotifications.somethingWentWrong'))
- }
-
- setIsPaypalEmailLoading(false)
- }
-
- return (
- <>
- <p className='text-base text-gray-900 dark:text-gray-50'>
- <Trans
- t={t}
- i18nKey='profileSettings.referral.desc'
- components={{
- url: (
- <a
- href={DOCS_REFERRAL_PROGRAM_URL}
- className='font-medium text-indigo-600 hover:text-indigo-500 hover:underline dark:text-indigo-400 dark:hover:text-indigo-500'
- target='_blank'
- rel='noreferrer noopener'
- />
- ),
- }}
- />
- </p>
- <h3 className='mt-5 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
- {t('profileSettings.referral.payoutEmail')}
- </h3>
- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
- {t('profileSettings.referral.payoutEmailDesc')}
- </p>
- <div className='mt-2 flex space-x-2'>
- <Input
- type='email'
- value={paypalEmailAddress || ''}
- placeholder='[email protected]'
- onChange={handlePaypalInput}
- error={paypalInputError}
- />
- <Button type='button' className='h-9' loading={isPaypalEmailLoading} onClick={updatePaypalEmail} primary large>
- {t('common.save')}
- </Button>
- </div>
- <h3 className='mt-5 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
- {t('profileSettings.referral.referralLink')}
- </h3>
- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
- {t('profileSettings.referral.referralLinkDesc')}
- </p>
- {user?.refCode ? (
- <div className='grid grid-cols-1 gap-x-4 gap-y-6 lg:grid-cols-2'>
- <Input
- label={t('profileSettings.referral.yourReferralLink')}
- name='refCode'
- className='mt-4'
- value={refUrl}
- disabled
- />
- </div>
- ) : (
- <Button className='mt-2' onClick={onRefCodeGenerate} loading={refCodeGenerating} primary large>
- {t('profileSettings.referral.generateRefLink')}
- </Button>
- )}
- <h3 className='mt-5 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
- {t('profileSettings.referral.referralStats')}
- </h3>
- {referralStatistics ? (
- <div>
- <Tooltip
- text={t('profileSettings.referral.trialDesc')}
- tooltipNode={
- <span className='text-gray-900 dark:text-gray-50'>
- {t('profileSettings.referral.trial')}: <Highlighted>{referralStatistics.trials}</Highlighted>
- </span>
- }
- className='block'
- />
- <Tooltip
- text={t('profileSettings.referral.activeDesc')}
- tooltipNode={
- <span className='text-gray-900 dark:text-gray-50'>
- {t('profileSettings.referral.active')}: <Highlighted>{referralStatistics.subscribers}</Highlighted>
- </span>
- }
- className='block'
- />
- <Tooltip
- text={t('profileSettings.referral.paidDesc')}
- tooltipNode={
- <span className='text-gray-900 dark:text-gray-50'>
- {t('profileSettings.referral.paid')}: <Highlighted>US$ {referralStatistics.paid}</Highlighted>
- </span>
- }
- className='block'
- />
- <Tooltip
- text={t('profileSettings.referral.nextPayoutDesc')}
- tooltipNode={
- <span className='text-gray-900 dark:text-gray-50'>
- {t('profileSettings.referral.nextPayout')}:{' '}
- <Highlighted>US$ {referralStatistics.nextPayout}</Highlighted>
- </span>
- }
- className='block'
- />
- <Tooltip
- text={t('profileSettings.referral.pendingDesc', {
- days: REFERRAL_PENDING_PAYOUT_DAYS,
- })}
- tooltipNode={
- <span className='text-gray-900 dark:text-gray-50'>
- {t('profileSettings.referral.pending')}: <Highlighted>US$ {referralStatistics.pending}</Highlighted>
- </span>
- }
- className='block'
- />
- </div>
- ) : (
- <Spin className='mt-2 !ml-0' />
- )}
- <h3 className='mt-5 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
- {t('profileSettings.referral.activeReferrals')}
- </h3>
- {!_isEmpty(activeReferrals) ? (
- <table className='200 mt-2 min-w-full divide-y divide-gray-300 ring-1 ring-black/10 md:rounded-lg dark:divide-gray-500'>
- <thead className='bg-gray-50 dark:bg-slate-800'>
- <tr>
- <th
- scope='col'
- className='py-3.5 pr-3 pl-4 text-left text-sm font-semibold text-gray-900 dark:text-gray-50'
- >
- {t('profileSettings.referral.activeReferralsTable.plan')}
- </th>
- <th scope='col' className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-gray-50'>
- <Tooltip
- text={t('profileSettings.referral.activeReferralsTable.yourCutDesc', {
- fee: MERCHANT_FEE,
- amount: REFERRAL_CUT * 100,
- })}
- tooltipNode={<>{t('profileSettings.referral.activeReferralsTable.yourCut')}</>}
- className='block'
- />
- </th>
- <th scope='col' className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-gray-50'>
- {t('profileSettings.referral.activeReferralsTable.registrationDate')}
- </th>
- </tr>
- </thead>
- <tbody className='divide-y divide-gray-200 bg-white dark:divide-gray-600 dark:bg-slate-800'>
- {_map(activeReferrals, ({ billingFrequency, created, planCode, tierCurrency }, index) => {
- // @ts-expect-error
- const planPrice = PLAN_LIMITS[planCode].price[tierCurrency][billingFrequency]
- const referrerCut = calculateReferralCut(planPrice)
- const currencySymbol = CURRENCIES[tierCurrency as 'EUR' | 'USD' | 'GBP'].symbol
- const tBillingFrequency = t(
- billingFrequency === BillingFrequency.monthly ? 'pricing.perMonth' : 'pricing.perYear',
- )
-
- return (
- <tr key={index}>
- <td className='px-3 py-4 text-sm whitespace-nowrap text-gray-900 sm:pl-6 dark:text-gray-50'>
- {currencySymbol}
- {planPrice}/{tBillingFrequency}
- </td>
- <td className='px-3 py-4 text-sm whitespace-nowrap text-gray-900 dark:text-gray-50'>
- {currencySymbol}
- {referrerCut}/{tBillingFrequency}
- </td>
- <td className='px-3 py-4 text-sm whitespace-nowrap text-gray-900 dark:text-gray-50'>
- {language === 'en'
- ? dayjs(created).locale(language).format('MMMM D, YYYY')
- : dayjs(created).locale(language).format('D MMMM, YYYY')}
- </td>
- </tr>
- )
- })}
- </tbody>
- </table>
- ) : uiIsLoading ? (
- <Spin className='mt-2 !ml-0' />
- ) : (
- <p className='mt-2 text-sm text-gray-900 dark:text-gray-50'>
- {t('profileSettings.referral.noActiveReferrals')}
- </p>
- )}
- </>
- )
-}
-
-export default Referral
diff --git a/web/app/routes/ref.$id.$page.tsx b/web/app/routes/ref.$id.$page.tsx
index c3524649f..e16b88123 100644
--- a/web/app/routes/ref.$id.$page.tsx
+++ b/web/app/routes/ref.$id.$page.tsx
@@ -1,25 +1,20 @@
import type { LoaderFunctionArgs } from 'react-router'
import { redirect } from 'react-router'
-import { isSelfhosted, REFERRAL_COOKIE, REFERRAL_COOKIE_DAYS } from '~/lib/constants'
-import { generateCookieString } from '~/utils/cookie'
+import { isSelfhosted } from '~/lib/constants'
-// This route sets the affiliate cookie ($id) and redirects to page specified at $page
export async function loader({ params }: LoaderFunctionArgs) {
if (isSelfhosted) {
return redirect('/login', 302)
}
- const { id, page } = params
+ const { page } = params
const init = {
status: 302,
- headers: {
- 'Set-Cookie': generateCookieString(REFERRAL_COOKIE, id as string, REFERRAL_COOKIE_DAYS * 24 * 60 * 60),
- },
}
- const redirectPath = page === 'index' ? '/#core-analytics' : `/${page}`
+ const redirectPath = page === 'index' ? '/' : `/${page}`
return redirect(redirectPath, init)
}
diff --git a/web/app/routes/ref.$id.tsx b/web/app/routes/ref.$id.tsx
index 572f2bf75..e7a8daa82 100644
--- a/web/app/routes/ref.$id.tsx
+++ b/web/app/routes/ref.$id.tsx
@@ -1,16 +1,15 @@
import { redirect } from 'react-router'
import { isSelfhosted } from '~/lib/constants'
-import ReferralPage from '~/pages/ReferralPage'
export async function loader() {
if (isSelfhosted) {
return redirect('/login', 302)
}
- return null
+ return redirect('/', 302)
}
export default function ReferralPageRoute() {
- return <ReferralPage />
+ return null
}
diff --git a/web/app/ui/Highlighted.tsx b/web/app/ui/Highlighted.tsx
deleted file mode 100644
index ec91c3d98..000000000
--- a/web/app/ui/Highlighted.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import React from 'react'
-
-interface HighlightedProps {
- children: React.ReactNode
-}
-
-const Highlighted = ({ children }: HighlightedProps) => (
- <span className='rounded-sm bg-slate-200 px-1 text-gray-900 dark:bg-slate-700 dark:text-gray-50'>{children}</span>
-)
-
-export default Highlighted
diff --git a/web/app/utils/cookie.ts b/web/app/utils/cookie.ts
index a88de3414..6856f2f36 100644
--- a/web/app/utils/cookie.ts
+++ b/web/app/utils/cookie.ts
@@ -16,12 +16,7 @@ export const getCookie = (key: string) => {
return null
}
-export const generateCookieString = (
- key: string,
- value: string | number | boolean,
- maxAge = 3600,
- sameSite = 'strict',
-) => {
+const generateCookieString = (key: string, value: string | number | boolean, maxAge = 3600, sameSite = 'strict') => {
return `${key}=${value}; max-age=${maxAge}; path=/; SameSite=${sameSite}${COOKIE_SUFFIX}`
}
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 4317e47cc..9e16e04db 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -552,11 +552,6 @@
"easyToUse": "Easy to use",
"privacyFirst": "Privacy-first"
},
- "referral": {
- "desc": "Swetrix is an ethical, open source and completely cookie-less alternative to Google Analytics. It allows you to understand your users' behaviour, monitor your website performance, track your marketing campaigns and much more. All without invading your users' privacy!",
- "cookieDetails": "If you click on the buttons above, a cookie will be stored for {{days}} days to reward the person who referred you and give you {{discount}}% off your first bill.",
- "buttons": "Click on these buttons to receive {{discount}}% off your first bill!"
- },
"unsubscribe": {
"success": "You've unsubscribed from analytics email reports"
},
@@ -754,36 +749,6 @@
"passwordChangeWarningModal": {
"title": "You're about to change your password",
"body": "You're about to change your password, this will log you out from all devices (including this one) and you will need to log in again with your new password."
- },
- "referral": {
- "title": "Referral program",
- "desc": "Referral program allows you to earn money by inviting new users to Swetrix.\nYou will receive a part of the subscription fee paid by the invited user and will be able to withdraw it to your PayPal account. Learn more about the referral program at <url>Swetrix Referral Program</url> documentation page.",
- "referralLink": "Referral link",
- "payoutEmail": "Referral payout email address",
- "payoutEmailDesc": "We will send your referral payouts via PayPal to this email address each month. Double check that it is correct.",
- "payoutEmailUpdated": "Payout email address has been updated",
- "yourReferralLink": "Your referral link",
- "referralLinkDesc": "This is your referral link, you can share it with your friends and earn money for each user that signs up and buys a paid plan using it.",
- "generateRefLink": "Generate referral link",
- "referralStats": "Referral statistics",
- "activeReferrals": "Active referrals",
- "noActiveReferrals": "You have no active referrals yet",
- "trial": "Trial referrals",
- "trialDesc": "Trial users referred by you",
- "active": "Active referrals",
- "activeDesc": "Paid subscribers referred by you",
- "paid": "Paid",
- "paidDesc": "Total amount paid to you",
- "nextPayout": "Next payout",
- "nextPayoutDesc": "How much you will get paid next time",
- "pending": "Pending",
- "pendingDesc": "Amount of money pending to be paid to you. It takes {{days}} days for the funds to become available.",
- "activeReferralsTable": {
- "plan": "Referral tier",
- "yourCut": "Your cut",
- "yourCutDesc": "You will receive {{amount}}% of the subscription fee paid by the user after all fees. Currently our merchant provider charges us {{fee}} per transaction.",
- "registrationDate": "Registration date"
- }
}
},
"alertsSettings": {