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!

(improvement) Pro-rata subscription upgrades (#166)

Andrii Romasiund3983845ce63
diff --git a/.env.example b/.env.example
index 9453892ea..be94e84c8 100644
--- a/.env.example
+++ b/.env.example
@@ -72,3 +72,7 @@ TELEGRAM_WEBHOOK_DOMAIN='' # domain name, for example api.swetrix.com
TELEGRAM_WEBHOOK_PATH='/v1/telegram/webhook'
TELEGRAM_WEBHOOK_IP_ADDRESS='' # server ip address
TELEGRAM_WEBHOOK_SECRET_TOKEN='' # random string; Only characters A-Z, a-z, 0-9, _ and - are allowed, length of 1-256 characters.
+
+# Paddle
+PADDLE_VENDOR_ID=
+PADDLE_API_KEY=
diff --git a/apps/production/src/user/dto/change-plan.dto.ts b/apps/production/src/user/dto/change-plan.dto.ts
new file mode 100644
index 000000000..26897663f
--- /dev/null
+++ b/apps/production/src/user/dto/change-plan.dto.ts
@@ -0,0 +1,8 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsNumber } from 'class-validator'
+
+export class IChangePlanDTO {
+ @ApiProperty({ example: 12345, required: true })
+ @IsNumber()
+ planId: number
+}
diff --git a/apps/production/src/user/user.controller.ts b/apps/production/src/user/user.controller.ts
index 4411c5db3..96f9474c1 100644
--- a/apps/production/src/user/user.controller.ts
+++ b/apps/production/src/user/user.controller.ts
@@ -53,6 +53,7 @@ import {
} from '../common/constants'
import { RolesGuard } from '../auth/guards/roles.guard'
import { UpdateUserProfileDTO } from './dto/update-user.dto'
+import { IChangePlanDTO } from './dto/change-plan.dto'
import { AdminUpdateUserProfileDTO } from './dto/admin-update-user.dto'
import { SetShowLiveVisitorsDTO } from './dto/set-show-live-visitors.dto'
import { ActionTokensService } from '../action-tokens/action-tokens.service'
@@ -673,4 +674,31 @@ export class UserController {
return info
}
+
+ @Post('change-plan')
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ async changePlan(
+ @CurrentUserId() id: string,
+ @Body() body: IChangePlanDTO,
+ ): Promise<void> {
+ this.logger.log({ body, id }, 'POST /change-plan')
+ const { planId } = body
+
+ await this.userService.updateSubscription(id, planId)
+ await this.projectService.clearProjectsRedisCache(id)
+ }
+
+ @Post('preview-plan')
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ async previewPlan(
+ @CurrentUserId() id: string,
+ @Body() body: IChangePlanDTO,
+ ): Promise<any> {
+ this.logger.log({ body, id }, 'POST /preview-plan')
+ const { planId } = body
+
+ return this.userService.previewSubscription(id, planId)
+ }
}
diff --git a/apps/production/src/user/user.module.ts b/apps/production/src/user/user.module.ts
index b51dc7f33..8a91cac34 100644
--- a/apps/production/src/user/user.module.ts
+++ b/apps/production/src/user/user.module.ts
@@ -1,7 +1,7 @@
import { Module, forwardRef } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
-import { TelegramService } from 'src/integrations/telegram/telegram.service'
+import { TelegramService } from '../integrations/telegram/telegram.service'
import { UserController } from './user.controller'
import { UserService } from './user.service'
import { User } from './entities/user.entity'
diff --git a/apps/production/src/user/user.service.ts b/apps/production/src/user/user.service.ts
index 189ca9db4..d47ce6afe 100644
--- a/apps/production/src/user/user.service.ts
+++ b/apps/production/src/user/user.service.ts
@@ -1,6 +1,11 @@
-import { Injectable, BadRequestException } from '@nestjs/common'
+import {
+ Injectable,
+ BadRequestException,
+ InternalServerErrorException,
+} from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
+import axios from 'axios'
import * as dayjs from 'dayjs'
import * as _isEmpty from 'lodash/isEmpty'
import * as _size from 'lodash/size'
@@ -8,7 +13,12 @@ import * as _omit from 'lodash/omit'
import * as _isNull from 'lodash/isNull'
import { Pagination, PaginationOptionsInterface } from '../common/pagination'
-import { User, ACCOUNT_PLANS, TRIAL_DURATION } from './entities/user.entity'
+import {
+ User,
+ ACCOUNT_PLANS,
+ TRIAL_DURATION,
+ BillingFrequency,
+} from './entities/user.entity'
import { UserProfileDTO } from './dto/user.dto'
import { RefreshToken } from './entities/refresh-token.entity'
import { UserGoogleDTO } from './dto/user-google.dto'
@@ -29,6 +39,19 @@ const GBP = {
code: 'GBP',
}
+const getSymbolByCode = (code: string) => {
+ switch (code) {
+ case EUR.code:
+ return EUR.symbol
+ case USD.code:
+ return USD.symbol
+ case GBP.code:
+ return GBP.symbol
+ default:
+ return null
+ }
+}
+
const CURRENCY_BY_COUNTRY = {
AT: EUR, // Austria
BE: EUR, // Belgium
@@ -55,6 +78,8 @@ const CURRENCY_BY_COUNTRY = {
US: USD, // United States
}
+const { PADDLE_VENDOR_ID, PADDLE_API_KEY } = process.env
+
@Injectable()
export class UserService {
constructor(
@@ -287,4 +312,164 @@ export class UserService {
getCurrencyByCountry(country: string) {
return CURRENCY_BY_COUNTRY[country] || USD
}
+
+ getPlanById(planId: number) {
+ if (!planId) {
+ return null
+ }
+
+ const stringifiedPlanId = String(planId)
+
+ const plan = Object.values(ACCOUNT_PLANS).find(
+ tier =>
+ // @ts-ignore
+ tier.pid === stringifiedPlanId ||
+ // @ts-ignore
+ tier.ypid === stringifiedPlanId,
+ )
+
+ // @ts-ignore
+ if (plan && plan.pid) {
+ const planCode = plan.id
+ const billingFrequency =
+ // @ts-ignore
+ plan?.pid === planId
+ ? BillingFrequency.Monthly
+ : BillingFrequency.Yearly
+
+ return {
+ planCode,
+ billingFrequency,
+ }
+ }
+
+ return null
+ }
+
+ async previewSubscription(id: string, planID: number) {
+ const user = await this.findOneWhere({ id })
+ const plan = this.getPlanById(planID)
+
+ if (!plan) {
+ throw new BadRequestException('Plan not found')
+ }
+
+ const { planCode, billingFrequency } = plan
+
+ if (
+ user.planCode === planCode &&
+ user.billingFrequency === billingFrequency
+ ) {
+ throw new BadRequestException('You are already subscribed to this plan')
+ }
+
+ const url = 'https://vendors.paddle.com/api/2.0/subscription/preview_update'
+
+ let preview: any = {}
+
+ try {
+ preview = await axios.post(url, {
+ vendor_id: Number(PADDLE_VENDOR_ID),
+ vendor_auth_code: PADDLE_API_KEY,
+ subscription_id: Number(user.subID),
+ plan_id: planID,
+ prorate: true,
+ bill_immediately: true,
+ currency: user.tierCurrency,
+ keep_modifiers: false,
+ })
+ } catch (error) {
+ console.error(
+ '[ERROR] (previewSubscription):',
+ error?.response?.data?.error?.message || error,
+ )
+ throw new BadRequestException('Something went wrong')
+ }
+
+ const { data } = preview
+
+ if (!data.success) {
+ console.error('[ERROR] (previewSubscription) success -> false:', preview)
+ throw new InternalServerErrorException('Something went wrong')
+ }
+
+ const symbol = getSymbolByCode(data.response.next_payment.currency)
+
+ return {
+ immediatePayment: {
+ ...data.response.immediate_payment,
+ symbol,
+ },
+ nextPayment: {
+ ...data.response.next_payment,
+ symbol,
+ },
+ }
+ }
+
+ async updateSubscription(id: string, planID: number) {
+ const user = await this.findOneWhere({ id })
+ const plan = this.getPlanById(planID)
+
+ if (!plan) {
+ throw new BadRequestException('Plan not found')
+ }
+
+ const { planCode, billingFrequency } = plan
+
+ if (
+ user.planCode === planCode &&
+ user.billingFrequency === billingFrequency
+ ) {
+ throw new BadRequestException('You are already subscribed to this plan')
+ }
+
+ const url = 'https://vendors.paddle.com/api/2.0/subscription/users/update'
+
+ let result: any = {}
+
+ try {
+ result = await axios.post(url, {
+ vendor_id: Number(PADDLE_VENDOR_ID),
+ vendor_auth_code: PADDLE_API_KEY,
+ subscription_id: Number(user.subID),
+ plan_id: planID,
+ prorate: true,
+ bill_immediately: true,
+ currency: user.tierCurrency,
+ keep_modifiers: false,
+ passthrough: JSON.stringify({
+ uid: id,
+ }),
+ })
+ } catch (error) {
+ console.error(
+ '[ERROR] (updateSubscription):',
+ error?.response?.data?.error?.message || error,
+ )
+ throw new BadRequestException('Something went wrong')
+ }
+
+ const { data, response } = result
+
+ if (!data.success) {
+ console.error('[ERROR] (updateSubscription) success -> false:', result)
+ throw new InternalServerErrorException('Something went wrong')
+ }
+
+ const {
+ subscription_id: subID,
+ next_payment: { currency, date },
+ } = response
+
+ const updateParams = {
+ planCode,
+ subID,
+ nextBillDate: date,
+ billingFrequency,
+ tierCurrency: currency,
+ }
+
+ await this.update(id, updateParams)
+ }
}