📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Address review comments
Blue Moused367b806a2c9
diff --git a/admin/src/commands/UsersCommand.tsx b/admin/src/commands/UsersCommand.tsxindex 8de73602a..e47cfbf71 100644--- a/admin/src/commands/UsersCommand.tsx+++ b/admin/src/commands/UsersCommand.tsx@@ -32,6 +32,9 @@ interface UserWithProjectCount extends User {projectCount?: number}+const numberValue = (source: Record<string, unknown> | null, key: string) =>+ source && typeof source[key] === 'number' ? (source[key] as number) : null+export function UsersCommand({ onBack, initialUser, showListOnBack = true }: UsersCommandProps) {const [mode, setMode] = useState<Mode>(initialUser ? 'detail' : 'list')const [loading, setLoading] = useState(false)@@ -215,6 +218,8 @@ export function UsersCommand({ onBack, initialUser, showListOnBack = true }: Use}async function handlePlanTypeSelect(item: { value: string }) {+ if (!selectedUser) return+const nextPlanType =item.value === 'clear' ? null : (item.value as PlanType)const update: Partial<User> = { planType: nextPlanType }@@ -222,7 +227,17 @@ export function UsersCommand({ onBack, initialUser, showListOnBack = true }: Useif (nextPlanType) {const entitlements = planEntitlements[nextPlanType]if (typeof entitlements.websites === 'number') {- update.maxProjects = entitlements.websites+ const purchasedWebsiteAddons =+ (selectedUser as User & { purchasedWebsiteAddons?: number })+ .purchasedWebsiteAddons ??+ numberValue(selectedUser.addonOverrides, 'websites') ??+ numberValue(selectedUser.addonOverrides, 'additionalWebsites') ??+ 0++ update.maxProjects = Math.max(+ entitlements.websites + purchasedWebsiteAddons,+ selectedUser.maxProjects || 0,+ )}if (typeof entitlements.apiRateLimitPerHour === 'number') {update.maxApiKeyRequestsPerHour = entitlements.apiRateLimitPerHour@@ -405,7 +420,7 @@ export function UsersCommand({ onBack, initialUser, showListOnBack = true }: Use{selectedUser.isActive ? 'Active' : 'Inactive'}</Text></Text>- <Text><Text color="cyan">Event Bucket:</Text> {selectedUser.planCode}</Text>+ <Text><Text color="cyan">Event Bucket:</Text> {effectiveLimits.eventBucket}</Text><Text><Text color="cyan">Plan Type:</Text> {selectedUser.planType || `${effectiveLimits.planType} fallback`}</Text><Text><Text color="cyan">Websites Included:</Text> {effectiveLimits.websitesIncluded}</Text><Text><Text color="cyan">Purchased Website Add-ons:</Text> {effectiveLimits.purchasedWebsiteAddons}</Text>diff --git a/admin/src/entities/user.entity.ts b/admin/src/entities/user.entity.tsindex 6b8fa8ca4..0e2a4fa63 100644--- a/admin/src/entities/user.entity.ts+++ b/admin/src/entities/user.entity.ts@@ -89,7 +89,7 @@ export class User {@Column('int', { default: 50 })maxProjects: number- @Column('int', { default: 600 })+ @Column('int', { default: 300 })maxApiKeyRequestsPerHour: number@Column({diff --git a/backend/apps/cloud/src/auth/guards/api-key-rate-limit.guard.ts b/backend/apps/cloud/src/auth/guards/api-key-rate-limit.guard.tsindex e4a9fde4b..1bd11be40 100644--- a/backend/apps/cloud/src/auth/guards/api-key-rate-limit.guard.ts+++ b/backend/apps/cloud/src/auth/guards/api-key-rate-limit.guard.ts@@ -6,6 +6,24 @@ import {PlanCode,} from '../../user/entities/user.entity'+const getNumericOverride = (+ overrides: Record<string, unknown> | null | undefined,+ key: string,+) => {+ const value = overrides?.[key]++ if (typeof value === 'number') {+ return Number.isFinite(value) ? value : null+ }++ if (typeof value === 'string' && value.trim()) {+ const parsed = Number(value)+ return Number.isFinite(parsed) ? parsed : null+ }++ return null+}+@Injectable()export class ApiKeyRateLimitGuard implements CanActivate {async canActivate(context: ExecutionContext) {@@ -19,15 +37,21 @@ export class ApiKeyRateLimitGuard implements CanActivate {const entitlements = effectivePlanType? getPlanTypeEntitlements(effectivePlanType): null- const planTypeLimit = entitlements?.apiRateLimitPerHour+ const overrideLimit = getNumericOverride(+ user.entitlementOverrides,+ 'apiRateLimitPerHour',+ )+ const planTypeLimit =+ overrideLimit ??+ (typeof entitlements?.apiRateLimitPerHour === 'number'+ ? entitlements.apiRateLimitPerHour+ : user.maxApiKeyRequestsPerHour)const reqAmount =user.planCode === PlanCode.none ||user.isAccountBillingSuspended ||user.dashboardBlockReason !== null? 0- : typeof planTypeLimit === 'number'- ? planTypeLimit- : user.maxApiKeyRequestsPerHour+ : planTypeLimitreturn checkRateLimitForApiKey(user.apiKey, reqAmount)}diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts b/backend/apps/cloud/src/feature-flag/feature-flag.controller.tsindex 90c932d21..106e45eff 100644--- a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts+++ b/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts@@ -528,7 +528,7 @@ export class FeatureFlagController {PlanFeatureCode.featureFlags,)) {- return { flags: {}, experiments: {} }+ return { flags: {} }}this.analyticsService.checkIpBlacklist(project, ip)diff --git a/backend/apps/cloud/src/user/dto/change-plan.dto.ts b/backend/apps/cloud/src/user/dto/change-plan.dto.tsindex eed8b87de..55380b84e 100644--- a/backend/apps/cloud/src/user/dto/change-plan.dto.ts+++ b/backend/apps/cloud/src/user/dto/change-plan.dto.ts@@ -1,7 +1,21 @@import { ApiProperty } from '@nestjs/swagger'-import { IsIn, IsNumber, IsOptional, IsString } from 'class-validator'+import { IsIn, IsNumber, IsOptional } from 'class-validator'const PLAN_TYPES = ['standard', 'plus', 'enterprise'] as const+const EVENT_TIERS = [+ '100k',+ '200k',+ '500k',+ '1m',+ '2m',+ '5m',+ '10m',+ '15m',+ '20m',+ '30m',+ '40m',+ '50m',+] as constexport class IChangePlanDTO {@ApiProperty({ example: 12345, required: true })@@ -13,8 +27,8 @@ export class IChangePlanDTO {@IsIn(PLAN_TYPES)planType?: string- @ApiProperty({ example: '100k', required: false })+ @ApiProperty({ example: '100k', required: false, enum: EVENT_TIERS })@IsOptional()- @IsString()+ @IsIn(EVENT_TIERS)eventTier?: string}diff --git a/backend/apps/cloud/src/user/entities/user-addon-charge.entity.ts b/backend/apps/cloud/src/user/entities/user-addon-charge.entity.tsindex fc3cbcf91..690112ab0 100644--- a/backend/apps/cloud/src/user/entities/user-addon-charge.entity.ts+++ b/backend/apps/cloud/src/user/entities/user-addon-charge.entity.ts@@ -26,6 +26,7 @@ export enum UserAddonChargeStatus {@Entity()@Index(['addonId', 'createdAt'])+@Index(['idempotencyKey'], { unique: true })export class UserAddonCharge {@PrimaryGeneratedColumn('uuid')id: string@@ -81,6 +82,9 @@ export class UserAddonCharge {@Column({ type: 'timestamp', nullable: true })periodEnd: Date | null+ @Column('varchar', { length: 191, nullable: true })+ idempotencyKey: string | null+@Column('int', { nullable: true })paddleInvoiceId: number | nulldiff --git a/backend/apps/cloud/src/user/entities/user-addon.entity.ts b/backend/apps/cloud/src/user/entities/user-addon.entity.tsindex af214fb8b..a52a7157b 100644--- a/backend/apps/cloud/src/user/entities/user-addon.entity.ts+++ b/backend/apps/cloud/src/user/entities/user-addon.entity.ts@@ -64,6 +64,9 @@ export class UserAddon {@Column('varchar', { length: 3, default: 'USD' })currency: string+ @Column('decimal', { precision: 10, scale: 2, nullable: true })+ recurringAmount: string | null+@Column({ type: 'timestamp', nullable: true })periodStart: Date | null@@ -89,6 +92,12 @@ export class UserAddon {@Column({ type: 'timestamp', nullable: true })cancelledAt: Date | null+ @Column('varchar', { length: 36, nullable: true })+ lastChargeId: string | null++ @Column({ type: 'timestamp', nullable: true })+ lastChargeAt: Date | null+@CreateDateColumn()createdAt: Datediff --git a/backend/apps/cloud/src/user/entities/user.entity.ts b/backend/apps/cloud/src/user/entities/user.entity.tsindex e2f681bd4..fbae41625 100644--- a/backend/apps/cloud/src/user/entities/user.entity.ts+++ b/backend/apps/cloud/src/user/entities/user.entity.ts@@ -113,18 +113,18 @@ export const getEffectivePlanType = (return null}- if (user.planType) {- return user.planType- }-if (- user.planCode &&- ![PlanCode.none, PlanCode.free, PlanCode.trial].includes(user.planCode)+ !user.planCode ||+ [PlanCode.none, PlanCode.free, PlanCode.trial].includes(user.planCode)) {- return PlanType.standard+ return null+ }++ if (user.planType) {+ return user.planType}- return null+ return PlanType.standard}export const getPlanTypeEntitlements = (planType?: PlanType | null) =>diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.tsindex 4b6e33502..1947c91dc 100644--- a/backend/apps/cloud/src/user/user.service.ts+++ b/backend/apps/cloud/src/user/user.service.ts@@ -6,6 +6,7 @@ import {} from '@nestjs/common'import { InjectRepository } from '@nestjs/typeorm'import {+ EntityManager,FindManyOptions,FindOneOptions,In,@@ -121,6 +122,7 @@ const FEEDBACK_ATTACHMENT_UPLOAD_TIMEOUT_MS = 10_000const WEBSITE_ADDON_BUNDLE_SIZE = 50const WEBSITE_ADDON_MAX_QUANTITY = 1000const WEBSITE_ADDON_RETRY_DELAY_HOURS = 6+const WEBSITE_ADDON_RENEWAL_CLAIM_MINUTES = 15const WEBSITE_ADDON_MAX_FAILED_CHARGES = 3const WEBSITE_ADDON_MONTHLY_PRICE: Record<string, number> = {USD: 7.5,@@ -169,6 +171,7 @@ interface WebsiteAddonSummary {status: UserAddonStatus | 'legacy' | nullperiodEnd: string | nullnextChargeDate: string | null+ recurringAmount: number | nullisLegacy: booleanfailedChargeAttempts: number}@@ -298,6 +301,51 @@ export class UserService {)}+ private getMoneyValue(value?: string | null): number | null {+ if (value === null || value === undefined) {+ return null+ }++ const amount = _toNumber(value)+ return Number.isFinite(amount) ? amount : null+ }++ private isDuplicateEntryError(reason: unknown): boolean {+ const error = reason as { code?: string; errno?: number }+ return error?.code === 'ER_DUP_ENTRY' || error?.errno === 1062+ }++ private getAddonChargeRepository(manager?: EntityManager) {+ return manager+ ? manager.getRepository(UserAddonCharge)+ : this.userAddonChargeRepository+ }++ private async getLockedUser(+ manager: EntityManager,+ userId: string,+ ): Promise<User | null> {+ return manager+ .getRepository(User)+ .createQueryBuilder('user')+ .setLock('pessimistic_write')+ .where('user.id = :userId', { userId })+ .getOne()+ }++ private async getLockedWebsiteAddon(+ manager: EntityManager,+ userId: string,+ ): Promise<UserAddon | null> {+ return manager+ .getRepository(UserAddon)+ .createQueryBuilder('addon')+ .setLock('pessimistic_write')+ .where('addon.userId = :userId', { userId })+ .andWhere('addon.code = :code', { code: UserAddonCode.websites })+ .getOne()+ }+private getIncludedWebsiteLimit(user: Partial<User>): number {const effectivePlanType = getEffectivePlanType(user)const entitlements = getPlanTypeEntitlements(effectivePlanType)@@ -581,6 +629,7 @@ export class UserService {private async syncWebsiteAddonEntitlements(user: User,quantity: number,+ manager?: EntityManager,): Promise<void> {const addonOverrides = { ...(user.addonOverrides || {}) }@@ -591,12 +640,19 @@ export class UserService {delete addonOverrides.additionalWebsites}- await this.update(user.id, {+ const update = {addonOverrides: Object.keys(addonOverrides).length? addonOverrides: null,maxProjects: this.getIncludedWebsiteLimit(user) + quantity,- })+ }++ if (manager) {+ await manager.getRepository(User).update(user.id, update)+ return+ }++ await this.update(user.id, update)}async refreshWebsiteAddonEntitlements(userId: string): Promise<void> {@@ -660,6 +716,32 @@ export class UserService {return data.response || {}}+ private buildWebsiteAddonChargeKey(+ addon: UserAddon,+ user: User,+ kind: UserAddonChargeKind,+ amount: number,+ quantity: number,+ previousQuantity: number | null,+ billingInterval: BillingFrequency,+ periodStart: Date | null,+ periodEnd: Date | null,+ ): string {+ return [+ 'website-addon',+ user.id,+ addon.id,+ kind,+ quantity,+ previousQuantity ?? 'none',+ billingInterval,+ amount.toFixed(2),+ addon.currency,+ periodStart ? dayjs.utc(periodStart).toISOString() : 'none',+ periodEnd ? dayjs.utc(periodEnd).toISOString() : 'none',+ ].join(':')+ }+private async chargeWebsiteAddon(addon: UserAddon,user: User,@@ -670,24 +752,91 @@ export class UserService {billingInterval: BillingFrequency,periodStart: Date | null,periodEnd: Date | null,- ): Promise<void> {+ manager?: EntityManager,+ ): Promise<UserAddonCharge> {+ const chargeRepository = this.getAddonChargeRepository(manager)const chargeName = `${quantity.toLocaleString()} additional websites for Swetrix (${billingInterval})`- const charge = await this.userAddonChargeRepository.save(- this.userAddonChargeRepository.create({- addonId: addon.id,- userId: user.id,- kind,- status: UserAddonChargeStatus.pending,- quantity,- previousQuantity,- billingInterval,- amount: amount.toFixed(2),- currency: addon.currency,- periodStart,- periodEnd,- }),+ const idempotencyKey = this.buildWebsiteAddonChargeKey(+ addon,+ user,+ kind,+ amount,+ quantity,+ previousQuantity,+ billingInterval,+ periodStart,+ periodEnd,)+ if (addon.lastChargeId) {+ const lastCharge = await chargeRepository.findOne({+ where: { id: addon.lastChargeId },+ })++ if (+ lastCharge?.idempotencyKey === idempotencyKey &&+ lastCharge.status === UserAddonChargeStatus.succeeded+ ) {+ return lastCharge+ }+ }++ let charge = await chargeRepository.findOne({+ where: { idempotencyKey },+ })++ if (charge?.status === UserAddonChargeStatus.succeeded) {+ return charge+ }++ if (charge?.status === UserAddonChargeStatus.pending) {+ throw new BadRequestException('websiteAddonChargeInProgress')+ }++ if (charge) {+ await chargeRepository.update(charge.id, {+ status: UserAddonChargeStatus.pending,+ failureReason: null,+ })+ } else {+ try {+ charge = await chargeRepository.save(+ chargeRepository.create({+ addonId: addon.id,+ userId: user.id,+ kind,+ status: UserAddonChargeStatus.pending,+ quantity,+ previousQuantity,+ billingInterval,+ amount: amount.toFixed(2),+ currency: addon.currency,+ periodStart,+ periodEnd,+ idempotencyKey,+ }),+ )+ } catch (reason) {+ if (!this.isDuplicateEntryError(reason)) {+ throw reason+ }++ charge = await chargeRepository.findOne({+ where: { idempotencyKey },+ })++ if (charge?.status === UserAddonChargeStatus.succeeded) {+ return charge+ }++ throw new BadRequestException('websiteAddonChargeInProgress')+ }+ }++ if (!charge) {+ throw new InternalServerErrorException('Unable to create add-on charge')+ }+try {const response = await this.createPaddleOneOffCharge(user.subID,@@ -695,7 +844,7 @@ export class UserService {chargeName,)- await this.userAddonChargeRepository.update(charge.id, {+ const update = {status: UserAddonChargeStatus.succeeded,paddleInvoiceId:typeof response.invoice_id === 'number' ? response.invoice_id : null,@@ -705,9 +854,17 @@ export class UserService {? String(response.receipt_url): null,paddleResponse: response,- })+ failureReason: null,+ }++ await chargeRepository.update(charge.id, update)++ return {+ ...charge,+ ...update,+ } as UserAddonCharge} catch (reason) {- await this.userAddonChargeRepository.update(charge.id, {+ await chargeRepository.update(charge.id, {status: UserAddonChargeStatus.failed,failureReason:reason instanceof Error ? reason.message : 'Paddle charge failed',@@ -737,6 +894,7 @@ export class UserService {status: addon.status,periodEnd: this.formatAddonDate(addon.periodEnd),nextChargeDate: this.formatAddonDate(addon.nextChargeDate),+ recurringAmount: this.getMoneyValue(addon.recurringAmount),isLegacy: false,failedChargeAttempts: addon.failedChargeAttempts,}@@ -760,6 +918,7 @@ export class UserService {status: 'legacy',periodEnd: null,nextChargeDate: null,+ recurringAmount: null,isLegacy: true,failedChargeAttempts: 0,}@@ -782,120 +941,145 @@ export class UserService {): Promise<Partial<User>> {this.validateWebsiteAddonSelection(quantity, billingInterval)- const user = await this.findOne({ where: { id: userId } })- if (!user) {- throw new BadRequestException('User not found')- }+ await this.usersRepository.manager.transaction(async (manager) => {+ const user = await this.getLockedUser(manager, userId)+ if (!user) {+ throw new BadRequestException('User not found')+ }- this.validateWebsiteAddonEligibility(user)+ this.validateWebsiteAddonEligibility(user)- let addon = await this.getWebsiteAddon(userId)- if (!addon && this.getAddonOverrideQuantity(user) > 0) {- throw new BadRequestException('legacyWebsiteAddon')- }+ const addonRepository = manager.getRepository(UserAddon)+ let addon = await this.getLockedWebsiteAddon(manager, userId)+ if (!addon && this.getAddonOverrideQuantity(user) > 0) {+ throw new BadRequestException('legacyWebsiteAddon')+ }- const preview = this.buildWebsiteAddonPreview(- user,- addon,- quantity,- billingInterval,- )+ const preview = this.buildWebsiteAddonPreview(+ user,+ addon,+ quantity,+ billingInterval,+ )- if (preview.changeType === 'none') {- if (- addon &&- (addon.pendingQuantity !== null ||- addon.pendingBillingInterval !== null)- ) {- await this.userAddonRepository.update(addon.id, {- pendingQuantity: null,- pendingBillingInterval: null,- })+ if (preview.changeType === 'none') {+ if (+ addon &&+ (addon.pendingQuantity !== null ||+ addon.pendingBillingInterval !== null)+ ) {+ await addonRepository.update(addon.id, {+ pendingQuantity: null,+ pendingBillingInterval: null,+ })+ }++ return}- return this.getUserWithWebsiteAddonSummary(userId)- }+ const now = new Date()++ if (!addon) {+ addon = await addonRepository.save(+ addonRepository.create({+ userId,+ code: UserAddonCode.websites,+ quantity: 0,+ billingInterval,+ currency: this.getWebsiteAddonCurrency(user),+ status: UserAddonStatus.cancelled,+ failedChargeAttempts: 0,+ }),+ )+ }- const now = new Date()+ const isInactiveAddon =+ addon.status === UserAddonStatus.cancelled ||+ (addon.status === UserAddonStatus.past_due && addon.quantity === 0)+ const currentQuantity = isInactiveAddon ? 0 : addon.quantity+ let charge: UserAddonCharge | null = null++ if (preview.dueNow > 0) {+ const chargePeriodStart = isInactiveAddon+ ? now+ : addon.periodStart || now+ const chargePeriodEnd = isInactiveAddon+ ? this.getWebsiteAddonPeriodEnd(now, billingInterval)+ : addon.periodEnd ||+ this.getWebsiteAddonPeriodEnd(now, addon.billingInterval)++ charge = await this.chargeWebsiteAddon(+ addon,+ user,+ isInactiveAddon+ ? UserAddonChargeKind.initial+ : UserAddonChargeKind.prorated,+ preview.dueNow,+ quantity,+ currentQuantity,+ isInactiveAddon ? billingInterval : addon.billingInterval,+ chargePeriodStart,+ chargePeriodEnd,+ manager,+ )+ }- if (!addon) {- addon = await this.userAddonRepository.save(- this.userAddonRepository.create({- userId,- code: UserAddonCode.websites,- quantity: 0,+ if (isInactiveAddon) {+ const periodEnd = this.getWebsiteAddonPeriodEnd(now, billingInterval)+ const recurringAmount = this.getWebsiteAddonAmount(+ quantity,billingInterval,- currency: this.getWebsiteAddonCurrency(user),- status: UserAddonStatus.cancelled,- failedChargeAttempts: 0,- }),- )- }-- const isInactiveAddon =- addon.status === UserAddonStatus.cancelled ||- (addon.status === UserAddonStatus.past_due && addon.quantity === 0)- const currentQuantity = isInactiveAddon ? 0 : addon.quantity-- if (preview.dueNow > 0) {- const chargePeriodStart = isInactiveAddon ? now : addon.periodStart || now- const chargePeriodEnd = isInactiveAddon- ? this.getWebsiteAddonPeriodEnd(now, billingInterval)- : addon.periodEnd ||- this.getWebsiteAddonPeriodEnd(now, addon.billingInterval)-- await this.chargeWebsiteAddon(- addon,- user,- isInactiveAddon- ? UserAddonChargeKind.initial- : UserAddonChargeKind.prorated,- preview.dueNow,- quantity,- currentQuantity,- isInactiveAddon ? billingInterval : addon.billingInterval,- chargePeriodStart,- chargePeriodEnd,- )- }+ preview.currency,+ )- if (isInactiveAddon) {- const periodEnd = this.getWebsiteAddonPeriodEnd(now, billingInterval)+ await addonRepository.update(addon.id, {+ quantity,+ pendingQuantity: null,+ billingInterval,+ pendingBillingInterval: null,+ currency: preview.currency,+ recurringAmount: recurringAmount.toFixed(2),+ periodStart: now,+ periodEnd,+ nextChargeDate: periodEnd,+ status: UserAddonStatus.active,+ failedChargeAttempts: 0,+ lastChargeFailedAt: null,+ cancelledAt: null,+ lastChargeId: charge?.id || addon.lastChargeId,+ lastChargeAt: charge ? now : addon.lastChargeAt,+ })+ await this.syncWebsiteAddonEntitlements(user, quantity, manager)+ } else if (quantity > currentQuantity) {+ const activeBillingInterval = addon.billingInterval+ const recurringAmount = this.getWebsiteAddonAmount(+ quantity,+ activeBillingInterval,+ preview.currency,+ )- await this.userAddonRepository.update(addon.id, {- quantity,- pendingQuantity: null,- billingInterval,- pendingBillingInterval: null,- currency: preview.currency,- periodStart: now,- periodEnd,- nextChargeDate: periodEnd,- status: UserAddonStatus.active,- failedChargeAttempts: 0,- lastChargeFailedAt: null,- cancelledAt: null,- })- await this.syncWebsiteAddonEntitlements(user, quantity)- } else if (quantity > currentQuantity) {- await this.userAddonRepository.update(addon.id, {- quantity,- pendingQuantity: null,- pendingBillingInterval:- billingInterval !== addon.billingInterval ? billingInterval : null,- status: UserAddonStatus.active,- failedChargeAttempts: 0,- lastChargeFailedAt: null,- })- await this.syncWebsiteAddonEntitlements(user, quantity)- } else {- await this.userAddonRepository.update(addon.id, {- pendingQuantity: quantity !== currentQuantity ? quantity : null,- pendingBillingInterval:- billingInterval !== addon.billingInterval ? billingInterval : null,- status: UserAddonStatus.active,- })- }+ await addonRepository.update(addon.id, {+ quantity,+ pendingQuantity: null,+ pendingBillingInterval:+ billingInterval !== addon.billingInterval ? billingInterval : null,+ recurringAmount: recurringAmount.toFixed(2),+ status: UserAddonStatus.active,+ failedChargeAttempts: 0,+ lastChargeFailedAt: null,+ lastChargeId: charge?.id || addon.lastChargeId,+ lastChargeAt: charge ? now : addon.lastChargeAt,+ })+ await this.syncWebsiteAddonEntitlements(user, quantity, manager)+ } else {+ await addonRepository.update(addon.id, {+ pendingQuantity: quantity !== currentQuantity ? quantity : null,+ pendingBillingInterval:+ billingInterval !== addon.billingInterval ? billingInterval : null,+ status: UserAddonStatus.active,+ })+ }+ })return this.getUserWithWebsiteAddonSummary(userId)}@@ -905,6 +1089,7 @@ export class UserService {quantity: 0,pendingQuantity: null,pendingBillingInterval: null,+ recurringAmount: null,nextChargeDate: null,status: UserAddonStatus.cancelled,failedChargeAttempts: 0,@@ -976,6 +1161,7 @@ export class UserService {? null: dayjs.utc().add(WEBSITE_ADDON_RETRY_DELAY_HOURS, 'hour').toDate(),quantity: shouldRemoveCapacity ? 0 : addon.quantity,+ recurringAmount: shouldRemoveCapacity ? null : addon.recurringAmount,pendingQuantity: shouldRemoveCapacity ? null : addon.pendingQuantity,pendingBillingInterval: shouldRemoveCapacity? null@@ -994,6 +1180,33 @@ export class UserService {}private async processWebsiteAddonRenewal(addon: UserAddon): Promise<void> {+ const claimStartedAt = new Date()+ const dueDate = addon.nextChargeDate++ if (!dueDate || dayjs.utc(dueDate).isAfter(dayjs.utc(claimStartedAt))) {+ return+ }++ const claimUntil = dayjs+ .utc(claimStartedAt)+ .add(WEBSITE_ADDON_RENEWAL_CLAIM_MINUTES, 'minute')+ .toDate()+ const claimResult = await this.userAddonRepository.update(+ {+ id: addon.id,+ code: UserAddonCode.websites,+ status: addon.status,+ nextChargeDate: LessThan(claimStartedAt),+ },+ {+ nextChargeDate: claimUntil,+ },+ )++ if (!claimResult.affected) {+ return+ }+const user = addon.userif (!user || !user.subID || user.cancellationEffectiveDate) {@@ -1010,7 +1223,7 @@ export class UserService {return}- const periodStart = new Date()+ const periodStart = dueDateconst periodEnd = this.getWebsiteAddonPeriodEnd(periodStart,targetBillingInterval,@@ -1022,7 +1235,7 @@ export class UserService {)try {- await this.chargeWebsiteAddon(+ const charge = await this.chargeWebsiteAddon(addon,user,UserAddonChargeKind.renewal,@@ -1033,18 +1246,26 @@ export class UserService {periodStart,periodEnd,)+ const recurringAmount = this.getWebsiteAddonAmount(+ targetQuantity,+ targetBillingInterval,+ addon.currency,+ )await this.userAddonRepository.update(addon.id, {quantity: targetQuantity,pendingQuantity: null,billingInterval: targetBillingInterval,pendingBillingInterval: null,+ recurringAmount: recurringAmount.toFixed(2),periodStart,periodEnd,nextChargeDate: periodEnd,status: UserAddonStatus.active,failedChargeAttempts: 0,lastChargeFailedAt: null,+ lastChargeId: charge.id,+ lastChargeAt: new Date(),})await this.syncWebsiteAddonEntitlements(user, targetQuantity)} catch (reason) {diff --git a/backend/apps/cloud/src/webhook/webhook.controller.ts b/backend/apps/cloud/src/webhook/webhook.controller.tsindex 245e5c02d..e6df53c09 100644--- a/backend/apps/cloud/src/webhook/webhook.controller.ts+++ b/backend/apps/cloud/src/webhook/webhook.controller.ts@@ -170,7 +170,8 @@ export class WebhookController {}: {}- const planType = requestedPlanType || PlanType.standard+ const planType =+ requestedPlanType || currentUser.planType || PlanType.standardconst updateParams: Record<string, any> = {planCode: plan.id,planType,diff --git a/backend/migrations/mysql/2026_06_02_user_addon_charge_guards.sql b/backend/migrations/mysql/2026_06_02_user_addon_charge_guards.sqlnew file mode 100644index 000000000..858fc550b--- /dev/null+++ b/backend/migrations/mysql/2026_06_02_user_addon_charge_guards.sql@@ -0,0 +1,25 @@+ALTER TABLE `user_addon`+ ADD COLUMN `recurringAmount` decimal(10,2) DEFAULT NULL AFTER `currency`,+ ADD COLUMN `lastChargeId` varchar(36) DEFAULT NULL AFTER `cancelledAt`,+ ADD COLUMN `lastChargeAt` timestamp NULL DEFAULT NULL AFTER `lastChargeId`;++UPDATE `user_addon`+SET `recurringAmount` = ROUND(+ (`quantity` / 50) *+ CASE `currency`+ WHEN 'EUR' THEN 7+ WHEN 'GBP' THEN 6+ ELSE 7.5+ END *+ CASE `billingInterval`+ WHEN 'yearly' THEN 10+ ELSE 1+ END,+ 2+)+WHERE `quantity` > 0+ AND `status` <> 'cancelled';++ALTER TABLE `user_addon_charge`+ ADD COLUMN `idempotencyKey` varchar(191) DEFAULT NULL AFTER `periodEnd`,+ ADD UNIQUE KEY `IDX_user_addon_charge_idempotency` (`idempotencyKey`);diff --git a/docs/content/docs/billing/update-subscription.mdx b/docs/content/docs/billing/update-subscription.mdxindex b73aa386d..cfb11f458 100644--- a/docs/content/docs/billing/update-subscription.mdx+++ b/docs/content/docs/billing/update-subscription.mdx@@ -11,9 +11,9 @@ Click **Manage plan** or **Choose a plan** to open the plan selection page.On the plan selection page:-1. Choose the monthly event volume you need.-2. Choose a plan type: **Standard**, **Plus**, or **Enterprise**.-3. Choose monthly or yearly billing.+1. Select the monthly event volume you need.+2. Pick a plan type: **Standard**, **Plus**, or **Enterprise**.+3. Opt for monthly or yearly billing.Standard and Plus plans can be changed through self-serve checkout. Enterprise plans require contacting us because the limits and terms are custom.diff --git a/web/app/components/pricing/MarketingPricing.tsx b/web/app/components/pricing/MarketingPricing.tsxindex 8474df412..e304535cb 100644--- a/web/app/components/pricing/MarketingPricing.tsx+++ b/web/app/components/pricing/MarketingPricing.tsx@@ -287,7 +287,9 @@ export const PricingInternal = ({const [billingFrequency, setBillingFrequency] =useState<BillingInterval>('monthly')const [selectedTierIndex, setSelectedTierIndex] = useState(0)- const [showAllBenefits, setShowAllBenefits] = useState(false)+ const [expandedBenefitsByPlan, setExpandedBenefitsByPlan] = useState<+ Partial<Record<PlanTypeCode, boolean>>+ >({})const currencyCode = (metainfo.code in CURRENCIES ? metainfo.code : 'USD'@@ -408,6 +410,7 @@ export const PricingInternal = ({{planCards.map((planType) => {const isEnterprise = planType === 'enterprise'const benefits = getBenefits(planType, t)+ const showAllBenefits = !!expandedBenefitsByPlan[planType]const visibleBenefits = showAllBenefits? benefits: benefits.slice(0, visibleBenefitsCount)@@ -589,7 +592,12 @@ export const PricingInternal = ({{hiddenBenefitsCount > 0 || showAllBenefits ? (<buttontype='button'- onClick={() => setShowAllBenefits((value) => !value)}+ onClick={() =>+ setExpandedBenefitsByPlan((current) => ({+ ...current,+ [planType]: !current[planType],+ }))+ }className='underline-animate flex items-center gap-2.5'>{showAllBenefits ? (diff --git a/web/app/lib/models/User.ts b/web/app/lib/models/User.tsindex 6954f6406..443f36c58 100644--- a/web/app/lib/models/User.ts+++ b/web/app/lib/models/User.ts@@ -45,6 +45,7 @@ interface WebsiteAddon {status: 'active' | 'past_due' | 'cancelled' | 'legacy' | nullperiodEnd: string | nullnextChargeDate: string | null+ recurringAmount: number | nullisLegacy: booleanfailedChargeAttempts: number}diff --git a/web/app/lib/pricing/catalog.ts b/web/app/lib/pricing/catalog.tsindex a291c0af2..66b95e31b 100644--- a/web/app/lib/pricing/catalog.ts+++ b/web/app/lib/pricing/catalog.ts@@ -113,6 +113,15 @@ export const EVENT_TIERS = {export const EVENT_TIER_CODES = Object.keys(EVENT_TIERS) as EventTierCode[]export const SELF_SERVE_PLAN_TYPES: PlanTypeCode[] = ['standard', 'plus']+const isProduction = () =>+ typeof window === 'undefined'+ ? process.env.NODE_ENV === 'production'+ : window.REMIX_ENV?.NODE_ENV === 'production'++/**+ * Paddle receives one product_id per billing interval; USD/EUR/GBP share it and+ * rely on Paddle localized pricing/overrides for country and locale checkout.+ */const price = (monthly: Record<CurrencyCode, number>,yearly: Record<CurrencyCode, number>,@@ -131,6 +140,31 @@ const price = (},})+const assertCatalogPrice = (+ eventTierCode: EventTierCode,+ billingInterval: BillingInterval,+ currencyCode: CurrencyCode,+ planPrice: PlanPrice | undefined,+): PlanPrice => {+ if (+ planPrice &&+ typeof planPrice.amount === 'number' &&+ Number.isFinite(planPrice.amount) &&+ planPrice.paddlePlanId+ ) {+ return planPrice+ }++ const message = `Missing PLAN_PRICES.standard.${eventTierCode}.${billingInterval}.${currencyCode} amount or paddlePlanId`++ if (!isProduction()) {+ throw new Error(message)+ }++ console.warn(message)+ return { amount: 0, paddlePlanId: null }+}+const PLAN_PRICES: PlanPriceCatalog = {standard: {'100k': price(@@ -483,6 +517,42 @@ const createPlanLimit = (const tier = EVENT_TIERS[eventTierCode]const monthly = PLAN_PRICES.standard[eventTierCode]?.monthlyconst yearly = PLAN_PRICES.standard[eventTierCode]?.yearly+ const monthlyUsd = assertCatalogPrice(+ eventTierCode,+ 'monthly',+ 'USD',+ monthly?.USD,+ )+ const monthlyEur = assertCatalogPrice(+ eventTierCode,+ 'monthly',+ 'EUR',+ monthly?.EUR,+ )+ const monthlyGbp = assertCatalogPrice(+ eventTierCode,+ 'monthly',+ 'GBP',+ monthly?.GBP,+ )+ const yearlyUsd = assertCatalogPrice(+ eventTierCode,+ 'yearly',+ 'USD',+ yearly?.USD,+ )+ const yearlyEur = assertCatalogPrice(+ eventTierCode,+ 'yearly',+ 'EUR',+ yearly?.EUR,+ )+ const yearlyGbp = assertCatalogPrice(+ eventTierCode,+ 'yearly',+ 'GBP',+ yearly?.GBP,+ )return {index,@@ -491,20 +561,20 @@ const createPlanLimit = (legacy: false,price: {USD: {- monthly: monthly?.USD.amount ?? 0,- yearly: yearly?.USD.amount ?? 0,+ monthly: monthlyUsd.amount,+ yearly: yearlyUsd.amount,},EUR: {- monthly: monthly?.EUR.amount ?? 0,- yearly: yearly?.EUR.amount ?? 0,+ monthly: monthlyEur.amount,+ yearly: yearlyEur.amount,},GBP: {- monthly: monthly?.GBP.amount ?? 0,- yearly: yearly?.GBP.amount ?? 0,+ monthly: monthlyGbp.amount,+ yearly: yearlyGbp.amount,},},- ...(monthly?.USD.paddlePlanId ? { pid: monthly.USD.paddlePlanId } : {}),- ...(yearly?.USD.paddlePlanId ? { ypid: yearly.USD.paddlePlanId } : {}),+ ...(monthlyUsd.paddlePlanId ? { pid: monthlyUsd.paddlePlanId } : {}),+ ...(yearlyUsd.paddlePlanId ? { ypid: yearlyUsd.paddlePlanId } : {}),maxAlerts: 50,}}@@ -520,21 +590,14 @@ export const PLAN_LIMITS = {),} as Record<PlanCode, PlanLimit>-const isPaidPlanCode = (planCode?: string | null) =>- !!planCode && !['none', 'free', 'trial'].includes(planCode)-export const getEffectivePlanType = (planType?: string | null,- planCode?: string | null,+ _planCode?: string | null,): PlanTypeCode => {if (planType && planType in PLAN_TYPES) {return planType as PlanTypeCode}- if (isPaidPlanCode(planCode)) {- return 'standard'- }-return 'standard'}@@ -549,9 +612,7 @@ export const getPlanPrice = (billingInterval: BillingInterval,currencyCode: CurrencyCode,) =>- PLAN_PRICES[planType]?.[eventTier]?.[billingInterval]?.[currencyCode] ??- PLAN_PRICES[planType]?.[eventTier]?.[billingInterval]?.USD ??- null+ PLAN_PRICES[planType]?.[eventTier]?.[billingInterval]?.[currencyCode] ?? nullexport const getPlanMonthlyPrice = (planType: PlanTypeCode,diff --git a/web/app/pages/Project/View/components/PlanFeatureLocked.tsx b/web/app/pages/Project/View/components/PlanFeatureLocked.tsxindex f0c2bc087..a421d5318 100644--- a/web/app/pages/Project/View/components/PlanFeatureLocked.tsx+++ b/web/app/pages/Project/View/components/PlanFeatureLocked.tsx@@ -11,11 +11,18 @@ interface PlanFeatureLockedProps {feature: PlanFeatureCode}+const allowedFeatures = ['featureFlags', 'experiments'] as const+const PlanFeatureLocked = ({ feature }: PlanFeatureLockedProps) => {const { t } = useTranslation('common')- const { isOwner } = useProjectFeatureAccess(feature)+ const safeFeature = allowedFeatures.includes(feature) ? feature : null+ const { isOwner } = useProjectFeatureAccess(safeFeature || 'featureFlags')const audience = isOwner ? 'owner' : 'viewer'+ if (!safeFeature) {+ return null+ }+return (<div className='mx-auto w-full max-w-2xl py-16 text-center'><div className='mx-auto mb-6 flex size-14 items-center justify-center rounded-xl bg-gray-100 dark:bg-slate-900'>@@ -25,7 +32,7 @@ const PlanFeatureLocked = ({ feature }: PlanFeatureLockedProps) => {/></div><Text as='h3' size='xl' weight='medium' tracking='tight'>- {t(`project.featureAccess.${feature}.${audience}Title`)}+ {t(`project.featureAccess.${safeFeature}.${audience}Title`)}</Text><Textas='p'diff --git a/web/app/pages/Subscribe/Subscribe.tsx b/web/app/pages/Subscribe/Subscribe.tsxindex 7aa5a8035..012872c58 100644--- a/web/app/pages/Subscribe/Subscribe.tsx+++ b/web/app/pages/Subscribe/Subscribe.tsx@@ -240,7 +240,18 @@ const Subscribe = () => {new Date(Date.now() + TRIAL_DAYS * 24 * 60 * 60 * 1000),)- const dueEndAmount = selectedPrice?.amount ?? 0+ const formatMonthlyPriceLabel = (amount: number | null) =>+ amount === null+ ? t('pricing.custom')+ : `${currency.symbol}${formatPrice(amount)}/${t('pricing.perMonth')}`+ const formatSelectedPriceLabel = (amount: number | null | undefined) =>+ amount === null || amount === undefined+ ? t('pricing.custom')+ : `${currency.symbol}${formatPrice(amount)}/${+ selectedBillingFrequency === 'yearly'+ ? t('pricing.perYear')+ : t('pricing.perMonth')+ }`const faqItems = useMemo(() => {const faqValues = {@@ -359,8 +370,7 @@ const Subscribe = () => {colour='secondary'className='mt-3 block'>- {currency.symbol}- {formatPrice(price)}/{t('pricing.perMonth')}+ {formatMonthlyPriceLabel(price)}</Text><Textas='span'@@ -413,8 +423,7 @@ const Subscribe = () => {{formatEventsLong(tier.monthlyEvents, i18n.language)}</Text><Text as='span' size='sm' colour='secondary'>- {currency.symbol}- {formatPrice(price)}/{t('pricing.perMonth')}+ {formatMonthlyPriceLabel(price)}</Text></button>)@@ -457,11 +466,17 @@ const Subscribe = () => {</Text></div><Text as='p' size='2xl' weight='bold'>- {currency.symbol}- {formatPrice(monthlyPrice)}- <Text as='span' size='sm' colour='secondary' weight='medium'>- /{t('pricing.perMonth')}- </Text>+ {monthlyPrice === null ? (+ t('pricing.custom')+ ) : (+ <>+ {currency.symbol}+ {formatPrice(monthlyPrice)}+ <Text as='span' size='sm' colour='secondary' weight='medium'>+ /{t('pricing.perMonth')}+ </Text>+ </>+ )}</Text></div></div>@@ -485,11 +500,7 @@ const Subscribe = () => {{t('checkout.dueEnd', { date: formattedEndDate })}</Text><Text as='p' size='base'>- {currency.symbol}- {formatPrice(dueEndAmount)}- {selectedBillingFrequency === 'yearly'- ? `/${t('pricing.perYear')}`- : `/${t('pricing.perMonth')}`}+ {formatSelectedPriceLabel(selectedPrice?.amount)}</Text></div></div>diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsxindex 23460a3a5..0dcd35747 100644--- a/web/app/pages/UserSettings/UserSettings.tsx+++ b/web/app/pages/UserSettings/UserSettings.tsx@@ -575,14 +575,14 @@ const UserSettings = () => {(websiteAddon?.pendingQuantity ?? null) !== null ||(websiteAddon?.pendingBillingInterval ?? null) !== nullconst websiteAddonDisabledReason = useMemo(() => {- if (!isSubscriber) {- return t('billing.websiteAddonRequiresSubscription')- }-if (isTrial) {return t('billing.websiteAddonUnavailableDuringTrial')}+ if (!isSubscriber) {+ return t('billing.websiteAddonRequiresSubscription')+ }+if (cancellationEffectiveDate) {return t('billing.websiteAddonUnavailableCancelled')}@@ -648,9 +648,7 @@ const UserSettings = () => {// monthly subscribers can still buy the add-on, billed monthly.const canSelectYearlyWebsiteAddon = user?.billingFrequency === 'yearly'const activeWebsiteAddonRecurringAmount =- websiteAddonPrice *- (activeWebsiteAddonQuantity / websiteAddonBundle.quantity) *- (currentWebsiteAddonBillingInterval === 'yearly' ? 10 : 1)+ websiteAddon?.recurringAmount ?? nullconst formatBillingDate = useCallback((date?: string | null) => {@@ -1971,10 +1969,10 @@ const UserSettings = () => {colour='secondary'className='mt-1'>- {purchasedWebsiteAddons+ {activeWebsiteAddonQuantity? t('billing.addedWebsites', {amount:- purchasedWebsiteAddons.toLocaleString(),+ activeWebsiteAddonQuantity.toLocaleString(),}): t('billing.websitesIncludedCaption')}</Text>@@ -2197,7 +2195,8 @@ const UserSettings = () => {</div></div>- {activeWebsiteAddonQuantity > 0 ? (+ {activeWebsiteAddonQuantity > 0 &&+ activeWebsiteAddonRecurringAmount !== null ? (<Textas='p'size='sm'diff --git a/web/app/routes/_index.tsx b/web/app/routes/_index.tsxindex 5634d1d0b..ef6f9e7f7 100644--- a/web/app/routes/_index.tsx+++ b/web/app/routes/_index.tsx@@ -558,7 +558,7 @@ const NewHero = ({ stats }: { stats: Stats | null }) => {}}variant='secondary'size='xl'- className='h-12 items-center border-white/25 bg-white/10 px-5 text-center text-base font-semibold text-white shadow-none ring-white/25 backdrop-blur-md hover:bg-white/20 dark:border-white/25 dark:bg-white/10 dark:text-white dark:hover:bg-white/20'+ className='h-12 border-white/25 bg-white/10 px-5 text-center text-base font-semibold text-white shadow-none ring-white/25 backdrop-blur-md hover:bg-white/20 dark:border-white/25 dark:bg-white/10 dark:text-white dark:hover:bg-white/20'aria-label={`${t('main.seeLiveDemo')} (opens in a new tab)`}>{t('common.liveDemo')}