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) Plan limitation rework (#212)

Andrii Romasiun6beeb99e127c
diff --git a/apps/production/src/alert/alert.controller.ts b/apps/production/src/alert/alert.controller.ts
index 718b27aaa..1f4672034 100644
--- a/apps/production/src/alert/alert.controller.ts
+++ b/apps/production/src/alert/alert.controller.ts
@@ -128,6 +128,13 @@ export class AlertController {
)
}
+ if (user.isAccountBillingSuspended) {
+ throw new HttpException(
+ 'The account that owns this site is currently suspended, this is because of a billing issue. Please resolve the issue to continue.',
+ HttpStatus.PAYMENT_REQUIRED,
+ )
+ }
+
if (alertsCount >= (maxAlerts || ALERTS_MAXIMUM)) {
throw new HttpException(
`You cannot create more than ${maxAlerts} alerts on your account plan. Please upgrade to be able to create more alerts.`,
@@ -206,7 +213,7 @@ export class AlertController {
pid: alert.project.id,
}
}
-
+
@ApiBearerAuth()
@Delete('/:id')
@UseGuards(JwtAccessTokenGuard, RolesGuard)
diff --git a/apps/production/src/analytics/analytics.controller.ts b/apps/production/src/analytics/analytics.controller.ts
index b81f22d19..e0d14d054 100644
--- a/apps/production/src/analytics/analytics.controller.ts
+++ b/apps/production/src/analytics/analytics.controller.ts
@@ -323,6 +323,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ await this.analyticsService.checkBillingAccess(pid)
+
let newTimebucket = timeBucket
let allowedTumebucketForPeriodAll
@@ -458,6 +460,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ await this.analyticsService.checkBillingAccess(pid)
+
const pagesArr = await this.analyticsService.getPagesArray(
pages,
funnelId,
@@ -523,6 +527,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ await this.analyticsService.checkBillingAccess(pid)
+
return this.analyticsService.getCustomEventMetadata(data)
}
@@ -542,6 +548,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ await this.analyticsService.checkBillingAccess(pid)
+
return this.analyticsService.getFilters(pid, type)
}
@@ -586,6 +594,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ await this.analyticsService.checkBillingAccess(pid)
+
const paramsData = {
params: {
pid,
@@ -640,6 +650,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ await this.analyticsService.checkBillingAccess(pid)
+
let newTimeBucket = timeBucket
let allowedTumebucketForPeriodAll
let diff
@@ -741,6 +753,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ await this.analyticsService.checkBillingAccess(pid)
+
const paramsData = {
params: {
pid,
@@ -794,6 +808,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ await this.analyticsService.checkBillingAccess(pid)
+
let diff
if (period === 'all') {
@@ -860,6 +876,8 @@ export class AnalyticsController {
uid,
headers['x-password'],
)
+
+ await this.analyticsService.checkBillingAccess(currentPID)
})
await Promise.all(validationPromises)
@@ -895,6 +913,8 @@ export class AnalyticsController {
const validationPromises = _map(pidsArray, async currentPID => {
this.analyticsService.validatePID(currentPID)
await this.analyticsService.checkProjectAccess(currentPID, uid)
+
+ await this.analyticsService.checkBillingAccess(currentPID)
})
await Promise.all(validationPromises)
@@ -934,6 +954,8 @@ export class AnalyticsController {
uid,
headers['x-password'],
)
+
+ await this.analyticsService.checkBillingAccess(currentPID)
})
await Promise.all(validationPromises)
@@ -988,6 +1010,8 @@ export class AnalyticsController {
uid,
headers['x-password'],
)
+
+ await this.analyticsService.checkBillingAccess(currentPID)
})
await Promise.all(validationPromises)
@@ -1025,6 +1049,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ await this.analyticsService.checkBillingAccess(pid)
+
const keys = await redis.keys(`sd:*:${pid}`)
if (_isEmpty(keys)) {
@@ -1356,6 +1382,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ await this.analyticsService.checkBillingAccess(pid)
+
const take = this.analyticsService.getSafeNumber(data.take, 30)
const skip = this.analyticsService.getSafeNumber(data.skip, 0)
@@ -1442,6 +1470,9 @@ export class AnalyticsController {
uid,
headers['x-password'],
)
+
+ await this.analyticsService.checkBillingAccess(pid)
+
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
const result = await this.analyticsService.getSessionDetails(
@@ -1482,6 +1513,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ await this.analyticsService.checkBillingAccess(pid)
+
let newTimeBucket = timeBucket
let diff
let timeBucketForAllTime
diff --git a/apps/production/src/analytics/analytics.service.ts b/apps/production/src/analytics/analytics.service.ts
index 6a2e3f7ab..16eabda5d 100644
--- a/apps/production/src/analytics/analytics.service.ts
+++ b/apps/production/src/analytics/analytics.service.ts
@@ -38,11 +38,7 @@ import {
PreconditionFailedException,
} from '@nestjs/common'
-import {
- ACCOUNT_PLANS,
- DEFAULT_TIMEZONE,
- PlanCode,
-} from '../user/entities/user.entity'
+import { DEFAULT_TIMEZONE } from '../user/entities/user.entity'
import {
redis,
isValidPID,
@@ -343,6 +339,17 @@ export class AnalyticsService {
this.projectService.allowedToView(project, uid, password)
}
+ async checkBillingAccess(pid: string) {
+ const project = await this.projectService.getRedisProject(pid)
+
+ if (project.admin.dashboardBlockReason) {
+ throw new HttpException(
+ 'The account that owns this site is currently suspended, this is because of a billing issue. Please resolve the issue to continue.',
+ HttpStatus.PAYMENT_REQUIRED,
+ )
+ }
+ }
+
checkOrigin(project: Project, origin: string): void {
// For some reasons the project.origins sometimes may look like [''], let's filter it out
// TODO: Properly validate the origins on project update
@@ -446,20 +453,9 @@ export class AnalyticsService {
)
}
- if (project.admin.planCode === PlanCode.none) {
- throw new HttpException(
- 'You cannot send analytics to this project due to no active subscription. Please upgrade your account plan to continue sending analytics.',
- HttpStatus.PAYMENT_REQUIRED,
- )
- }
-
- const count = await this.projectService.getRedisCount(project.admin.id)
- const maxCount =
- ACCOUNT_PLANS[project.admin.planCode].monthlyUsageLimit || 0
-
- if (count >= maxCount) {
+ if (project.admin.isAccountBillingSuspended) {
throw new HttpException(
- 'You have exceeded the available monthly request limit for your account. Please upgrade your account plan if you need more requests.',
+ 'The account that owns this site is currently suspended, this is because of a billing issue. This, and all other events, are NOT being tracked and saved on our side. Please log in to your account on Swetrix or contact our support to resolve the issue.',
HttpStatus.PAYMENT_REQUIRED,
)
}
@@ -2714,7 +2710,10 @@ export class AnalyticsService {
.format('YYYY-MM-DD HH:mm:ss')
// eslint-disable-next-line
- timeBucket = dayjs(to).diff(dayjs(from), 'hour') > 1 ? TimeBucketType.HOUR : TimeBucketType.MINUTE
+ timeBucket =
+ dayjs(to).diff(dayjs(from), 'hour') > 1
+ ? TimeBucketType.HOUR
+ : TimeBucketType.MINUTE
const groupedChart = await this.groupChartByTimeBucket(
timeBucket,
diff --git a/apps/production/src/auth/guards/api-key-rate-limit.guard.ts b/apps/production/src/auth/guards/api-key-rate-limit.guard.ts
index 97b243ae2..ce42eb2b2 100644
--- a/apps/production/src/auth/guards/api-key-rate-limit.guard.ts
+++ b/apps/production/src/auth/guards/api-key-rate-limit.guard.ts
@@ -12,7 +12,11 @@ export class ApiKeyRateLimitGuard implements CanActivate {
if (!user) return false
const reqAmount =
- user.planCode === PlanCode.none ? 0 : user.maxApiKeyRequestsPerHour
+ user.planCode === PlanCode.none ||
+ user.isAccountBillingSuspended ||
+ user.dashboardBlockReason !== null
+ ? 0
+ : user.maxApiKeyRequestsPerHour
return checkRateLimitForApiKey(user.apiKey, reqAmount)
}
diff --git a/apps/production/src/common/constants.ts b/apps/production/src/common/constants.ts
index 2cb9718a6..306826076 100644
--- a/apps/production/src/common/constants.ts
+++ b/apps/production/src/common/constants.ts
@@ -100,6 +100,8 @@ const UNIQUE_SESSION_LIFE_TIME = 1800
// 35 seconds
const HEARTBEAT_SID_LIFE_TIME = 35
+const AFFILIATE_CUT = 0.2
+
// how often can user request a fresh GDPR export of their data; in days.
const GDPR_EXPORT_TIMEFRAME = 14
@@ -116,6 +118,8 @@ const CAPTCHA_SECRET_KEY_LENGTH = 50
const MIN_PAGES_IN_FUNNEL = 2
const MAX_PAGES_IN_FUNNEL = 10
+const TRAFFIC_SPIKE_ALLOWED_PERCENTAGE = 0.3
+
const BLOG_POSTS_ROOT = 'blog-posts/posts'
const BLOG_POSTS_PATH = isDevelopment
@@ -232,4 +236,6 @@ export {
MAX_FUNNELS,
ALL_COLUMNS,
BLOG_POSTS_ROOT,
+ TRAFFIC_SPIKE_ALLOWED_PERCENTAGE,
+ AFFILIATE_CUT,
}
diff --git a/apps/production/src/common/templates/en/dashboard-locked-exceeding-limits.html b/apps/production/src/common/templates/en/dashboard-locked-exceeding-limits.html
new file mode 100644
index 000000000..7f71ae68f
--- /dev/null
+++ b/apps/production/src/common/templates/en/dashboard-locked-exceeding-limits.html
@@ -0,0 +1,14 @@
+Hi! A week ago we contacted you regarding your website traffic exceeding your Swetrix subscription{{#if hitPercentageLimit}} by over {{percentageLimit}}% this month{{else}} for two consecutive months{{/if}}.
+<br /><br />
+Your subscription is still active, we're still counting your stats and we haven't deleted any of your data, but as you've outgrown your subscription tier, we'd like to ask you to upgrade to a tier that reflects your new traffic volumes. Once you have upgraded to an appropriate tier, your dashboard access will be restored immediately. A detailed usage report can be found on the <a href="{{billingUrl}}" target="_blank">billing page</a>.
+<br /><br />
+{{#ifEquals user.planCode "10m"}}
+Your usage exceeds our standard plans, so please reply to this email to receive a tailored offering and resolve this issue.
+<br /><br />
+Thank you again for using Swetrix.
+{{/ifEquals}}
+{{#ifNotEquals user.planCode "10m"}}
+We recommend that you upgrade to the {{suggestedPlanLimit}} events per month plan to keep up with your usage. The cost of the plan will be prorated to reflect the amount you have already paid for your current subscription plan.
+<br /><br />
+Thank you for using Swetrix, please reply to this email if you have any questions or need help with anything.
+{{/ifNotEquals}}
diff --git a/apps/production/src/common/templates/en/dashboard-locked-payment-failure.html b/apps/production/src/common/templates/en/dashboard-locked-payment-failure.html
new file mode 100644
index 000000000..5849bf23e
--- /dev/null
+++ b/apps/production/src/common/templates/en/dashboard-locked-payment-failure.html
@@ -0,0 +1,3 @@
+There was a problem with your last Swetrix subscription payment. We're still counting your stats and we haven't deleted any of your data, but due to the payment issue we've had to temporarily lock your analytics dashboard. Once you have updated your payment information, your dashboard access will be restored immediately. Please visit the <a href="{{billingUrl}}" target="_blank">billing page</a> for more details.
+<br /><br />
+Thank you for being a Swetrix subscriber, please reply to this email if you have any questions or need help with anything.
diff --git a/apps/production/src/common/templates/en/gdpr_data_export.html b/apps/production/src/common/templates/en/gdpr_data_export.html
index 4829494bd..b4a2da2bf 100644
--- a/apps/production/src/common/templates/en/gdpr_data_export.html
+++ b/apps/production/src/common/templates/en/gdpr_data_export.html
@@ -1,56 +1,141 @@
Swetrix GDPR Account Data Export.
-<br/>
-<i>Note: All times are Greenwich Mean Time unless specified otherwise.</i><br />
+<br />
+<i>Note: All times are Greenwich Mean Time unless specified otherwise.</i>
+<br /><br />
Below is the list of your Swetrix account information and settings (including your created projects) that you can request at any time.
<br/>
Our <a href="https://swetrix.com/privacy" target="_blank">Privacy Policy</a> has more information about what data we collect and how we use it.
-<br/>
+<br />
+<br />
<h3>Account Information:</h3>
-Account ID: {{user.id}}<br />
-Email address: {{user.email}}<br />
-Email confirmed: {{#if user.isActive}} Yes {{else}} No {{/if}}<br />
-Verification emails sent: {{user.emailRequests}}<br />
-Summary report frequency: {{user.reportFrequency}}<br />
-Is 2FA Enabled: {{#if user.isTwoFactorAuthenticationEnabled}} Yes {{else}} No {{/if}}<br />
-Account created at: {{user.created}}<br />
-Account updated at: {{user.updated}}<br />
-Last report generation time: {{user.exportedAt}}<br />
-Last tier warning email sent on: {{user.evWarningSentOn}}<br />
-Timezone: {{user.timezone}}<br />
-API Key: {{#if user.apiKey}}{{user.apiKey}}{{else}}-{{/if}}<br />
-Billing frequency: {{#if user.billingFrequency}}{{user.billingFrequency}}{{else}}-{{/if}}<br />
-Next billing date: {{#if user.nextBillDate}}{{user.nextBillDate}}{{else}}-{{/if}}<br />
-Paddle: Subscription ID: {{user.subID}}<br />
-Paddle: Update subscription URL: {{user.subUpdateURL}}<br />
-Paddle: Cancel subscription URL: {{user.subCancelURL}}<br />
-Is Telegram Chat ID confirmed: {{#if user.isTelegramChatIdConfirmed}} Yes {{else}} No {{/if}}<br />
-Telegram Chat ID: {{user.telegramChatId}}<br />
-Theme: {{user.theme}}<br />
-Nickname: {{user.nickname}}<br />
+<br />
+Account ID: {{user.id}}
+<br />
+Email address: {{user.email}}
+<br />
+Email confirmed: {{#if user.isActive}} Yes {{else}} No {{/if}}
+<br />
+Is registered with Google: {{user.registeredWithGoogle}}
+<br />
+Is registered with Github: {{user.registeredWithGithub}}
+<br />
+PayPal payouts email address: {{user.paypalPaymentsEmail}}
+<br />
+Verification emails sent: {{user.emailRequests}}
+<br />
+Summary report frequency: {{user.reportFrequency}}
+<br />
+Is 2FA Enabled: {{#if user.isTwoFactorAuthenticationEnabled}} Yes {{else}} No {{/if}}
+<br />
+Account created at: {{user.created}}
+<br />
+Account updated at: {{user.updated}}
+<br />
+Last report generation time: {{user.exportedAt}}
+<br />
+Last tier warning email sent on: {{user.evWarningSentOn}}
+<br />
+Timezone: {{user.timezone}}
+<br />
+API Key: {{#if user.apiKey}}{{user.apiKey}}{{else}}-{{/if}}
+<br />
+Max Projects: {{user.maxProjects}}
+<br />
+Max API requests per hour: {{user.maxApiKeyRequestsPerHour}}
+<br />
+Trial reminder sent: {{user.trialReminderSent}}
+<br />
+Show live visitors in title: {{user.showLiveVisitorsInTitle}}
+<br />
+Receive login notifications: {{user.receiveLoginNotifications}}
+<br />
+Time format: {{user.timeFormat}}
+<br />
+Plan exceed contacted at: {{user.planExceedContactedAt}}
+<br />
+Dashboard block reason: {{user.dashboardBlockReason}}
+<br />
+Account suspended (billing): {{user.isAccountBillingSuspended}}
+<br />
+Referral code: {{user.refCode}}
+<br />
+Referrer ID: {{user.referrerID}}
+<br />
+Subscription plan currency: {{user.tierCurrency}}
+<br />
+Billing cancellation effective date: {{user.cancellationEffectiveDate}}
+<br />
+Billing frequency: {{#if user.billingFrequency}}{{user.billingFrequency}}{{else}}-{{/if}}
+<br />
+Next billing date: {{#if user.nextBillDate}}{{user.nextBillDate}}{{else}}-{{/if}}
+<br />
+Paddle: Subscription ID: {{user.subID}}
+<br />
+Paddle: Update subscription URL: {{user.subUpdateURL}}
+<br />
+Paddle: Cancel subscription URL: {{user.subCancelURL}}
+<br />
+Is Telegram Chat ID confirmed: {{#if user.isTelegramChatIdConfirmed}} Yes {{else}} No {{/if}}
+<br />
+Telegram Chat ID: {{user.telegramChatId}}
+<br />
+Theme: {{user.theme}}
+<br />
+Nickname: {{user.nickname}}
+<br />
<h3>Projects Information:</h3>
+<br />
{{#each projects}}
- Project Identifier: {{id}}<br />
- Name: {{name}}<br />
- Active: {{#if active}} Yes {{else}} No {{/if}}<br />
- Public: {{#if public}} Yes {{else}} No {{/if}}<br />
- Allowed origins: {{#if origins}}{{origins}}{{else}}*{{/if}}<br />
- Blacklisted IPs: {{#if ipBlacklist}}{{ipBlacklist}}{{else}}-{{/if}}<br />
- Created at: {{created}}<br />
+ Project Identifier: {{id}}
+ <br />
+ Name: {{name}}
+ <br />
+ Active: {{#if active}} Yes {{else}} No {{/if}}
+ <br />
+ Public: {{#if public}} Yes {{else}} No {{/if}}
+ <br />
+ Allowed origins: {{#if origins}}{{origins}}{{else}}*{{/if}}
+ <br />
+ Blacklisted IPs: {{#if ipBlacklist}}{{ipBlacklist}}{{else}}-{{/if}}
+ <br />
+ Is transferring: {{#if isTransferring}} Yes {{else}} No {{/if}}
+ <br />
+ Is password protected: {{#if isPasswordProtected}} Yes {{else}} No {{/if}}
+ <br />
+ Is analytics project:{{#if isAnalyticsProject}} Yes {{else}} No {{/if}}
+ <br />
+ Is CAPTCHA project: {{#if isCaptchaProject}} Yes {{else}} No {{/if}}
+ <br />
+ Is CAPTCHA enabled: {{#if isCaptchaEnabled}} Yes {{else}} No {{/if}}
+ <br />
+ CAPTCHA secret key: {{captchaSecretKey}}
+ <br />
+ Created at: {{created}}
+ <br />
Automated alerts:
{{#each alerts}}
<br />
- Alert ID: {{id}}<br />
- Alert name: {{name}}<br />
- Alert active: {{#if active}} Yes {{else}} No {{/if}}<br />
- Alert last triggered: {{lastTriggered}}<br />
- Alert query metric: {{queryMetric}}<br />
- Alert query condition: {{queryCondition}}<br />
- Alert query value: {{queryValue}}<br />
- Alert query time: {{queryTime}}<br />
- Alert created at: {{created}}<br />
+ Alert ID: {{id}}
+ <br />
+ Alert name: {{name}}
+ <br />
+ Alert active: {{#if active}} Yes {{else}} No {{/if}}
+ <br />
+ Alert last triggered: {{lastTriggered}}
+ <br />
+ Alert query metric: {{queryMetric}}
+ <br />
+ Alert query condition: {{queryCondition}}
+ <br />
+ Alert query value: {{queryValue}}
+ <br />
+ Alert query time: {{queryTime}}
+ <br />
+ Alert created at: {{created}}
+ <br />
{{else}}
-
<br />
diff --git a/apps/production/src/common/templates/en/project-report.html b/apps/production/src/common/templates/en/project-report.html
index 7c9834b77..2aa3c2915 100644
--- a/apps/production/src/common/templates/en/project-report.html
+++ b/apps/production/src/common/templates/en/project-report.html
@@ -1,12 +1,123 @@
-Your {{#ifEquals type "w"}}Weekly{{/ifEquals}}{{#ifEquals type "M"}}Monthly{{/ifEquals}}{{#ifEquals type "Q"}}Quarterly{{/ifEquals}} Report
-<br/>
-For {{date}} period
-{{#each projects}}
-{{name}}
-Unique visitors: {{data.thisWeekUnique}} ({{#greater data.percChangeUnique 0}}+{{data.percChangeUnique}}%{{else}}{{data.percChangeUnique}}%{{/greater}})
-<br/>
-Pageviews: {{data.thisWeek}} ({{#greater data.percChange 0}}+{{data.percChange}}%{{else}}{{data.percChange}}%{{/greater}}
-<br/>
-{{/each}}
-{{tip}}
-You can manage email reports preferences in your <a href="https://swetrix.com/settings" target="_blank">account settings</a>.
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html>
+
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+ <title>Swetrix {{#ifEquals type "w"}}Weekly{{/ifEquals}}{{#ifEquals type "M"}}Monthly{{/ifEquals}}{{#ifEquals type
+ "Q"}}Quarterly{{/ifEquals}} Project Report</title>
+</head>
+
+<body style="margin: 0; padding: 0; background-color: #f0f4f7;">
+ <table cellpadding="0" cellspacing="0" border="0" width="100%"
+ style="background: #f0f4f7; min-width: 340px; font-size: 1px; line-height: normal;">
+ <tr>
+ <td align="center" valign="top" bgcolor="#f0f4f7">
+ <!--[if (gte mso 9)|(IE)]>
+ <table border="0" cellspacing="0" cellpadding="0">
+ <tr><td align="center" valign="top" width="750"><![endif]-->
+ <table cellpadding="0" cellspacing="0" border="0" width="750"
+ style="width: 100%; max-width: 750px; min-width: 340px; background: #f0f4f7;">
+ <tr>
+ <td width="25" style="width: 25px; max-width: 25px; min-width: 25px;">&nbsp;</td>
+ <td align="center" valign="top" style="background: #ffffff;">
+ <table cellpadding="0" cellspacing="0" border="0" width="100%"
+ style="width: 100% !important; min-width: 100%; max-width: 100%; background: #f0f4f7;">
+ <tr>
+ <td align="right" valign="top">
+ <div style="height: 25px; line-height: 25px; font-size: 23px;">&nbsp;</div>
+ </td>
+ </tr>
+ </table>
+ <table cellpadding="0" cellspacing="0" border="0" width="88%"
+ style="width: 88% !important; min-width: 88%; max-width: 88%;">
+ <tr>
+ <td align="center" valign="top">
+ <div style="height: 40px; line-height: 40px; font-size: 38px;">&nbsp;</div>
+ <a href="https://swetrix.com" target="_blank"
+ style="display: block; max-width: 173px;text-decoration: none;">
+ <img src="https://swetrix.com/assets/logo_blue.png" alt="Swetrix" width="175" border="0"
+ style="display: block; width: 175px; font-size: 32px;" />
+ </a>
+ <div style="height: 40px; line-height: 40px; font-size: 40px;">&nbsp;</div>
+ </td>
+ </tr>
+ </table>
+ <table cellpadding="0" cellspacing="0" border="0" width="88%"
+ style="width: 88% !important; min-width: 88%; max-width: 88%;">
+ <tr>
+ <td align="center" valign="top">
+ <font align="center"
+ style="font-size: 52px; line-height: 55px; font-weight: 300; letter-spacing: -1.5px;">
+ <span align="center"
+ style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; font-size: 44px; color: #1a1a1a;">
+ Your {{#ifEquals type "w"}}Weekly{{/ifEquals}}{{#ifEquals type
+ "M"}}Monthly{{/ifEquals}}{{#ifEquals type "Q"}}Quarterly{{/ifEquals}} Report
+ </span>
+ </font>
+ <div style="height: 10px; line-height: 10px; font-size: 9px;">&nbsp;</div>
+ <font style="font-size: 36px; line-height: 45px; font-weight: 300; letter-spacing: -1px;">
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ color: #5e5e5e;
+ font-size: 30px;
+ line-height: 45px;
+ font-weight: 300;
+ letter-spacing: -1px;
+ ">
+ For the {{date}} period
+ </span>
+ </font>
+ <div style="height: 38px; line-height: 38px; font-size: 36px;">&nbsp;</div>
+ <table cellpadding="0" cellspacing="0" border="0" width="88%"
+ style="width: 88% !important; min-width: 88%; max-width: 88%;">
+ <tr>
+ <td align="left" valign="top">
+ <font face="'Source Sans Pro', sans-serif" color="#6d6d6d"
+ style="font-size: 17px; line-height: 23px;">
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ color: #6d6d6d;
+ font-size: 17px;
+ line-height: 23px;
+ ">
+ {{#each projects}}
+ <h3 style="margin-bottom: 5px;">{{name}}</h3>
+ <b>Unique visitors:</b> {{data.thisWeekUnique}} ({{#greater data.percChangeUnique 0}}<span
+ style="color: #059669;">+{{data.percChangeUnique}}%</span>{{else}}<span
+ style="color: #DC2626;">{{data.percChangeUnique}}%</span>{{/greater}})<br />
+ <b>Pageviews:</b> {{data.thisWeek}} ({{#greater data.percChange 0}}<span
+ style="color: #059669;">+{{data.percChange}}%</span>{{else}}<span
+ style="color: #DC2626;">{{data.percChange}}%</span>{{/greater}})<br /><br />
+ {{/each}}
+
+ <i style="white-space: pre-line;">
+ <span style="font-style: normal;">&#128161;</span>
+ {{tip}}
+ </i>
+
+ <br /><br />
+
+ You can manage email reports preferences in your <a href="https://swetrix.com/settings"
+ target="_blank">account settings</a>.
+ </span>
+ </font>
+ <div style="height: 30px; line-height: 30px; font-size: 28px;">&nbsp;</div>
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ </table>
+ </td>
+ <td width="25" style="width: 25px; max-width: 25px; min-width: 25px;">&nbsp;</td>
+ </tr>
+ </table>
+ <!--[if (gte mso 9)|(IE)]>
+ </td></tr>
+ </table><![endif]-->
+ </td>
+ </tr>
+ </table>
+</body>
+
+</html>
\ No newline at end of file
diff --git a/apps/production/src/common/templates/en/subscription-cancelled.html b/apps/production/src/common/templates/en/subscription-cancelled.html
new file mode 100644
index 000000000..04b41aa9e
--- /dev/null
+++ b/apps/production/src/common/templates/en/subscription-cancelled.html
@@ -0,0 +1 @@
+Hi, we've noticed that you've cancelled your Swetrix subscription. We'd like to get your feedback on why you decided to cancel and if there's anything we can do to improve our service. We are funded entirely by our subscribers and we'd really appreciate your feedback! Please feel free to reply to this email and thank you for your time :)
diff --git a/apps/production/src/common/templates/en/trial-ends-tomorrow.html b/apps/production/src/common/templates/en/trial-ends-tomorrow.html
index 611416343..2782b35cc 100644
--- a/apps/production/src/common/templates/en/trial-ends-tomorrow.html
+++ b/apps/production/src/common/templates/en/trial-ends-tomorrow.html
@@ -1,13 +1,6 @@
-Time goes by so fast! Your free Swetrix trial ends tomorrow!
-<br/><br />
-We hope that you enjoyed using Swetrix and liked the experience of using a service that respects user privacy, does not annoy your users with cookie banners and keeps your website as fast as possible :)
+Your free Swetrix trial ends tomorrow, we hope that you enjoyed using Swetrix and liked the experience of using a service that respects user privacy, does not annoy your users with cookie banners and keeps your website as fast as possible :)
<br/>
-If you wish to continue using Swetrix and receiving all the needed analytics data easily, you'll need to upgrade your account.
-<br/>
-You can do it by clicking the link below or going to the Billing page.
-<br/>
-<br/>
-<a href="{{url}}" target="_blank">Upgrade</a>
+If you wish to continue using Swetrix and receiving all the needed analytics data easily, you'll need to <a href="{{url}}" target="_blank">upgrade</a> your account to one of our subscription plans.
<br/>
<br/>
Please reply back to this email in case you have any questions or need assistance.
diff --git a/apps/production/src/common/templates/en/trial-expired.html b/apps/production/src/common/templates/en/trial-expired.html
index 114ba2b65..13d3a6ffa 100644
--- a/apps/production/src/common/templates/en/trial-expired.html
+++ b/apps/production/src/common/templates/en/trial-expired.html
@@ -1,13 +1,7 @@
-Your free Swetrix trial has ended.
-<br/>
-We hope that you enjoyed using Swetrix so far!
+Your free Swetrix trial has ended, we hope you have enjoyed using Swetrix so far!
<br/><br/>
-If you wish to continue using Swetrix and receiving all the needed analytics data easily, you'll need to upgrade your account.
+Please upgrade your account to one of our subscription tiers to continue receiving analytics insights about your website while respecting your users' privacy.
<br/><br/>
-You can do it by clicking the link below or going to the Billing page.
-<br/>
-<br/>
<a href="{{url}}" target="_blank">Upgrade</a>
-<br/>
-<br/>
-You can reply back to this email in case you have any questions!
+<br/><br/>
+Please reply back to this email in case you have any questions or need assistance.
diff --git a/apps/production/src/common/templates/en/usage-over-limit.html b/apps/production/src/common/templates/en/usage-over-limit.html
new file mode 100644
index 000000000..a6f4ae098
--- /dev/null
+++ b/apps/production/src/common/templates/en/usage-over-limit.html
@@ -0,0 +1,23 @@
+Hi! First of all, thanks a lot for {{#ifEquals user.planCode "trial"}}giving Swetrix a try!{{/ifEquals}}{{#ifNotEquals user.planCode "trial"}}being a Swetrix subscriber.{{/ifNotEquals}}
+<br /><br />
+We'd like to inform you that your traffic has exceeded your subscription plan{{#if hitPercentageLimit}} by over {{percentageLimit}}% this month{{else}} for two consecutive months{{/if}}.
+<br /><br />
+In order to continue using Swetrix and have access to your stats, we kindly ask you to upgrade your subscription plan to reflect your usage. If you don't take action to upgrade your account to a new plan within the next {{upgradePeriodDays}} days, access to your stats will be temporarily blocked (please note that we will not stop collecting data, just block your account until the issue is resolved).
+<br /><br />
+{{#if hitPercentageLimit}}
+This month you have used {{thisMonthUsage}} billable events, which exceeds your plan limit by more than {{percentageLimit}}%.
+{{else}}
+This month you have used {{thisMonthUsage}} billable events, the month before that you used {{lastMonthUsage}} events.
+{{/if}}
+Billable events include pageviews, custom events and CAPTCHA events. A detailed usage report can be found on the <a href="{{billingUrl}}" target="_blank">billing page</a>.
+<br /><br />
+{{#ifEquals user.planCode "10m"}}
+Your usage exceeds our standard plans, so please reply to this email to receive a tailored offering and resolve this issue.
+<br /><br />
+Thank you again for using Swetrix and sorry for the inconvenience.
+{{/ifEquals}}
+{{#ifNotEquals user.planCode "10m"}}
+We recommend that you upgrade to the {{suggestedPlanLimit}} events per month plan to keep up with your usage. The cost of the plan will be prorated to reflect the amount you have already paid for your current subscription plan.
+<br /><br />
+Thank you again for using Swetrix and sorry for the inconvenience, please reply to this email if you have any questions or need help with anything.
+{{/ifNotEquals}}
diff --git a/apps/production/src/mailer/letter.ts b/apps/production/src/mailer/letter.ts
index 073ce0bf5..5b01d6581 100644
--- a/apps/production/src/mailer/letter.ts
+++ b/apps/production/src/mailer/letter.ts
@@ -8,6 +8,7 @@ export enum LetterTemplate {
GDPRDataExport = 'gdpr_data_export',
ProjectReport = 'project-report',
TierWarning = 'tier-warning',
+ SubscriptionCancelled = 'subscription-cancelled',
ProjectInvitation = 'customer_project-invitation',
TwoFAOn = '2fa-turned-on',
TwoFAOff = '2fa-turned-off',
@@ -16,4 +17,7 @@ export enum LetterTemplate {
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/apps/production/src/mailer/mailer.service.ts b/apps/production/src/mailer/mailer.service.ts
index aa3d58dbf..63f655e70 100644
--- a/apps/production/src/mailer/mailer.service.ts
+++ b/apps/production/src/mailer/mailer.service.ts
@@ -53,12 +53,17 @@ const metaInfoJson = {
[LetterTemplate.TierWarning]: {
subject: {
en: () =>
- `You have used more than ${SEND_WARNING_AT_PERC}% of the available events per your tier for this month.`,
+ `You have used more than ${SEND_WARNING_AT_PERC}% of the available events per your tier for this month`,
+ },
+ },
+ [LetterTemplate.SubscriptionCancelled]: {
+ subject: {
+ en: () => 'Your feedback on Swetrix',
},
},
[LetterTemplate.ProjectInvitation]: {
subject: {
- en: () => 'You have been invited to join the project.',
+ en: () => 'You have been invited to join the project',
},
},
[LetterTemplate.TwoFAOn]: {
@@ -83,13 +88,13 @@ const metaInfoJson = {
},
[LetterTemplate.ProjectSubscriberInvitation]: {
subject: {
- en: () => 'You have been invited to join the project.',
+ en: () => 'You have been invited to join the project',
},
},
[LetterTemplate.ProjectTransfer]: {
subject: {
en: (p: Params) =>
- `A Swetrix user offers to transfer ${p.name} project to your account.`,
+ `A Swetrix user offers to transfer ${p.name} project to your account`,
},
},
[LetterTemplate.PayPalEmailUpdate]: {
@@ -97,6 +102,21 @@ const metaInfoJson = {
en: () => 'Your PayPal email has been updated',
},
},
+ [LetterTemplate.UsageOverLimit]: {
+ subject: {
+ en: () => 'You have exceeded your Swetrix subscription plan',
+ },
+ },
+ [LetterTemplate.DashboardLockedExceedingLimits]: {
+ subject: {
+ en: () => 'Your Swetrix dashboard has been locked',
+ },
+ },
+ [LetterTemplate.DashboardLockedPaymentFailure]: {
+ subject: {
+ en: () => 'Your Swetrix dashboard has been locked due to a payment issue',
+ },
+ },
}
interface Params {
@@ -108,6 +128,14 @@ handlebars.registerHelper('ifEquals', function ifEquals(arg1, arg2, options) {
return arg1 == arg2 ? options.fn(this) : options.inverse(this)
})
+handlebars.registerHelper(
+ 'ifNotEquals',
+ function ifNotEquals(arg1, arg2, options) {
+ // eslint-disable-next-line eqeqeq
+ return arg1 != arg2 ? options.fn(this) : options.inverse(this)
+ },
+)
+
handlebars.registerHelper('greater', function greater(v1, v2, options) {
if (v1 > v2) {
return options.fn(this)
diff --git a/apps/production/src/marketplace/extensions/extensions.controller.ts b/apps/production/src/marketplace/extensions/extensions.controller.ts
index 461129778..2c046165e 100644
--- a/apps/production/src/marketplace/extensions/extensions.controller.ts
+++ b/apps/production/src/marketplace/extensions/extensions.controller.ts
@@ -339,7 +339,6 @@ export class ExtensionsController {
required: false,
type: String,
})
-
@ApiBearerAuth()
@Roles(UserType.ADMIN)
@UseGuards(JwtAccessTokenGuard, RolesGuard)
diff --git a/apps/production/src/project/project.controller.ts b/apps/production/src/project/project.controller.ts
index 3c305f30a..7d1eb3095 100644
--- a/apps/production/src/project/project.controller.ts
+++ b/apps/production/src/project/project.controller.ts
@@ -161,13 +161,22 @@ export class ProjectController {
}
}
- const paginated = await this.projectService.paginate({ take, skip }, where)
-
- const totalMonthlyEvents = await this.projectService.getRedisCount(userId)
+ const [paginated, totalMonthlyEvents, user] = await Promise.all([
+ this.projectService.paginate({ take, skip }, where),
+ this.projectService.getRedisCount(userId),
+ this.userService.findOneWhere(
+ {
+ id: userId,
+ },
+ [],
+ ['dashboardBlockReason'],
+ ),
+ ])
paginated.results = _map(paginated.results, p => ({
...p,
isOwner: true,
+ isLocked: !!user.dashboardBlockReason,
}))
return {
@@ -365,6 +374,13 @@ export class ProjectController {
)
}
+ if (user.isAccountBillingSuspended) {
+ throw new HttpException(
+ 'This account is currently suspended, this is because of a billing issue. Please resolve the issue to continue.',
+ HttpStatus.PAYMENT_REQUIRED,
+ )
+ }
+
if (projectDTO.isCaptcha) {
if (
_size(
@@ -480,6 +496,13 @@ export class ProjectController {
)
}
+ if (user.isAccountBillingSuspended) {
+ throw new HttpException(
+ 'This account is currently suspended, this is because of a billing issue. Please resolve the issue to continue.',
+ HttpStatus.PAYMENT_REQUIRED,
+ )
+ }
+
const project = await this.projectService.findOneWhere(
{
id: funnelDTO.pid,
@@ -527,6 +550,13 @@ export class ProjectController {
)
}
+ if (user.isAccountBillingSuspended) {
+ throw new HttpException(
+ 'This account is currently suspended, this is because of a billing issue. Please resolve the issue to continue.',
+ HttpStatus.PAYMENT_REQUIRED,
+ )
+ }
+
const project = await this.projectService.findOneWhere(
{
id: funnelDTO.pid,
@@ -1731,6 +1761,7 @@ export class ProjectController {
return {
..._omit(project, ['admin', 'passwordHash', 'share']),
isOwner: uid === project.admin?.id,
+ isLocked: !!project.admin?.dashboardBlockReason,
}
}
}
diff --git a/apps/production/src/project/project.service.ts b/apps/production/src/project/project.service.ts
index 9909af331..bef945821 100644
--- a/apps/production/src/project/project.service.ts
+++ b/apps/production/src/project/project.service.ts
@@ -803,6 +803,16 @@ export class ProjectService {
await this.clearProjectsRedisCache(user.id)
}
+ async clearProjectsRedisCacheBySubId(subID: string): Promise<void> {
+ const user = await this.userService.findOneWhere({ subID })
+
+ if (!user) {
+ return
+ }
+
+ await this.clearProjectsRedisCache(user.id)
+ }
+
async getProject(projectId: string, userId: string) {
return this.projectsRepository.findOne({
where: {
diff --git a/apps/production/src/task-manager/interfaces/ch-plan-usage.interface.ts b/apps/production/src/task-manager/interfaces/ch-plan-usage.interface.ts
new file mode 100644
index 000000000..5708548bb
--- /dev/null
+++ b/apps/production/src/task-manager/interfaces/ch-plan-usage.interface.ts
@@ -0,0 +1,4 @@
+export interface CHPlanUsage {
+ id: string
+ count: number
+}
diff --git a/apps/production/src/task-manager/interfaces/index.ts b/apps/production/src/task-manager/interfaces/index.ts
new file mode 100644
index 000000000..e03ef0e60
--- /dev/null
+++ b/apps/production/src/task-manager/interfaces/index.ts
@@ -0,0 +1 @@
+export * from './ch-plan-usage.interface'
diff --git a/apps/production/src/task-manager/task-manager.service.ts b/apps/production/src/task-manager/task-manager.service.ts
index 7304da4e4..638961f67 100644
--- a/apps/production/src/task-manager/task-manager.service.ts
+++ b/apps/production/src/task-manager/task-manager.service.ts
@@ -12,8 +12,10 @@ import * as _size from 'lodash/size'
import * as _map from 'lodash/map'
import * as _now from 'lodash/now'
import * as _find from 'lodash/find'
+import * as _includes from 'lodash/includes'
import * as _toNumber from 'lodash/toNumber'
import * as _reduce from 'lodash/reduce'
+import * as _filter from 'lodash/filter'
import { AlertService } from '../alert/alert.service'
import { QueryCondition, QueryMetric, QueryTime } from '../alert/dto/alert.dto'
@@ -35,6 +37,9 @@ import {
PlanCode,
BillingFrequency,
TRIAL_DURATION,
+ User,
+ getNextPlan,
+ DashboardBlockReason,
} from '../user/entities/user.entity'
import {
clickhouse,
@@ -52,8 +57,10 @@ import {
JWT_REFRESH_TOKEN_LIFETIME,
PAYPAL_CLIENT_ID,
PAYPAL_CLIENT_SECRET,
+ TRAFFIC_SPIKE_ALLOWED_PERCENTAGE,
isDevelopment,
} from '../common/constants'
+import { CHPlanUsage } from './interfaces'
import { getRandomTip } from '../common/utils'
import { AppLoggerService } from '../logger/logger.service'
@@ -97,6 +104,129 @@ const getQueryCondition = (condition: QueryCondition): string => {
return ''
}
+// TODO: Check custom events & CAPTCHA events as well
+const generatePlanUsageQuery = (
+ users: User[],
+ getDate: (user?: User) => string,
+): string => {
+ let query = ''
+
+ for (let i = 0; i < _size(users); ++i) {
+ const user = users[i]
+ const pidsStringified = _map(user.projects, p => `'${p.id}'`).join(',')
+
+ query += `SELECT '${
+ user.id
+ }' AS id, count(*) AS "count" FROM analytics WHERE pid IN (${pidsStringified}) and created > '${getDate(
+ user,
+ )}'`
+
+ if (_size(users) - 1 !== i) {
+ query += ' UNION ALL '
+ }
+ }
+
+ return query
+}
+
+const getUsersThatExceedPlanUsage = (
+ users: User[],
+ usage: CHPlanUsage[],
+ allowedExceed = TRAFFIC_SPIKE_ALLOWED_PERCENTAGE,
+): User & { usage: number }[] => {
+ const usageMap = _reduce(
+ usage,
+ (acc, value: CHPlanUsage) => ({
+ ...acc,
+ [value.id]: value.count,
+ }),
+ {},
+ )
+ const exceedingUsers = []
+
+ for (let i = 0; i < _size(users); ++i) {
+ const user = users[i]
+ const allowedEvents = ACCOUNT_PLANS[user.planCode].monthlyUsageLimit
+
+ if (usageMap[user.id] > allowedEvents + allowedEvents * allowedExceed) {
+ exceedingUsers.push({
+ ...user,
+ usage: usageMap[user.id],
+ })
+ }
+ }
+
+ return exceedingUsers as User & { usage: number }[]
+}
+
+const getUserIDsThatExceedPlanUsage = (
+ users: User[],
+ usage: CHPlanUsage[],
+ allowedExceed = TRAFFIC_SPIKE_ALLOWED_PERCENTAGE,
+): string[] => {
+ const usageMap = _reduce(
+ usage,
+ (acc, value: CHPlanUsage) => ({
+ ...acc,
+ [value.id]: value.count,
+ }),
+ {},
+ )
+ const exceedingUsers = []
+
+ for (let i = 0; i < _size(users); ++i) {
+ const user = users[i]
+ const allowedEvents = ACCOUNT_PLANS[user.planCode].monthlyUsageLimit
+
+ if (usageMap[user.id] > allowedEvents + allowedEvents * allowedExceed) {
+ exceedingUsers.push(user.id)
+ }
+ }
+
+ return exceedingUsers
+}
+
+const getUsersThatExceedContinuously = (
+ users: User[],
+ usage: CHPlanUsage[][],
+): User & { usage: any[] }[] => {
+ const transformedUsage = _map(usage, (el: CHPlanUsage[]) => {
+ return _reduce(
+ el,
+ (acc, value: CHPlanUsage) => ({
+ ...acc,
+ [value.id]: value.count,
+ }),
+ {},
+ )
+ })
+
+ const exceedingUsers = []
+
+ for (let i = 0; i < _size(users); ++i) {
+ let exceedingTimes = 0
+ const user = users[i]
+ const allowedEvents = ACCOUNT_PLANS[user.planCode].monthlyUsageLimit
+ const userUsage = []
+
+ for (let x = 0; x < _size(transformedUsage); ++x) {
+ userUsage.push(transformedUsage[x][user.id])
+ if (transformedUsage[x][user.id] > allowedEvents) {
+ exceedingTimes++
+ }
+ }
+
+ if (exceedingTimes === _size(usage)) {
+ exceedingUsers.push({
+ ...user,
+ usage: userUsage,
+ })
+ }
+ }
+
+ return exceedingUsers as User & { usage: any[] }[]
+}
+
@Injectable()
export class TaskManagerService {
constructor(
@@ -169,6 +299,201 @@ export class TaskManagerService {
}
}
+ @Cron(CronExpression.EVERY_DAY_AT_5PM)
+ async lockDashboards(): Promise<void> {
+ const sevenDaysAgo = dayjs
+ .utc()
+ .subtract(7, 'days')
+ .format('YYYY-MM-DD HH:mm:ss')
+
+ const users = await this.userService.find({
+ where: {
+ isActive: true,
+ planCode: Not(PlanCode.none),
+ planExceedContactedAt: MoreThan(sevenDaysAgo),
+ dashboardBlockReason: IsNull(),
+ isAccountBillingSuspended: false,
+ },
+ relations: ['projects'],
+ select: ['id', 'email', 'planCode'],
+ })
+
+ if (_isEmpty(users)) {
+ return
+ }
+
+ const monthlyUsageQuery = generatePlanUsageQuery(users, (user: User) =>
+ dayjs.utc(user.planExceedContactedAt).format('YYYY-MM-01'),
+ )
+
+ const monthlyUsage = <CHPlanUsage[]>(
+ await clickhouse.query(monthlyUsageQuery).toPromise()
+ )
+
+ const exceedingUserIds = getUserIDsThatExceedPlanUsage(users, monthlyUsage)
+
+ await Promise.allSettled(
+ _map(users, async (user: User) => {
+ const { id, email, planCode } = user
+
+ const suggestedPlanLimit = getNextPlan(planCode)
+
+ const data = {
+ user,
+ hitPercentageLimit: _includes(exceedingUserIds, user.id),
+ percentageLimit: TRAFFIC_SPIKE_ALLOWED_PERCENTAGE * 100,
+ billingUrl: 'https://swetrix.com/billing',
+ suggestedPlanLimit,
+ }
+
+ await this.mailerService.sendEmail(
+ email,
+ LetterTemplate.DashboardLockedExceedingLimits,
+ data,
+ )
+ await this.userService.update(id, {
+ dashboardBlockReason: DashboardBlockReason.exceeding_plan_limits,
+ })
+ }),
+ ).catch(reason => {
+ this.logger.error(
+ `[CRON WORKER](lockDashboards) Error occured: ${reason}`,
+ )
+ })
+ }
+
+ @Cron(CronExpression.EVERY_DAY_AT_4PM)
+ async checkPlanUsage(): Promise<void> {
+ const users = await this.userService.find({
+ where: {
+ isActive: true,
+ planCode: Not(PlanCode.none),
+ planExceedContactedAt: IsNull(),
+ dashboardBlockReason: IsNull(),
+ isAccountBillingSuspended: false,
+ },
+ relations: ['projects'],
+ select: ['id', 'email', 'planCode'],
+ })
+
+ if (_isEmpty(users)) {
+ return
+ }
+
+ const planExceedContactedAt = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
+
+ const thisMonthDate = dayjs.utc().format('YYYY-MM-01')
+ const thisMonthQuery = generatePlanUsageQuery(users, () => thisMonthDate)
+
+ const thisMonthUsage = <CHPlanUsage[]>(
+ await clickhouse.query(thisMonthQuery).toPromise()
+ )
+
+ const exceedingUsers = getUsersThatExceedPlanUsage(users, thisMonthUsage)
+
+ // if there are exceeding users, contact them and let them know that their usage is > than 30% their tier allows
+ if (!_isEmpty(exceedingUsers)) {
+ const percExceedingUsagePromises = _map(exceedingUsers, async user => {
+ const { id, email, usage, planCode } = user
+
+ const suggestedPlanLimit = getNextPlan(planCode)
+
+ const data = {
+ user,
+ hitPercentageLimit: true,
+ upgradePeriodDays: 7,
+ thisMonthUsage: usage,
+ percentageLimit: TRAFFIC_SPIKE_ALLOWED_PERCENTAGE * 100,
+ billingUrl: 'https://swetrix.com/billing',
+ suggestedPlanLimit,
+ }
+
+ await this.mailerService.sendEmail(
+ email,
+ LetterTemplate.UsageOverLimit,
+ data,
+ )
+ await this.userService.update(id, {
+ planExceedContactedAt,
+ })
+ })
+
+ await Promise.allSettled(percExceedingUsagePromises).catch(reason => {
+ this.logger.error(
+ `[CRON WORKER](checkPlanUsage - percExceedingUsagePromises) Error occured: ${reason}`,
+ )
+ })
+ }
+
+ const filteredUsers = _filter(
+ users,
+ user =>
+ !_find(exceedingUsers, exceedingUser => exceedingUser.id === user.id),
+ )
+
+ if (_isEmpty(filteredUsers)) {
+ return
+ }
+
+ const lastMonthDate = dayjs.utc().subtract(1, 'M').format('YYYY-MM-01')
+ const lastMonthQuery = generatePlanUsageQuery(
+ filteredUsers,
+ () => lastMonthDate,
+ )
+
+ const lastMonthUsage = <CHPlanUsage[]>(
+ await clickhouse.query(lastMonthQuery).toPromise()
+ )
+
+ const continuousExceedingUsers = getUsersThatExceedContinuously(users, [
+ // the order should be kept like this
+ thisMonthUsage,
+ lastMonthUsage,
+ ])
+
+ // if there are exceeding users, contact them and let them know that their usage more then what their tier allows for two consequetive months
+ if (!_isEmpty(continuousExceedingUsers)) {
+ const continuousExceedingUsagePromises = _map(
+ continuousExceedingUsers,
+ async user => {
+ const { id, email, usage, planCode } = user
+
+ const [userThisMonthUsage, userLastMonthUsage] = usage || []
+
+ const suggestedPlanLimit = getNextPlan(planCode)
+
+ const data = {
+ user,
+ hitPercentageLimit: false,
+ upgradePeriodDays: 7,
+ thisMonthUsage: userThisMonthUsage,
+ lastMonthUsage: userLastMonthUsage,
+ percentageLimit: TRAFFIC_SPIKE_ALLOWED_PERCENTAGE * 100,
+ billingUrl: 'https://swetrix.com/billing',
+ suggestedPlanLimit,
+ }
+
+ await this.mailerService.sendEmail(
+ email,
+ LetterTemplate.UsageOverLimit,
+ data,
+ )
+ await this.userService.update(id, {
+ planExceedContactedAt,
+ })
+ },
+ )
+
+ await Promise.allSettled(continuousExceedingUsagePromises).catch(
+ reason => {
+ this.logger.error(
+ `[CRON WORKER](checkPlanUsage - continuousExceedingUsagePromises) Error occured: ${reason}`,
+ )
+ },
+ )
+ }
+ }
+
@Cron(CronExpression.EVERY_DAY_AT_9AM)
async checkLeftEvents(): Promise<void> {
const thisMonth = dayjs.utc().format('YYYY-MM-01')
@@ -178,11 +503,13 @@ export class TaskManagerService {
evWarningSentOn: IsNull(),
isActive: true,
planCode: Not(PlanCode.none),
+ dashboardBlockReason: IsNull(),
},
{
evWarningSentOn: LessThan(thisMonth),
isActive: true,
planCode: Not(PlanCode.none),
+ dashboardBlockReason: IsNull(),
},
],
relations: ['projects'],
@@ -261,6 +588,8 @@ export class TaskManagerService {
const users = await this.userService.find({
where: {
reportFrequency: ReportFrequency.WEEKLY,
+ planCode: Not(PlanCode.none),
+ dashboardBlockReason: IsNull(),
},
relations: ['projects'],
select: ['email'],
@@ -313,6 +642,8 @@ export class TaskManagerService {
const users = await this.userService.find({
where: {
reportFrequency: ReportFrequency.MONTHLY,
+ planCode: Not(PlanCode.none),
+ dashboardBlockReason: IsNull(),
},
relations: ['projects'],
select: ['email'],
@@ -364,6 +695,8 @@ export class TaskManagerService {
const users = await this.userService.find({
where: {
reportFrequency: ReportFrequency.QUARTERLY,
+ planCode: Not(PlanCode.none),
+ dashboardBlockReason: IsNull(),
},
relations: ['projects'],
select: ['email'],
@@ -650,7 +983,12 @@ export class TaskManagerService {
await this.userService.update(user.id, {
cancellationEffectiveDate: null,
planCode: PlanCode.none,
+ dashboardBlockReason: DashboardBlockReason.subscription_cancelled,
+ planExceedContactedAt: user.cancellationEffectiveDate,
nextBillDate: null,
+ subID: null,
+ subUpdateURL: null,
+ subCancelURL: null,
billingFrequency: BillingFrequency.Monthly,
})
await this.projectService.clearProjectsRedisCache(user.id)
@@ -742,6 +1080,7 @@ export class TaskManagerService {
await this.userService.update(id, {
planCode: PlanCode.none,
+ dashboardBlockReason: DashboardBlockReason.trial_ended,
// trialEndDate: null,
})
await this.mailerService.sendEmail(email, LetterTemplate.TrialExpired)
@@ -754,13 +1093,13 @@ export class TaskManagerService {
}
@Cron(CronExpression.EVERY_5_MINUTES)
- // @Cron(CronExpression.EVERY_5_SECONDS)
async checkOnlineUsersAlerts(): Promise<void> {
const projects = await this.projectService.findWhere(
{
admin: {
isTelegramChatIdConfirmed: true,
planCode: Not(PlanCode.none),
+ dashboardBlockReason: IsNull(),
},
},
['admin'],
@@ -814,13 +1153,13 @@ export class TaskManagerService {
}
@Cron(CronExpression.EVERY_5_MINUTES)
- // @Cron(CronExpression.EVERY_5_SECONDS)
async checkMetricAlerts(): Promise<void> {
const projects = await this.projectService.findWhere(
{
admin: {
isTelegramChatIdConfirmed: true,
planCode: Not(PlanCode.none),
+ dashboardBlockReason: IsNull(),
},
},
['admin'],
diff --git a/apps/production/src/user/entities/user.entity.ts b/apps/production/src/user/entities/user.entity.ts
index 0db5917eb..a1d78c968 100644
--- a/apps/production/src/user/entities/user.entity.ts
+++ b/apps/production/src/user/entities/user.entity.ts
@@ -31,6 +31,13 @@ export enum PlanCode {
'10m' = '10m',
}
+export enum DashboardBlockReason {
+ 'exceeding_plan_limits' = 'exceeding_plan_limits',
+ 'trial_ended' = 'trial_ended',
+ 'payment_failed' = 'payment_failed',
+ 'subscription_cancelled' = 'subscription_cancelled',
+}
+
export const ACCOUNT_PLANS = {
[PlanCode.none]: {
id: PlanCode.none,
@@ -116,6 +123,33 @@ export const ACCOUNT_PLANS = {
},
}
+export const getNextPlan = (planCode: PlanCode) => {
+ const currentLimit = ACCOUNT_PLANS[planCode].monthlyUsageLimit
+
+ let nextPlan
+
+ Object.values(ACCOUNT_PLANS).some(plan => {
+ if (plan.monthlyUsageLimit > currentLimit) {
+ nextPlan = plan
+ return true
+ }
+
+ return false
+ })
+
+ return nextPlan
+}
+
+export const isNextPlan = (
+ currentPlanCode: PlanCode,
+ potentialNextPlanCode: PlanCode,
+): boolean => {
+ const currentPlanLimit = ACCOUNT_PLANS[currentPlanCode].monthlyUsageLimit
+ const nextPlanLimit = ACCOUNT_PLANS[potentialNextPlanCode].monthlyUsageLimit
+
+ return nextPlanLimit > currentPlanLimit
+}
+
export enum UserType {
CUSTOMER = 'customer',
ADMIN = 'admin',
@@ -242,6 +276,24 @@ export class User {
@Column({ default: false })
showLiveVisitorsInTitle: boolean
+ /* Plan usage related fields */
+ // the date when user was last contacted about exceeding the plan limits for X consecutive months
+ @Column({ type: 'timestamp', nullable: true })
+ planExceedContactedAt: Date
+
+ // dashboard block reason
+ @Column({
+ type: 'enum',
+ enum: DashboardBlockReason,
+ nullable: true,
+ })
+ dashboardBlockReason: DashboardBlockReason
+
+ // if we should stop counting user events
+ @Column({ default: false })
+ isAccountBillingSuspended: boolean
+
+ /* Affiliate system related fields */
@Column('varchar', { length: 8, default: null })
refCode: string | null
@@ -261,6 +313,8 @@ export class User {
this.updated = new Date()
}
+ /* Relations */
+
@OneToMany(() => Project, project => project.admin)
projects: Project[]
diff --git a/apps/production/src/user/user.controller.ts b/apps/production/src/user/user.controller.ts
index c3fa92451..53a157a78 100644
--- a/apps/production/src/user/user.controller.ts
+++ b/apps/production/src/user/user.controller.ts
@@ -105,7 +105,7 @@ export class UserController {
relations: ['project'],
})
const user = this.userService.omitSensitiveData(
- await this.userService.findOneWhere({ id: user_id }),
+ await this.userService.findOne(user_id),
)
user.sharedProjects = sharedProjects
@@ -662,6 +662,9 @@ export class UserController {
'refCode',
'referrerID',
'maxProjects',
+ 'planExceedContactedAt',
+ 'dashboardBlockReason',
+ 'isAccountBillingSuspended',
])
await this.userService.update(id, userToUpdate)
@@ -796,6 +799,12 @@ export class UserController {
...user,
created: dayjs(user.created).format('YYYY/MM/DD HH:mm:ss'),
updated: dayjs(user.updated).format('YYYY/MM/DD HH:mm:ss'),
+ cancellationEffectiveDate: _isNull(user.cancellationEffectiveDate)
+ ? '-'
+ : dayjs(user.cancellationEffectiveDate).format('YYYY/MM/DD HH:mm:ss'),
+ planExceedContactedAt: _isNull(user.planExceedContactedAt)
+ ? '-'
+ : dayjs(user.planExceedContactedAt).format('YYYY/MM/DD HH:mm:ss'),
exportedAt: _isNull(user.exportedAt)
? '-'
: dayjs(user.exportedAt).format('YYYY/MM/DD HH:mm:ss'),
@@ -806,6 +815,11 @@ export class UserController {
subUpdateURL: user.subUpdateURL || '-',
subCancelURL: user.subCancelURL || '-',
telegramChatId: user.telegramChatId || '-',
+ dashboardBlockReason: user.dashboardBlockReason || '-',
+ refCode: user.refCode || '-',
+ referrerID: user.referrerID || '-',
+ paypalPaymentsEmail: user.paypalPaymentsEmail || '-',
+ tierCurrency: user.tierCurrency || '-',
nickname: user.nickname || '-',
},
projects: _map(projects, project => ({
diff --git a/apps/production/src/user/user.service.ts b/apps/production/src/user/user.service.ts
index fdd7268e3..c429267f2 100644
--- a/apps/production/src/user/user.service.ts
+++ b/apps/production/src/user/user.service.ts
@@ -161,8 +161,9 @@ export class UserService {
findOneWhere(
where: Record<string, unknown>,
relations: string[] = [],
+ select: any = [],
): Promise<User> {
- return this.usersRepository.findOne({ where, relations })
+ return this.usersRepository.findOne({ where, relations, select })
}
findOne(id: string, params: any = {}): Promise<User> {
diff --git a/apps/production/src/webhook/webhook.controller.ts b/apps/production/src/webhook/webhook.controller.ts
index 107d46322..bf8b408f0 100644
--- a/apps/production/src/webhook/webhook.controller.ts
+++ b/apps/production/src/webhook/webhook.controller.ts
@@ -13,14 +13,18 @@ import * as _find from 'lodash/find'
import { ProjectService } from '../project/project.service'
import { getIPFromHeaders } from '../common/utils'
+import { AFFILIATE_CUT } from '../common/constants'
import {
- PlanCode,
ACCOUNT_PLANS,
BillingFrequency,
+ DashboardBlockReason,
+ isNextPlan,
} from '../user/entities/user.entity'
import { UserService } from '../user/user.service'
import { AppLoggerService } from '../logger/logger.service'
import { WebhookService } from './webhook.service'
+import { LetterTemplate } from '../mailer/letter'
+import { MailerService } from '../mailer/mailer.service'
const MAX_PAYMENT_ATTEMPTS = 5
@@ -32,6 +36,7 @@ export class WebhookController {
private readonly userService: UserService,
private readonly webhookService: WebhookService,
private readonly projectService: ProjectService,
+ private readonly mailerService: MailerService,
) {}
@Post('/paddle')
@@ -85,6 +90,19 @@ export class WebhookController {
)
}
+ const currentUser = uid
+ ? await this.userService.findOne(uid)
+ : await this.userService.findOneWhere({ email })
+ const unlockDashboardParams =
+ body.alert_name === 'subscription_created' ||
+ isNextPlan(currentUser.planCode, plan.id)
+ ? {
+ dashboardBlockReason: null,
+ planExceedContactedAt: null,
+ isAccountBillingSuspended: false,
+ }
+ : {}
+
const updateParams = {
planCode: plan.id,
subID,
@@ -95,6 +113,8 @@ export class WebhookController {
? BillingFrequency.Monthly
: BillingFrequency.Yearly,
tierCurrency: currency,
+ cancellationEffectiveDate: null,
+ ...unlockDashboardParams,
}
if (uid) {
@@ -115,12 +135,22 @@ export class WebhookController {
} = body
await this.userService.updateBySubID(subID, {
- billingFrequency: BillingFrequency.Monthly,
nextBillDate: null,
cancellationEffectiveDate,
- tierCurrency: null,
})
+ const { email } =
+ (await this.userService.findOneWhere({
+ subID,
+ })) || {}
+
+ if (email) {
+ await this.mailerService.sendEmail(
+ email,
+ LetterTemplate.SubscriptionCancelled,
+ )
+ }
+
break
}
@@ -157,6 +187,16 @@ export class WebhookController {
return
}
+ if (
+ subscriber.dashboardBlockReason ===
+ DashboardBlockReason.payment_failed
+ ) {
+ await this.userService.updateBySubID(subID, {
+ dashboardBlockReason: null,
+ })
+ await this.projectService.clearProjectsRedisCacheBySubId(subID)
+ }
+
// That user was not referred by anyone
if (!subscriber.referrerID) {
return
@@ -181,7 +221,7 @@ export class WebhookController {
await this.webhookService.addPayoutForUser(
referrer,
subscriber.id,
- Number(balanceEarnings),
+ Number(balanceEarnings) * AFFILIATE_CUT,
balanceCurrency,
)
@@ -192,12 +232,33 @@ export class WebhookController {
const { subscription_id: subID, attempt_number: attemptNumber } = body
if (parseInt(attemptNumber, 10) >= MAX_PAYMENT_ATTEMPTS) {
+ const { email } =
+ (await this.userService.findOneWhere({
+ subID,
+ })) || {}
+
+ if (!email) {
+ this.logger.error(
+ `[subscription_payment_failed] Cannot find the subscriber with subID: ${subID}\nBody: ${JSON.stringify(
+ body,
+ null,
+ 2,
+ )}`,
+ )
+ return
+ }
+
await this.userService.updateBySubID(subID, {
- planCode: PlanCode.none,
- billingFrequency: BillingFrequency.Monthly,
- nextBillDate: null,
- tierCurrency: null,
+ dashboardBlockReason: DashboardBlockReason.payment_failed,
})
+
+ await this.mailerService.sendEmail(
+ email,
+ LetterTemplate.DashboardLockedPaymentFailure,
+ {
+ billingUrl: 'https://swetrix.com/billing',
+ },
+ )
}
break
diff --git a/apps/production/src/webhook/webhook.module.ts b/apps/production/src/webhook/webhook.module.ts
index 7e982b8f2..b8d8b6634 100644
--- a/apps/production/src/webhook/webhook.module.ts
+++ b/apps/production/src/webhook/webhook.module.ts
@@ -5,6 +5,7 @@ import { PayoutsModule } from '../payouts/payouts.module'
import { WebhookController } from './webhook.controller'
import { UserModule } from '../user/user.module'
import { AppLoggerModule } from '../logger/logger.module'
+import { MailerModule } from '../mailer/mailer.module'
import { WebhookService } from './webhook.service'
@Module({
@@ -13,6 +14,7 @@ import { WebhookService } from './webhook.service'
ProjectModule,
PayoutsModule,
AppLoggerModule,
+ MailerModule,
],
providers: [WebhookService],
exports: [WebhookService],
diff --git a/migrations/mysql/2024_02_16.sql b/migrations/mysql/2024_02_16.sql
new file mode 100644
index 000000000..b43ab5b8d
--- /dev/null
+++ b/migrations/mysql/2024_02_16.sql
@@ -0,0 +1,3 @@
+alter table user add column `planExceedContactedAt` timestamp NULL DEFAULT NULL AFTER `registeredWithGithub`;
+alter table user add column `dashboardBlockReason` enum('exceeding_plan_limits','trial_ended','payment_failed','subscription_cancelled') DEFAULT NULL AFTER `planExceedContactedAt`;
+alter table user add column `isAccountBillingSuspended` tinyint NOT NULL DEFAULT '0' AFTER `dashboardBlockReason`;