📈 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
User addons
Blue Mousef4af8e940cc4
diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.tsindex eee920f76..4c71c8497 100644--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts@@ -1447,6 +1447,15 @@ export class TaskManagerService {})}+ @Cron(CronExpression.EVERY_HOUR)+ async processWebsiteAddonRenewals() {+ await this.userService.processDueWebsiteAddonRenewals().catch((reason) => {+ this.logger.error(+ `[CRON WORKER](processWebsiteAddonRenewals) Error occured: ${reason}`,+ )+ })+ }+@Cron(CronExpression.EVERY_2_HOURS)async cleanUpUnpaidSubUsers() {const users = await this.userService.find({@@ -1461,6 +1470,9 @@ export class TaskManagerService {const now = new Date()if (now > cancellationEffectiveDate) {+ await this.userService.clearWebsiteAddonsForCancelledSubscription(+ user.id,+ )await this.userService.update(user.id, {cancellationEffectiveDate: null,planCode: PlanCode.none,diff --git a/backend/apps/cloud/src/user/dto/update-website-addon.dto.ts b/backend/apps/cloud/src/user/dto/update-website-addon.dto.tsnew file mode 100644index 000000000..92fe24dd1--- /dev/null+++ b/backend/apps/cloud/src/user/dto/update-website-addon.dto.ts@@ -0,0 +1,16 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsIn, IsInt, Max, Min } from 'class-validator'++import { BillingFrequency } from '../entities/user.entity'++export class UpdateWebsiteAddonDTO {+ @ApiProperty({ example: 100, minimum: 0, maximum: 1000 })+ @IsInt()+ @Min(0)+ @Max(1000)+ quantity: number++ @ApiProperty({ example: BillingFrequency.Monthly, enum: BillingFrequency })+ @IsIn([BillingFrequency.Monthly, BillingFrequency.Yearly])+ billingInterval: BillingFrequency+}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.tsnew file mode 100644index 000000000..fc3cbcf91--- /dev/null+++ b/backend/apps/cloud/src/user/entities/user-addon-charge.entity.ts@@ -0,0 +1,107 @@+import {+ Column,+ CreateDateColumn,+ Entity,+ Index,+ JoinColumn,+ ManyToOne,+ PrimaryGeneratedColumn,+ UpdateDateColumn,+} from 'typeorm'++import { BillingFrequency, User } from './user.entity'+import { UserAddon } from './user-addon.entity'++export enum UserAddonChargeKind {+ initial = 'initial',+ prorated = 'prorated',+ renewal = 'renewal',+}++export enum UserAddonChargeStatus {+ pending = 'pending',+ succeeded = 'succeeded',+ failed = 'failed',+}++@Entity()+@Index(['addonId', 'createdAt'])+export class UserAddonCharge {+ @PrimaryGeneratedColumn('uuid')+ id: string++ @Column('varchar', { length: 36 })+ addonId: string++ @ManyToOne(() => UserAddon, { onDelete: 'CASCADE' })+ @JoinColumn({ name: 'addonId' })+ addon: UserAddon++ @Column('varchar', { length: 36 })+ userId: string++ @ManyToOne(() => User, { onDelete: 'CASCADE' })+ @JoinColumn({ name: 'userId' })+ user: User++ @Column({+ type: 'enum',+ enum: UserAddonChargeKind,+ })+ kind: UserAddonChargeKind++ @Column({+ type: 'enum',+ enum: UserAddonChargeStatus,+ default: UserAddonChargeStatus.pending,+ })+ status: UserAddonChargeStatus++ @Column('int')+ quantity: number++ @Column('int', { nullable: true })+ previousQuantity: number | null++ @Column({+ type: 'enum',+ enum: BillingFrequency,+ })+ billingInterval: BillingFrequency++ @Column('decimal', { precision: 10, scale: 2 })+ amount: string++ @Column('varchar', { length: 3 })+ currency: string++ @Column({ type: 'timestamp', nullable: true })+ periodStart: Date | null++ @Column({ type: 'timestamp', nullable: true })+ periodEnd: Date | null++ @Column('int', { nullable: true })+ paddleInvoiceId: number | null++ @Column('varchar', { length: 80, nullable: true })+ paddleOrderId: string | null++ @Column('varchar', { length: 80, nullable: true })+ paddleStatus: string | null++ @Column('varchar', { length: 300, nullable: true })+ paddleReceiptUrl: string | null++ @Column({ type: 'json', nullable: true })+ paddleResponse: Record<string, unknown> | null++ @Column('text', { nullable: true })+ failureReason: string | null++ @CreateDateColumn()+ createdAt: Date++ @UpdateDateColumn()+ updatedAt: Date+}diff --git a/backend/apps/cloud/src/user/entities/user-addon.entity.ts b/backend/apps/cloud/src/user/entities/user-addon.entity.tsnew file mode 100644index 000000000..af214fb8b--- /dev/null+++ b/backend/apps/cloud/src/user/entities/user-addon.entity.ts@@ -0,0 +1,97 @@+import {+ Column,+ CreateDateColumn,+ Entity,+ Index,+ JoinColumn,+ ManyToOne,+ PrimaryGeneratedColumn,+ UpdateDateColumn,+} from 'typeorm'++import { User, BillingFrequency } from './user.entity'++export enum UserAddonCode {+ websites = 'websites',+}++export enum UserAddonStatus {+ active = 'active',+ past_due = 'past_due',+ cancelled = 'cancelled',+}++@Entity()+@Index(['userId', 'code'], { unique: true })+@Index(['nextChargeDate', 'status'])+export class UserAddon {+ @PrimaryGeneratedColumn('uuid')+ id: string++ @Column('varchar', { length: 36 })+ userId: string++ @ManyToOne(() => User, { onDelete: 'CASCADE' })+ @JoinColumn({ name: 'userId' })+ user: User++ @Column({+ type: 'enum',+ enum: UserAddonCode,+ })+ code: UserAddonCode++ @Column('int', { default: 0 })+ quantity: number++ @Column('int', { nullable: true })+ pendingQuantity: number | null++ @Column({+ type: 'enum',+ enum: BillingFrequency,+ default: BillingFrequency.Monthly,+ })+ billingInterval: BillingFrequency++ @Column({+ type: 'enum',+ enum: BillingFrequency,+ nullable: true,+ })+ pendingBillingInterval: BillingFrequency | null++ @Column('varchar', { length: 3, default: 'USD' })+ currency: string++ @Column({ type: 'timestamp', nullable: true })+ periodStart: Date | null++ @Column({ type: 'timestamp', nullable: true })+ periodEnd: Date | null++ @Column({ type: 'timestamp', nullable: true })+ nextChargeDate: Date | null++ @Column({+ type: 'enum',+ enum: UserAddonStatus,+ default: UserAddonStatus.active,+ })+ status: UserAddonStatus++ @Column('int', { default: 0 })+ failedChargeAttempts: number++ @Column({ type: 'timestamp', nullable: true })+ lastChargeFailedAt: Date | null++ @Column({ type: 'timestamp', nullable: true })+ cancelledAt: Date | null++ @CreateDateColumn()+ createdAt: Date++ @UpdateDateColumn()+ updatedAt: Date+}diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.tsindex a442adc0f..dd6639898 100644--- a/backend/apps/cloud/src/user/user.controller.ts+++ b/backend/apps/cloud/src/user/user.controller.ts@@ -65,6 +65,7 @@ import { AppLoggerService } from '../logger/logger.service'import { DeleteSelfDTO } from './dto/delete-self.dto'import { CancelSubscriptionDTO } from './dto/cancel-subscription.dto'import { CreateFeedbackDTO } from './dto/create-feedback.dto'+import { UpdateWebsiteAddonDTO } from './dto/update-website-addon.dto'import { checkRateLimit, getIPDetails, getIPFromHeaders } from '../common/utils'import { IUsageInfo, IMetaInfo } from './interfaces'import { ReportFrequency } from '../project/enums'@@ -107,10 +108,16 @@ export class UserController {this.projectService.getRedisCount(uid),])- const sanitizedUser = this.userService.omitSensitiveData(user)+ const sanitizedUser = this.userService.omitSensitiveData(user) as Partial<+ User+ > & { websiteAddon?: unknown }sanitizedUser.sharedProjects = sharedProjectssanitizedUser.organisationMemberships = organisationMemberships+ sanitizedUser.websiteAddon = await this.userService.getWebsiteAddonSummary(+ uid,+ user,+ )return {user: sanitizedUser,@@ -870,6 +877,39 @@ export class UserController {return this.userService.previewSubscription(id, planId, planType)}+ @ApiBearerAuth()+ @Post('addons/websites/preview')+ async previewWebsiteAddon(+ @CurrentUserId() id: string,+ @Body() body: UpdateWebsiteAddonDTO,+ ): Promise<any> {+ this.logger.log({ body, id }, 'POST /addons/websites/preview')++ return this.userService.previewWebsiteAddon(+ id,+ body.quantity,+ body.billingInterval,+ )+ }++ @ApiBearerAuth()+ @Put('addons/websites')+ async updateWebsiteAddon(+ @CurrentUserId() id: string,+ @Body() body: UpdateWebsiteAddonDTO,+ ): Promise<Partial<User>> {+ this.logger.log({ body, id }, 'PUT /addons/websites')++ const user = await this.userService.updateWebsiteAddon(+ id,+ body.quantity,+ body.billingInterval,+ )+ await this.projectService.clearProjectsRedisCache(id)++ return user+ }+@ApiBearerAuth()@Post('subscription/cancel')async cancelSubscription(diff --git a/backend/apps/cloud/src/user/user.module.ts b/backend/apps/cloud/src/user/user.module.tsindex 864c00f48..a744dd1a8 100644--- a/backend/apps/cloud/src/user/user.module.ts+++ b/backend/apps/cloud/src/user/user.module.ts@@ -15,6 +15,8 @@ import { CancellationFeedback } from './entities/cancellation-feedback.entity'import { UserFeedback } from './entities/user-feedback.entity'import { Message } from '../integrations/telegram/entities/message.entity'import { OrganisationModule } from '../organisation/organisation.module'+import { UserAddon } from './entities/user-addon.entity'+import { UserAddonCharge } from './entities/user-addon-charge.entity'@Module({imports: [@@ -24,6 +26,8 @@ import { OrganisationModule } from '../organisation/organisation.module'DeleteFeedback,CancellationFeedback,UserFeedback,+ UserAddon,+ UserAddonCharge,Message,]),ActionTokensModule,diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.tsindex 2d8c43c45..d70d379fc 100644--- a/backend/apps/cloud/src/user/user.service.ts+++ b/backend/apps/cloud/src/user/user.service.ts@@ -36,12 +36,23 @@ import {getEffectivePlanType,getPlanTypeEntitlements,getPlanTypeAccountLimitUpdates,+ DEFAULT_MAX_PROJECTS,} from './entities/user.entity'import { UserProfileDTO } from './dto/user.dto'import { RefreshToken } from './entities/refresh-token.entity'import { DeleteFeedback } from './entities/delete-feedback.entity'import { CancellationFeedback } from './entities/cancellation-feedback.entity'import { UserFeedback } from './entities/user-feedback.entity'+import {+ UserAddon,+ UserAddonCode,+ UserAddonStatus,+} from './entities/user-addon.entity'+import {+ UserAddonCharge,+ UserAddonChargeKind,+ UserAddonChargeStatus,+} from './entities/user-addon-charge.entity'import { UserGoogleDTO } from './dto/user-google.dto'import { UserGithubDTO } from './dto/user-github.dto'import { EMAIL_ACTION_ENCRYPTION_KEY } from '../common/constants'@@ -107,6 +118,60 @@ const CURRENCY_BY_COUNTRY = {const { PADDLE_VENDOR_ID, PADDLE_API_KEY } = process.envconst DEFAULT_CDN_URL = 'https://cdn.swetrix.com'const FEEDBACK_ATTACHMENT_UPLOAD_TIMEOUT_MS = 10_000+const WEBSITE_ADDON_BUNDLE_SIZE = 50+const WEBSITE_ADDON_MAX_QUANTITY = 1000+const WEBSITE_ADDON_RETRY_DELAY_HOURS = 6+const WEBSITE_ADDON_MAX_FAILED_CHARGES = 3+const WEBSITE_ADDON_MONTHLY_PRICE: Record<string, number> = {+ USD: 7.5,+ EUR: 7,+ GBP: 6,+}+const WEBSITE_ADDON_CURRENCIES = ['USD', 'EUR', 'GBP']++type WebsiteAddonChangeType =+ | 'none'+ | 'new'+ | 'increase'+ | 'decrease'+ | 'cancel'+ | 'interval_change'+ | 'reactivate'++interface WebsiteAddonPreview {+ code: UserAddonCode.websites+ quantity: number+ currentQuantity: number+ pendingQuantity: number | null+ billingInterval: BillingFrequency+ currentBillingInterval: BillingFrequency | null+ pendingBillingInterval: BillingFrequency | null+ currency: string+ dueNow: number+ recurringAmount: number+ nextChargeDate: string | null+ effectiveDate: string | null+ includedWebsites: number+ totalWebsites: number+ activeExtraWebsites: number+ changeType: WebsiteAddonChangeType+ isLegacy: boolean+ status: UserAddonStatus | null+}++interface WebsiteAddonSummary {+ code: UserAddonCode.websites+ quantity: number+ pendingQuantity: number | null+ billingInterval: BillingFrequency | null+ pendingBillingInterval: BillingFrequency | null+ currency: string | null+ status: UserAddonStatus | 'legacy' | null+ periodEnd: string | null+ nextChargeDate: string | null+ isLegacy: boolean+ failedChargeAttempts: number+}type CdnFileResponse =| string@@ -163,6 +228,10 @@ export class UserService {private readonly cancellationFeedbackRepository: Repository<CancellationFeedback>,@InjectRepository(UserFeedback)private readonly userFeedbackRepository: Repository<UserFeedback>,+ @InjectRepository(UserAddon)+ private readonly userAddonRepository: Repository<UserAddon>,+ @InjectRepository(UserAddonCharge)+ private readonly userAddonChargeRepository: Repository<UserAddonCharge>,private readonly organisationService: OrganisationService,) {}@@ -212,6 +281,808 @@ export class UserService {return this.usersRepository.count(options)}+ private getNumericOverride(+ source: Record<string, unknown> | null | undefined,+ key: string,+ ): number | null {+ const value = source?.[key]+ return typeof value === 'number' ? value : null+ }++ private getAddonOverrideQuantity(user: Partial<User>): number {+ const addonOverrides = user?.addonOverrides || {}+ return (+ this.getNumericOverride(addonOverrides, 'websites') ||+ this.getNumericOverride(addonOverrides, 'additionalWebsites') ||+ 0+ )+ }++ private getIncludedWebsiteLimit(user: Partial<User>): number {+ const effectivePlanType = getEffectivePlanType(user)+ const entitlements = getPlanTypeEntitlements(effectivePlanType)+ const websiteOverride = this.getNumericOverride(+ user?.entitlementOverrides,+ 'websites',+ )++ if (typeof entitlements.websites === 'number') {+ return entitlements.websites+ }++ if (typeof websiteOverride === 'number') {+ return websiteOverride+ }++ return Math.max(+ DEFAULT_MAX_PROJECTS,+ (user?.maxProjects || DEFAULT_MAX_PROJECTS) -+ this.getAddonOverrideQuantity(user),+ )+ }++ private getWebsiteAddonCurrency(user: User): string {+ return (+ typeof user.tierCurrency === 'string' &&+ WEBSITE_ADDON_CURRENCIES.includes(user.tierCurrency)+ )+ ? user.tierCurrency+ : 'USD'+ }++ private roundMoney(amount: number): number {+ return Math.round((amount + Number.EPSILON) * 100) / 100+ }++ private getWebsiteAddonAmount(+ quantity: number,+ billingInterval: BillingFrequency,+ currency: string,+ ): number {+ const monthlyPrice =+ WEBSITE_ADDON_MONTHLY_PRICE[currency] || WEBSITE_ADDON_MONTHLY_PRICE.USD+ const bundles = quantity / WEBSITE_ADDON_BUNDLE_SIZE+ const intervalMultiplier =+ billingInterval === BillingFrequency.Yearly ? 10 : 1++ return this.roundMoney(bundles * monthlyPrice * intervalMultiplier)+ }++ private getWebsiteAddonPeriodEnd(+ from: Date,+ billingInterval: BillingFrequency,+ ): Date {+ return dayjs+ .utc(from)+ .add(+ 1,+ billingInterval === BillingFrequency.Yearly ? 'year' : 'month',+ )+ .toDate()+ }++ private formatAddonDate(date?: Date | string | null): string | null {+ return date ? dayjs.utc(date).toISOString() : null+ }++ private validateWebsiteAddonSelection(+ quantity: number,+ billingInterval: BillingFrequency,+ ) {+ if (+ !Number.isInteger(quantity) ||+ quantity < 0 ||+ quantity > WEBSITE_ADDON_MAX_QUANTITY ||+ quantity % WEBSITE_ADDON_BUNDLE_SIZE !== 0+ ) {+ throw new BadRequestException('invalidWebsiteAddonQuantity')+ }++ if (+ ![BillingFrequency.Monthly, BillingFrequency.Yearly].includes(+ billingInterval,+ )+ ) {+ throw new BadRequestException('invalidWebsiteAddonBillingInterval')+ }+ }++ private validateWebsiteAddonEligibility(user: User) {+ const isSubscriber = ![+ PlanCode.none,+ PlanCode.free,+ PlanCode.trial,+ ].includes(user.planCode)+ const isTrialingPaidPlan =+ user.trialEndDate && dayjs.utc(user.trialEndDate).isAfter(dayjs.utc())++ if (!isSubscriber || !user.subID) {+ throw new BadRequestException('websiteAddonRequiresSubscription')+ }++ if (isTrialingPaidPlan) {+ throw new BadRequestException('websiteAddonUnavailableDuringTrial')+ }++ if (user.cancellationEffectiveDate) {+ throw new BadRequestException('websiteAddonUnavailableCancelled')+ }++ if (user.isAccountBillingSuspended) {+ throw new BadRequestException('websiteAddonUnavailableSuspended')+ }+ }++ private async getWebsiteAddon(userId: string): Promise<UserAddon | null> {+ return this.userAddonRepository.findOne({+ where: {+ userId,+ code: UserAddonCode.websites,+ },+ })+ }++ private getProratedWebsiteAddonAmount(+ addon: UserAddon,+ addedQuantity: number,+ currency: string,+ ): number {+ const fullAmount = this.getWebsiteAddonAmount(+ addedQuantity,+ addon.billingInterval,+ currency,+ )++ if (!addon.periodStart || !addon.periodEnd) {+ return fullAmount+ }++ const now = dayjs.utc()+ const start = dayjs.utc(addon.periodStart)+ const end = dayjs.utc(addon.periodEnd)+ const totalMs = end.diff(start)+ const remainingMs = end.diff(now)++ if (totalMs <= 0 || remainingMs <= 0) {+ return fullAmount+ }++ return this.roundMoney(fullAmount * Math.min(1, remainingMs / totalMs))+ }++ private buildWebsiteAddonPreview(+ user: User,+ addon: UserAddon | null,+ quantity: number,+ billingInterval: BillingFrequency,+ ): WebsiteAddonPreview {+ const legacyQuantity = addon ? 0 : this.getAddonOverrideQuantity(user)+ const isLegacy = legacyQuantity > 0+ const currentQuantity =+ addon && addon.status !== UserAddonStatus.cancelled+ ? addon.quantity+ : legacyQuantity+ const currentBillingInterval =+ addon && addon.status !== UserAddonStatus.cancelled+ ? addon.billingInterval+ : null+ const currency = addon?.currency || this.getWebsiteAddonCurrency(user)+ const includedWebsites = this.getIncludedWebsiteLimit(user)+ const existingChargeDate = addon?.nextChargeDate || addon?.periodEnd || null+ let changeType: WebsiteAddonChangeType = 'none'+ let dueNow = 0+ let effectiveDate: string | null = null++ if (isLegacy) {+ return {+ code: UserAddonCode.websites,+ quantity: currentQuantity,+ currentQuantity,+ pendingQuantity: null,+ billingInterval,+ currentBillingInterval: null,+ pendingBillingInterval: null,+ currency,+ dueNow: 0,+ recurringAmount: 0,+ nextChargeDate: null,+ effectiveDate: null,+ includedWebsites,+ totalWebsites: includedWebsites + currentQuantity,+ activeExtraWebsites: currentQuantity,+ changeType,+ isLegacy,+ status: null,+ }+ }++ if (+ !addon ||+ addon.status === UserAddonStatus.cancelled ||+ (addon.status === UserAddonStatus.past_due && currentQuantity === 0)+ ) {+ if (quantity > 0) {+ changeType =+ addon?.status === UserAddonStatus.past_due ? 'reactivate' : 'new'+ dueNow = this.getWebsiteAddonAmount(quantity, billingInterval, currency)+ }+ } else if (quantity > currentQuantity) {+ changeType = 'increase'+ dueNow = this.getProratedWebsiteAddonAmount(+ addon,+ quantity - currentQuantity,+ currency,+ )+ if (billingInterval !== addon.billingInterval) {+ effectiveDate = this.formatAddonDate(existingChargeDate)+ }+ } else if (quantity < currentQuantity) {+ changeType = quantity === 0 ? 'cancel' : 'decrease'+ effectiveDate = this.formatAddonDate(existingChargeDate)+ } else if (billingInterval !== addon.billingInterval) {+ changeType = 'interval_change'+ effectiveDate = this.formatAddonDate(existingChargeDate)+ } else if (+ addon.pendingQuantity !== null ||+ addon.pendingBillingInterval !== null+ ) {+ changeType = 'none'+ }++ const nextChargeDate =+ existingChargeDate ||+ (quantity > 0+ ? this.getWebsiteAddonPeriodEnd(new Date(), billingInterval)+ : null)+ const displayedExtraWebsites =+ changeType === 'decrease' || changeType === 'cancel'+ ? currentQuantity+ : quantity++ return {+ code: UserAddonCode.websites,+ quantity,+ currentQuantity,+ pendingQuantity: addon?.pendingQuantity ?? null,+ billingInterval,+ currentBillingInterval,+ pendingBillingInterval: addon?.pendingBillingInterval ?? null,+ currency,+ dueNow,+ recurringAmount: this.getWebsiteAddonAmount(+ quantity,+ billingInterval,+ currency,+ ),+ nextChargeDate: this.formatAddonDate(nextChargeDate),+ effectiveDate,+ includedWebsites,+ totalWebsites: includedWebsites + displayedExtraWebsites,+ activeExtraWebsites: currentQuantity,+ changeType,+ isLegacy,+ status: addon?.status || null,+ }+ }++ async previewWebsiteAddon(+ userId: string,+ quantity: number,+ billingInterval: BillingFrequency,+ ): Promise<WebsiteAddonPreview> {+ this.validateWebsiteAddonSelection(quantity, billingInterval)++ const user = await this.findOne({ where: { id: userId } })+ if (!user) {+ throw new BadRequestException('User not found')+ }++ this.validateWebsiteAddonEligibility(user)++ const addon = await this.getWebsiteAddon(userId)+ return this.buildWebsiteAddonPreview(user, addon, quantity, billingInterval)+ }++ private async syncWebsiteAddonEntitlements(+ user: User,+ quantity: number,+ ): Promise<void> {+ const addonOverrides = { ...(user.addonOverrides || {}) }++ if (quantity > 0) {+ addonOverrides.websites = quantity+ } else {+ delete addonOverrides.websites+ delete addonOverrides.additionalWebsites+ }++ await this.update(user.id, {+ addonOverrides: Object.keys(addonOverrides).length+ ? addonOverrides+ : null,+ maxProjects: this.getIncludedWebsiteLimit(user) + quantity,+ })+ }++ async refreshWebsiteAddonEntitlements(userId: string): Promise<void> {+ const user = await this.findOne({ where: { id: userId } })+ if (!user) {+ return+ }++ const addon = await this.getWebsiteAddon(userId)+ const addonQuantity =+ addon && addon.status !== UserAddonStatus.cancelled+ ? addon.quantity+ : this.getAddonOverrideQuantity(user)++ await this.syncWebsiteAddonEntitlements(user, addonQuantity)+ }++ private getPaddleErrorMessage(data: any): string {+ if (typeof data?.error === 'string') {+ return data.error+ }++ if (typeof data?.response?.message === 'string') {+ return data.response.message+ }++ if (typeof data?.response?.error === 'string') {+ return data.response.error+ }++ return 'Paddle charge failed'+ }++ private async createPaddleOneOffCharge(+ subscriptionId: string,+ amount: number,+ chargeName: string,+ ): Promise<Record<string, any>> {+ if (!PADDLE_VENDOR_ID || !PADDLE_API_KEY) {+ throw new ServiceUnavailableException('Paddle is not configured')+ }++ const url = `https://vendors.paddle.com/api/2.0/subscription/${subscriptionId}/charge`+ const body = new URLSearchParams()+ body.set('vendor_id', String(Number(PADDLE_VENDOR_ID)))+ body.set('vendor_auth_code', PADDLE_API_KEY)+ body.set('amount', amount.toFixed(2))+ body.set('charge_name', chargeName)++ const res = await fetch(url, {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body,+ })+ const data = await res.json()++ if (!res.ok || !data?.success) {+ throw new BadRequestException(this.getPaddleErrorMessage(data))+ }++ return data.response || {}+ }++ private async chargeWebsiteAddon(+ addon: UserAddon,+ user: User,+ kind: UserAddonChargeKind,+ amount: number,+ quantity: number,+ previousQuantity: number | null,+ billingInterval: BillingFrequency,+ periodStart: Date | null,+ periodEnd: Date | null,+ ): Promise<void> {+ 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,+ }),+ )++ try {+ const response = await this.createPaddleOneOffCharge(+ user.subID,+ amount,+ chargeName,+ )++ await this.userAddonChargeRepository.update(charge.id, {+ status: UserAddonChargeStatus.succeeded,+ paddleInvoiceId:+ typeof response.invoice_id === 'number' ? response.invoice_id : null,+ paddleOrderId: response.order_id ? String(response.order_id) : null,+ paddleStatus: response.status ? String(response.status) : null,+ paddleReceiptUrl: response.receipt_url+ ? String(response.receipt_url)+ : null,+ paddleResponse: response,+ })+ } catch (reason) {+ await this.userAddonChargeRepository.update(charge.id, {+ status: UserAddonChargeStatus.failed,+ failureReason:+ reason instanceof Error ? reason.message : 'Paddle charge failed',+ })++ throw reason+ }+ }++ async getWebsiteAddonSummary(+ userId: string,+ user?: User,+ ): Promise<WebsiteAddonSummary | null> {+ const [addon, resolvedUser] = await Promise.all([+ this.getWebsiteAddon(userId),+ user ? Promise.resolve(user) : this.findOne({ where: { id: userId } }),+ ])++ if (addon) {+ return {+ code: UserAddonCode.websites,+ quantity: addon.quantity,+ pendingQuantity: addon.pendingQuantity,+ billingInterval: addon.billingInterval,+ pendingBillingInterval: addon.pendingBillingInterval,+ currency: addon.currency,+ status: addon.status,+ periodEnd: this.formatAddonDate(addon.periodEnd),+ nextChargeDate: this.formatAddonDate(addon.nextChargeDate),+ isLegacy: false,+ failedChargeAttempts: addon.failedChargeAttempts,+ }+ }++ const legacyQuantity = resolvedUser+ ? this.getAddonOverrideQuantity(resolvedUser)+ : 0++ if (!legacyQuantity) {+ return null+ }++ return {+ code: UserAddonCode.websites,+ quantity: legacyQuantity,+ pendingQuantity: null,+ billingInterval: null,+ pendingBillingInterval: null,+ currency: resolvedUser?.tierCurrency || null,+ status: 'legacy',+ periodEnd: null,+ nextChargeDate: null,+ isLegacy: true,+ failedChargeAttempts: 0,+ }+ }++ async getUserWithWebsiteAddonSummary(userId: string): Promise<Partial<User>> {+ const user = await this.findOne({ where: { id: userId } })+ const sanitizedUser = this.omitSensitiveData(user)++ return {+ ...sanitizedUser,+ websiteAddon: await this.getWebsiteAddonSummary(userId, user),+ } as Partial<User>+ }++ async updateWebsiteAddon(+ userId: string,+ quantity: number,+ billingInterval: BillingFrequency,+ ): Promise<Partial<User>> {+ this.validateWebsiteAddonSelection(quantity, billingInterval)++ const user = await this.findOne({ where: { id: userId } })+ if (!user) {+ throw new BadRequestException('User not found')+ }++ this.validateWebsiteAddonEligibility(user)++ let addon = await this.getWebsiteAddon(userId)+ if (!addon && this.getAddonOverrideQuantity(user) > 0) {+ throw new BadRequestException('legacyWebsiteAddon')+ }++ 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,+ })+ }++ return this.getUserWithWebsiteAddonSummary(userId)+ }++ const now = new Date()++ if (!addon) {+ addon = await this.userAddonRepository.save(+ this.userAddonRepository.create({+ userId,+ code: UserAddonCode.websites,+ quantity: 0,+ 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,+ )+ }++ if (isInactiveAddon) {+ const periodEnd = this.getWebsiteAddonPeriodEnd(now, billingInterval)++ 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,+ })+ }++ return this.getUserWithWebsiteAddonSummary(userId)+ }++ private async cancelWebsiteAddonNow(addon: UserAddon): Promise<void> {+ await this.userAddonRepository.update(addon.id, {+ quantity: 0,+ pendingQuantity: null,+ pendingBillingInterval: null,+ nextChargeDate: null,+ status: UserAddonStatus.cancelled,+ failedChargeAttempts: 0,+ lastChargeFailedAt: null,+ cancelledAt: new Date(),+ })++ const user =+ addon.user || (await this.findOne({ where: { id: addon.userId } }))+ if (user) {+ await this.syncWebsiteAddonEntitlements(user, 0)+ }+ }++ async scheduleWebsiteAddonCancellation(+ userId: string,+ effectiveDate?: string | Date | null,+ ): Promise<void> {+ const addon = await this.getWebsiteAddon(userId)+ if (!addon || addon.status === UserAddonStatus.cancelled) {+ return+ }++ const effective = effectiveDate ? dayjs.utc(effectiveDate) : null+ if (effective && effective.isBefore(dayjs.utc())) {+ await this.cancelWebsiteAddonNow(addon)+ return+ }++ await this.userAddonRepository.update(addon.id, {+ pendingQuantity: 0,+ nextChargeDate:+ effective &&+ (!addon.nextChargeDate || effective.isBefore(addon.nextChargeDate))+ ? effective.toDate()+ : addon.nextChargeDate,+ })+ }++ async clearWebsiteAddonsForCancelledSubscription(+ userId: string,+ ): Promise<void> {+ const addons = await this.userAddonRepository.find({+ where: { userId, code: UserAddonCode.websites },+ relations: ['user'],+ })++ await Promise.all(addons.map((addon) => this.cancelWebsiteAddonNow(addon)))++ const user = await this.findOne({ where: { id: userId } })+ if (user) {+ await this.syncWebsiteAddonEntitlements(user, 0)+ }+ }++ private async handleWebsiteAddonRenewalFailure(+ addon: UserAddon,+ reason: Error,+ ): Promise<void> {+ const failedChargeAttempts = addon.failedChargeAttempts + 1+ const shouldRemoveCapacity =+ failedChargeAttempts >= WEBSITE_ADDON_MAX_FAILED_CHARGES++ await this.userAddonRepository.update(addon.id, {+ status: UserAddonStatus.past_due,+ failedChargeAttempts,+ lastChargeFailedAt: new Date(),+ nextChargeDate: shouldRemoveCapacity+ ? null+ : dayjs.utc().add(WEBSITE_ADDON_RETRY_DELAY_HOURS, 'hour').toDate(),+ quantity: shouldRemoveCapacity ? 0 : addon.quantity,+ pendingQuantity: shouldRemoveCapacity ? null : addon.pendingQuantity,+ pendingBillingInterval: shouldRemoveCapacity+ ? null+ : addon.pendingBillingInterval,+ })++ if (shouldRemoveCapacity) {+ const user =+ addon.user || (await this.findOne({ where: { id: addon.userId } }))+ if (user) {+ await this.syncWebsiteAddonEntitlements(user, 0)+ }+ }++ console.error('[ERROR] (processWebsiteAddonRenewal):', reason)+ }++ private async processWebsiteAddonRenewal(addon: UserAddon): Promise<void> {+ const user = addon.user++ if (!user || !user.subID || user.cancellationEffectiveDate) {+ await this.cancelWebsiteAddonNow(addon)+ return+ }++ const targetQuantity = addon.pendingQuantity ?? addon.quantity+ const targetBillingInterval =+ addon.pendingBillingInterval || addon.billingInterval++ if (targetQuantity <= 0) {+ await this.cancelWebsiteAddonNow(addon)+ return+ }++ const periodStart = new Date()+ const periodEnd = this.getWebsiteAddonPeriodEnd(+ periodStart,+ targetBillingInterval,+ )+ const amount = this.getWebsiteAddonAmount(+ targetQuantity,+ targetBillingInterval,+ addon.currency,+ )++ try {+ await this.chargeWebsiteAddon(+ addon,+ user,+ UserAddonChargeKind.renewal,+ amount,+ targetQuantity,+ addon.quantity,+ targetBillingInterval,+ periodStart,+ periodEnd,+ )++ await this.userAddonRepository.update(addon.id, {+ quantity: targetQuantity,+ pendingQuantity: null,+ billingInterval: targetBillingInterval,+ pendingBillingInterval: null,+ periodStart,+ periodEnd,+ nextChargeDate: periodEnd,+ status: UserAddonStatus.active,+ failedChargeAttempts: 0,+ lastChargeFailedAt: null,+ })+ await this.syncWebsiteAddonEntitlements(user, targetQuantity)+ } catch (reason) {+ await this.handleWebsiteAddonRenewalFailure(+ addon,+ reason instanceof Error ? reason : new Error(String(reason)),+ )+ }+ }++ async processDueWebsiteAddonRenewals(): Promise<void> {+ const dueAddons = await this.userAddonRepository.find({+ where: [+ {+ code: UserAddonCode.websites,+ status: UserAddonStatus.active,+ nextChargeDate: LessThan(new Date()),+ },+ {+ code: UserAddonCode.websites,+ status: UserAddonStatus.past_due,+ nextChargeDate: LessThan(new Date()),+ },+ ],+ relations: ['user'],+ })++ await Promise.allSettled(+ dueAddons.map((addon) => this.processWebsiteAddonRenewal(addon)),+ )+ }+omitSensitiveData(user: Partial<User>): Partial<User> {const maxEventsCount = ACCOUNT_PLANS[user?.planCode]?.monthlyUsageLimit || 0const effectivePlanType = getEffectivePlanType(user)@@ -760,6 +1631,7 @@ export class UserService {}await this.update(id, updateParams)+ await this.refreshWebsiteAddonEntitlements(id)}async generatePayLink(diff --git a/backend/apps/cloud/src/webhook/webhook.controller.ts b/backend/apps/cloud/src/webhook/webhook.controller.tsindex fe96b6aa3..245e5c02d 100644--- a/backend/apps/cloud/src/webhook/webhook.controller.ts+++ b/backend/apps/cloud/src/webhook/webhook.controller.ts@@ -195,6 +195,7 @@ export class WebhookController {}await this.userService.update(currentUser.id, updateParams)+ await this.userService.refreshWebsiteAddonEntitlements(currentUser.id)await this.projectService.clearProjectsRedisCache(currentUser.id)if (body.alert_name === 'subscription_created' && isTrialing) {@@ -232,6 +233,13 @@ export class WebhookController {where: { subID },})+ if (user?.id) {+ await this.userService.scheduleWebsiteAddonCancellation(+ user.id,+ cancellationEffectiveDate,+ )+ }+if (user?.email) {const isTrialing =user.trialEndDate && new Date(user.trialEndDate) > new Date()diff --git a/backend/migrations/mysql/2026_06_01_user_addons.sql b/backend/migrations/mysql/2026_06_01_user_addons.sqlnew file mode 100644index 000000000..dfafb1f47--- /dev/null+++ b/backend/migrations/mysql/2026_06_01_user_addons.sql@@ -0,0 +1,51 @@+CREATE TABLE `user_addon` (+ `id` varchar(36) NOT NULL,+ `userId` varchar(36) NOT NULL,+ `code` enum('websites') NOT NULL,+ `quantity` int NOT NULL DEFAULT '0',+ `pendingQuantity` int DEFAULT NULL,+ `billingInterval` enum('monthly','yearly') NOT NULL DEFAULT 'monthly',+ `pendingBillingInterval` enum('monthly','yearly') DEFAULT NULL,+ `currency` varchar(3) NOT NULL DEFAULT 'USD',+ `periodStart` timestamp NULL DEFAULT NULL,+ `periodEnd` timestamp NULL DEFAULT NULL,+ `nextChargeDate` timestamp NULL DEFAULT NULL,+ `status` enum('active','past_due','cancelled') NOT NULL DEFAULT 'active',+ `failedChargeAttempts` int NOT NULL DEFAULT '0',+ `lastChargeFailedAt` timestamp NULL DEFAULT NULL,+ `cancelledAt` timestamp NULL DEFAULT NULL,+ `createdAt` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),+ `updatedAt` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),+ PRIMARY KEY (`id`),+ UNIQUE KEY `IDX_user_addon_user_code` (`userId`,`code`),+ KEY `IDX_user_addon_next_charge_status` (`nextChargeDate`,`status`),+ CONSTRAINT `FK_user_addon_user` FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;++CREATE TABLE `user_addon_charge` (+ `id` varchar(36) NOT NULL,+ `addonId` varchar(36) NOT NULL,+ `userId` varchar(36) NOT NULL,+ `kind` enum('initial','prorated','renewal') NOT NULL,+ `status` enum('pending','succeeded','failed') NOT NULL DEFAULT 'pending',+ `quantity` int NOT NULL,+ `previousQuantity` int DEFAULT NULL,+ `billingInterval` enum('monthly','yearly') NOT NULL,+ `amount` decimal(10,2) NOT NULL,+ `currency` varchar(3) NOT NULL,+ `periodStart` timestamp NULL DEFAULT NULL,+ `periodEnd` timestamp NULL DEFAULT NULL,+ `paddleInvoiceId` int DEFAULT NULL,+ `paddleOrderId` varchar(80) DEFAULT NULL,+ `paddleStatus` varchar(80) DEFAULT NULL,+ `paddleReceiptUrl` varchar(300) DEFAULT NULL,+ `paddleResponse` json DEFAULT NULL,+ `failureReason` text,+ `createdAt` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),+ `updatedAt` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),+ PRIMARY KEY (`id`),+ KEY `IDX_user_addon_charge_addon_created` (`addonId`,`createdAt`),+ KEY `IDX_user_addon_charge_user` (`userId`),+ CONSTRAINT `FK_user_addon_charge_addon` FOREIGN KEY (`addonId`) REFERENCES `user_addon` (`id`) ON DELETE CASCADE,+ CONSTRAINT `FK_user_addon_charge_user` FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;diff --git a/web/app/lib/models/User.ts b/web/app/lib/models/User.tsindex ef9b0568d..9aee6f96e 100644--- a/web/app/lib/models/User.ts+++ b/web/app/lib/models/User.ts@@ -35,6 +35,20 @@ export enum PlanType {enterprise = 'enterprise',}+export interface WebsiteAddon {+ code: 'websites'+ quantity: number+ pendingQuantity: number | null+ billingInterval: 'monthly' | 'yearly' | null+ pendingBillingInterval: 'monthly' | 'yearly' | null+ currency: 'USD' | 'EUR' | 'GBP' | null+ status: 'active' | 'past_due' | 'cancelled' | 'legacy' | null+ periodEnd: string | null+ nextChargeDate: string | null+ isLegacy: boolean+ failedChargeAttempts: number+}+enum OnboardingStep {LANGUAGE = 'language',WELCOME = 'welcome',@@ -89,6 +103,7 @@ export interface User {maxApiKeyRequestsPerHour: numbersessionReplaysIncluded: number | stringpurchasedWebsiteAddons: number+ websiteAddon?: WebsiteAddon | nulltierCurrency: 'USD' | 'EUR' | 'GBP' | nullshowLiveVisitorsInTitle: booleanreceiveLoginNotifications: booleandiff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsxindex 6f3117465..74cfda674 100644--- a/web/app/pages/UserSettings/UserSettings.tsx+++ b/web/app/pages/UserSettings/UserSettings.tsx@@ -19,6 +19,8 @@ import {CaretDownIcon,CreditCardIcon,ArrowRightIcon,+ MinusIcon,+ PlusIcon,} from '@phosphor-icons/react'import _round from 'lodash/round'import React, {@@ -60,6 +62,7 @@ import { User } from '~/lib/models/User'import {ADDONS,getEffectivePlanType,+ type BillingInterval,type CurrencyCode,} from '~/lib/pricing/catalog'import PaidFeature from '~/modals/PaidFeature'@@ -68,6 +71,7 @@ import { useTheme } from '~/providers/ThemeProvider'import type {UserSettingsActionData,UserSettingsLoaderData,+ WebsiteAddonPreview,} from '~/routes/user-settings'import Alert from '~/ui/Alert'import Button from '~/ui/Button'@@ -195,6 +199,11 @@ const DEFAULT_USAGE_INFO: UsageInfo = {captchaPerc: 0,}+const WEBSITE_ADDON_QUANTITY_OPTIONS = Array.from(+ { length: 21 },+ (_, index) => index * 50,+)+const formatBillingPrice = (amount: number) =>Number.isInteger(amount) ? amount.toFixed(0) : amount.toFixed(2)@@ -250,6 +259,8 @@ const UserSettings = () => {const fetcher = useFetcher<UserSettingsActionData>()const profileAutosaveFetcher = useFetcher<UserSettingsActionData>()const metainfoFetcher = useFetcher<UserSettingsActionData>()+ const websiteAddonFetcher = useFetcher<UserSettingsActionData>()+ const websiteAddonPreviewFetcher = useFetcher<UserSettingsActionData>()const [searchParams, setSearchParams] = useSearchParams()@@ -286,6 +297,8 @@ const UserSettings = () => {maxApiKeyRequestsPerHour = 0,sessionReplaysIncluded = 0,purchasedWebsiteAddons = 0,+ websiteAddon,+ isAccountBillingSuspended,} = user || ({} as Partial<User>)const isSubscriber = !['none', 'trial', 'free'].includes(planCode || '')@@ -317,17 +330,21 @@ const UserSettings = () => {: sessionReplaysIncluded || '0'const currentPlanType = getEffectivePlanType(user?.planType, planCode)const currentPlanName = t(`pricing.planTypes.${currentPlanType}.name`)- const hasActiveSubscription = isSubscriber && !cancellationEffectiveDateconst currencyCode = ((user?.tierCurrency || metainfo.code) in CURRENCIES? user?.tierCurrency || metainfo.code: 'USD') as CurrencyCodeconst currency = CURRENCIES[currencyCode]- const websiteAddon = ADDONS.websiteBundles[0]+ const websiteAddonBundle = ADDONS.websiteBundles[0]const sessionReplayAddon = ADDONS.sessionReplayBundles[0]- const websiteAddonPrice = websiteAddon.monthly[currencyCode]+ const websiteAddonPrice = websiteAddonBundle.monthly[currencyCode]const sessionReplayAddonPrice = sessionReplayAddon.monthly[currencyCode]+ const activeWebsiteAddonQuantity =+ websiteAddon?.quantity ?? purchasedWebsiteAddons+ const currentWebsiteAddonBillingInterval = (websiteAddon?.billingInterval ||+ 'monthly') as BillingInterval+ const isWebsiteAddonLegacy = !!websiteAddon?.isLegacyconst isTrialEnded = (() => {if (!trialEndDate) {@@ -387,6 +404,24 @@ const UserSettings = () => {}}+ const onWebsiteAddonQuantityStep = (direction: 1 | -1) => {+ setSelectedWebsiteAddonQuantity((value) =>+ Math.min(1000, Math.max(0, value + direction * 50)),+ )+ }++ const onWebsiteAddonUpdate = () => {+ const formData = new FormData()+ formData.set('intent', 'update-website-addon')+ formData.set('quantity', String(selectedWebsiteAddonQuantity))+ formData.set('billingInterval', selectedWebsiteAddonBillingInterval)++ websiteAddonFetcher.submit(formData, {+ method: 'POST',+ action: '/user-settings',+ })+ }+const tabs = getTabs(t)const sidebarGroups = useMemo<SettingsTabGroup<SettingsTab>[]>(() => [@@ -443,6 +478,12 @@ const UserSettings = () => {const [reportFrequency, setReportFrequency] = useState(() => user?.reportFrequency,)+ const [selectedWebsiteAddonQuantity, setSelectedWebsiteAddonQuantity] =+ useState(activeWebsiteAddonQuantity)+ const [+ selectedWebsiteAddonBillingInterval,+ setSelectedWebsiteAddonBillingInterval,+ ] = useState<BillingInterval>(currentWebsiteAddonBillingInterval)const [showModal, setShowModal] = useState(false)const [showAPIDeleteModal, setShowAPIDeleteModal] = useState(false)const translatedFrequencies = useMemo(@@ -459,6 +500,9 @@ const UserSettings = () => {const lastHandledProfileAutosaveData = useRef<UserSettingsActionData | null>(null,)+ const lastHandledWebsiteAddonData = useRef<UserSettingsActionData | null>(+ null,+ )const shouldHandleFetcherData =useDeduplicateFetcherResponse<UserSettingsActionData>()const profileUpdateToast = useRef('profileSettings.updated')@@ -475,6 +519,151 @@ const UserSettings = () => {const pendingToggles = useRef<Map<string, boolean>>(new Map())const isSubmitting = fetcher.state === 'submitting'+ const isWebsiteAddonSubmitting = websiteAddonFetcher.state !== 'idle'+ const websiteAddonPreview = useMemo(() => {+ if (+ websiteAddonPreviewFetcher.data?.success &&+ websiteAddonPreviewFetcher.data.intent === 'preview-website-addon'+ ) {+ return websiteAddonPreviewFetcher.data.data as WebsiteAddonPreview+ }++ return null+ }, [websiteAddonPreviewFetcher.data])+ const isWebsiteAddonPreviewLoading =+ websiteAddonPreviewFetcher.state !== 'idle'+ const currentWebsiteAddonPreview = useMemo(() => {+ if (+ websiteAddonPreview?.quantity === selectedWebsiteAddonQuantity &&+ websiteAddonPreview.billingInterval === selectedWebsiteAddonBillingInterval+ ) {+ return websiteAddonPreview+ }++ return null+ }, [+ websiteAddonPreview,+ selectedWebsiteAddonQuantity,+ selectedWebsiteAddonBillingInterval,+ ])+ const hasPendingWebsiteAddonChange =+ (websiteAddon?.pendingQuantity ?? null) !== null ||+ (websiteAddon?.pendingBillingInterval ?? null) !== null+ const websiteAddonDisabledReason = useMemo(() => {+ if (!isSubscriber) {+ return t('billing.websiteAddonRequiresSubscription')+ }++ if (isTrial) {+ return t('billing.websiteAddonUnavailableDuringTrial')+ }++ if (cancellationEffectiveDate) {+ return t('billing.websiteAddonUnavailableCancelled')+ }++ if (isAccountBillingSuspended) {+ return t('billing.websiteAddonUnavailableSuspended')+ }++ if (isWebsiteAddonLegacy) {+ return t('billing.websiteAddonLegacyManaged')+ }++ return null+ }, [+ isSubscriber,+ isTrial,+ cancellationEffectiveDate,+ isAccountBillingSuspended,+ isWebsiteAddonLegacy,+ t,+ ])+ const isWebsiteAddonDisabled = !!websiteAddonDisabledReason+ const hasWebsiteAddonChanges =+ selectedWebsiteAddonQuantity !== activeWebsiteAddonQuantity ||+ selectedWebsiteAddonBillingInterval !== currentWebsiteAddonBillingInterval ||+ hasPendingWebsiteAddonChange+ const websiteAddonPreviewError =+ websiteAddonPreviewFetcher.data?.intent === 'preview-website-addon' &&+ websiteAddonPreviewFetcher.data.error+ ? websiteAddonPreviewFetcher.data.error+ : null+ const websiteAddonPreviewErrorMessage = websiteAddonPreviewError+ ? (() => {+ const billingTranslated = t(`billing.${websiteAddonPreviewError}`)+ const apiTranslated = t(`apiNotifications.${websiteAddonPreviewError}`)++ return billingTranslated !== `billing.${websiteAddonPreviewError}`+ ? billingTranslated+ : apiTranslated !== `apiNotifications.${websiteAddonPreviewError}`+ ? apiTranslated+ : websiteAddonPreviewError+ })()+ : null+ const includedWebsiteLimit =+ currentWebsiteAddonPreview?.includedWebsites ??+ Math.max(0, (maxProjects || 0) - activeWebsiteAddonQuantity)+ const displayedWebsiteLimit = maxProjects+ const displayedProjectsUsage =+ displayedWebsiteLimit > 0+ ? Math.min(+ 100,+ _round((usageInfo.projects / displayedWebsiteLimit) * 100, 2),+ )+ : 0+ const displayedPurchasedWebsites = activeWebsiteAddonQuantity+ const selectedWebsiteAddonRecurringAmount =+ currentWebsiteAddonPreview?.recurringAmount ??+ websiteAddonPrice *+ (selectedWebsiteAddonQuantity / websiteAddonBundle.quantity) *+ (selectedWebsiteAddonBillingInterval === 'yearly' ? 10 : 1)+ const websiteAddonStatusLabel = (() => {+ if (hasPendingWebsiteAddonChange) {+ return t('billing.websiteAddonPending')+ }++ if (isWebsiteAddonLegacy) {+ return t('billing.websiteAddonLegacy')+ }++ if (websiteAddon?.status === 'past_due') {+ return t('billing.websiteAddonPastDue')+ }++ if (activeWebsiteAddonQuantity > 0) {+ return t('billing.websiteAddonActive')+ }++ return t('billing.websiteAddonIncluded')+ })()+ const websiteAddonStatusClassName = cx(+ 'shrink-0 rounded-md px-2 py-1 text-xs font-semibold',+ {+ 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300':+ activeWebsiteAddonQuantity > 0 &&+ !hasPendingWebsiteAddonChange &&+ !isWebsiteAddonLegacy &&+ websiteAddon?.status !== 'past_due',+ 'bg-amber-100 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300':+ hasPendingWebsiteAddonChange || websiteAddon?.status === 'past_due',+ 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200':+ !hasPendingWebsiteAddonChange &&+ websiteAddon?.status !== 'past_due' &&+ (activeWebsiteAddonQuantity === 0 || isWebsiteAddonLegacy),+ },+ )++ const formatBillingDate = useCallback(+ (date?: string | null) => {+ if (!date) return null++ return language === 'en'+ ? dayjs(date).locale(language).format('MMMM D, YYYY')+ : dayjs(date).locale(language).format('D MMMM, YYYY')+ },+ [language],+ )const activeTabConfig = useMemo(() => _find(tabs, (tab) => tab.id === activeTab),@@ -482,6 +671,41 @@ const UserSettings = () => {)const activeTabLabel = activeTabConfig?.label+ useEffect(() => {+ setSelectedWebsiteAddonQuantity(activeWebsiteAddonQuantity)+ setSelectedWebsiteAddonBillingInterval(currentWebsiteAddonBillingInterval)+ }, [+ activeWebsiteAddonQuantity,+ currentWebsiteAddonBillingInterval,+ user?.id,+ ])++ useEffect(() => {+ if (+ activeTab !== TAB_MAPPING.BILLING ||+ !user?.id ||+ isWebsiteAddonDisabled+ ) {+ return+ }++ const formData = new FormData()+ formData.set('intent', 'preview-website-addon')+ formData.set('quantity', String(selectedWebsiteAddonQuantity))+ formData.set('billingInterval', selectedWebsiteAddonBillingInterval)+ websiteAddonPreviewFetcher.submit(formData, {+ method: 'POST',+ action: '/user-settings',+ })+ }, [+ activeTab,+ user?.id,+ isWebsiteAddonDisabled,+ selectedWebsiteAddonQuantity,+ selectedWebsiteAddonBillingInterval,+ websiteAddonPreviewFetcher,+ ])+useEffect(() => {if (fetcher.state !== 'idle' || !fetcher.data) returnif (!shouldHandleFetcherData(fetcher.data)) return@@ -579,6 +803,48 @@ const UserSettings = () => {shouldHandleFetcherData,])+ useEffect(() => {+ if (+ websiteAddonFetcher.state !== 'idle' ||+ !websiteAddonFetcher.data ||+ lastHandledWebsiteAddonData.current === websiteAddonFetcher.data+ ) {+ return+ }++ lastHandledWebsiteAddonData.current = websiteAddonFetcher.data++ if (+ websiteAddonFetcher.data.success &&+ websiteAddonFetcher.data.intent === 'update-website-addon' &&+ websiteAddonFetcher.data.user+ ) {+ mergeUser(websiteAddonFetcher.data.user)+ toast.success(t('billing.websiteAddonUpdated'))+ loadUser()+ return+ }++ if (websiteAddonFetcher.data.error) {+ const translated = t(`apiNotifications.${websiteAddonFetcher.data.error}`)+ const billingTranslated = t(`billing.${websiteAddonFetcher.data.error}`)++ toast.error(+ billingTranslated !== `billing.${websiteAddonFetcher.data.error}`+ ? billingTranslated+ : translated !== `apiNotifications.${websiteAddonFetcher.data.error}`+ ? translated+ : websiteAddonFetcher.data.error,+ )+ }+ }, [+ websiteAddonFetcher.data,+ websiteAddonFetcher.state,+ mergeUser,+ t,+ loadUser,+ ])+const flushProfileAutosave = useCallback(() => {const autosave = pendingProfileAutosave.currentif (profileAutosaveFetcher.state !== 'idle' || !autosave) return@@ -1884,119 +2150,382 @@ const UserSettings = () => {</div></SettingsSection>- {hasActiveSubscription ? (- <SettingsSection- title={t('billing.addonsTitle')}- description={t('billing.addonsDesc')}- >- <div className='grid gap-6 border-t border-gray-200 pt-4 lg:grid-cols-2 dark:border-slate-800'>- <div>- <div className='flex items-start justify-between gap-3'>- <div>- <Text as='h4' size='base' weight='semibold'>- {t('billing.websiteAddonTitle')}+ <SettingsSection+ title={t('billing.addonsTitle')}+ description={t('billing.addonsDesc')}+ >+ <div className='grid gap-4 border-t border-gray-200 pt-4 xl:grid-cols-[minmax(0,1.55fr)_minmax(300px,0.85fr)] dark:border-slate-800'>+ <div className='rounded-lg border border-gray-200 p-4 dark:border-slate-800'>+ <div className='flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between'>+ <div>+ <Text as='h4' size='base' weight='semibold'>+ {t('billing.websiteAddonTitle')}+ </Text>+ <Text+ as='p'+ size='sm'+ colour='secondary'+ className='mt-1'+ >+ {t('billing.websiteAddonDescription', {+ amount: websiteAddonBundle.quantity,+ unitPrice: `${currency.symbol}${formatBillingPrice(+ websiteAddonPrice /+ websiteAddonBundle.quantity,+ )}`,+ })}+ </Text>+ </div>+ <Text as='span' className={websiteAddonStatusClassName}>+ {websiteAddonStatusLabel}+ </Text>+ </div>++ <div className='mt-4 border-y border-gray-200 py-3 dark:border-slate-800'>+ <div className='grid gap-3 sm:grid-cols-3 sm:divide-x sm:divide-gray-200 dark:sm:divide-slate-800'>+ <div className='sm:pr-4'>+ <Text as='p' size='xs' colour='muted'>+ {t('billing.websiteAddonUsage')}</Text><Textas='p'size='sm'- colour='secondary'+ weight='semibold'className='mt-1'>- {t('billing.websiteAddonDescription', {- amount: websiteAddon.quantity,- unitPrice: `${currency.symbol}${formatBillingPrice(- websiteAddonPrice / websiteAddon.quantity,- )}`,+ {t('billing.xofy', {+ x: (usageInfo.projects || 0).toLocaleString(),+ y: (+ displayedWebsiteLimit || 0+ ).toLocaleString(),})}</Text></div>- {purchasedWebsiteAddons ? (+ <div className='sm:px-4'>+ <Text as='p' size='xs' colour='muted'>+ {t('billing.websiteAddonIncluded')}+ </Text><Text- as='span'- size='xs'+ as='p'+ size='sm'weight='semibold'- className='shrink-0 rounded-md bg-emerald-100 px-2 py-1 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300'+ className='mt-1'>- {t('billing.activeAddonAmount', {- amount:- purchasedWebsiteAddons.toLocaleString(),+ {t('pricing.websiteCount', {+ count: includedWebsiteLimit,})}</Text>- ) : null}+ </div>+ <div className='sm:pl-4'>+ <Text as='p' size='xs' colour='muted'>+ {t('billing.websiteAddonPurchased')}+ </Text>+ <Text+ as='p'+ size='sm'+ weight='semibold'+ className='mt-1'+ >+ {displayedPurchasedWebsites+ ? t('billing.addedWebsites', {+ amount:+ displayedPurchasedWebsites.toLocaleString(),+ })+ : t('billing.noAdditionalWebsites')}+ </Text>+ </div></div>- <Text- as='p'- size='lg'- weight='bold'- className='mt-4'- >- {currency.symbol}- {formatBillingPrice(websiteAddonPrice)}+ <div className='mt-3 h-1.5 overflow-hidden rounded-full bg-gray-200 dark:bg-slate-800'>+ <div+ className='h-full rounded-full bg-slate-900 dark:bg-slate-100'+ style={{ width: `${displayedProjectsUsage}%` }}+ />+ </div>+ </div>++ <div className='mt-4 grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(260px,0.8fr)]'>+ <div>+ <Text as='label' size='sm' weight='medium'>+ {t('billing.websiteAddonQuantity')}+ </Text>+ <div className='mt-1.5 flex items-center gap-2'>+ <Button+ variant='icon'+ aria-label={t(+ 'billing.websiteAddonDecreaseQuantity',+ )}+ title={t(+ 'billing.websiteAddonDecreaseQuantity',+ )}+ disabled={+ isWebsiteAddonDisabled ||+ selectedWebsiteAddonQuantity <= 0+ }+ onClick={() => onWebsiteAddonQuantityStep(-1)}+ >+ <MinusIcon className='size-4' />+ </Button>+ <Select<number>+ selectedItem={selectedWebsiteAddonQuantity}+ items={WEBSITE_ADDON_QUANTITY_OPTIONS}+ onSelect={setSelectedWebsiteAddonQuantity}+ disabled={isWebsiteAddonDisabled}+ className='min-w-44 flex-1'+ title={+ selectedWebsiteAddonQuantity+ ? t('billing.extraWebsitesAmount', {+ amount:+ selectedWebsiteAddonQuantity.toLocaleString(),+ })+ : t('billing.noAdditionalWebsites')+ }+ labelExtractor={(amount) =>+ amount+ ? t('billing.extraWebsitesAmount', {+ amount: amount.toLocaleString(),+ })+ : t('billing.noAdditionalWebsites')+ }+ keyExtractor={(amount) => String(amount)}+ />+ <Button+ variant='icon'+ aria-label={t(+ 'billing.websiteAddonIncreaseQuantity',+ )}+ title={t(+ 'billing.websiteAddonIncreaseQuantity',+ )}+ disabled={+ isWebsiteAddonDisabled ||+ selectedWebsiteAddonQuantity >= 1000+ }+ onClick={() => onWebsiteAddonQuantityStep(1)}+ >+ <PlusIcon className='size-4' />+ </Button>+ </div>+ </div>++ <div>+ <Text as='p' size='sm' weight='medium'>+ {t('billing.websiteAddonBillingInterval')}+ </Text>+ <div className='mt-1.5 grid grid-cols-2 rounded-md border border-gray-300 bg-gray-50 p-1 dark:border-slate-700/80 dark:bg-slate-950'>+ {(['monthly', 'yearly'] as BillingInterval[]).map(+ (interval) => (+ <button+ key={interval}+ type='button'+ disabled={isWebsiteAddonDisabled}+ onClick={() =>+ setSelectedWebsiteAddonBillingInterval(+ interval,+ )+ }+ className={cx(+ 'rounded-sm px-3 py-1.5 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-60',+ selectedWebsiteAddonBillingInterval ===+ interval+ ? 'bg-white text-slate-900 ring-1 ring-gray-200 dark:bg-slate-900 dark:text-gray-50 dark:ring-slate-700'+ : 'text-gray-600 hover:text-slate-900 dark:text-gray-300 dark:hover:text-gray-50',+ )}+ >+ {interval === 'monthly'+ ? t('billing.websiteAddonMonthly')+ : t('billing.websiteAddonYearly')}+ </button>+ ),+ )}+ </div><Text- as='span'- size='sm'- weight='medium'- colour='secondary'+ as='p'+ size='xs'+ colour='muted'+ className='mt-1'>- /{t('pricing.intervals.month')}+ {t('billing.websiteAddonYearlyDiscount')}</Text>+ </div>+ </div>++ {websiteAddonDisabledReason ? (+ <Alert variant='info' className='mt-4'>+ {websiteAddonDisabledReason}+ </Alert>+ ) : null}+ {hasPendingWebsiteAddonChange &&+ !websiteAddonDisabledReason ? (+ <Alert variant='warning' className='mt-4'>+ {t('billing.websiteAddonPendingChange', {+ date:+ formatBillingDate(+ websiteAddon?.nextChargeDate ||+ websiteAddon?.periodEnd,+ ) || t('billing.websiteAddonNextRenewal'),+ })}+ </Alert>+ ) : null}+ {websiteAddonPreviewErrorMessage ? (+ <Alert variant='error' className='mt-4'>+ {websiteAddonPreviewErrorMessage}+ </Alert>+ ) : null}++ {currentWebsiteAddonPreview &&+ hasWebsiteAddonChanges ? (+ <div className='mt-4 border-t border-gray-200 pt-4 dark:border-slate-800'>+ <div className='grid gap-3 sm:grid-cols-2 xl:grid-cols-4'>+ <div>+ <Text as='p' size='xs' colour='muted'>+ {t('billing.websiteAddonDueNow')}+ </Text>+ <Text+ as='p'+ size='sm'+ weight='semibold'+ className='mt-1'+ >+ {currentWebsiteAddonPreview.dueNow > 0+ ? `${currency.symbol}${formatBillingPrice(+ currentWebsiteAddonPreview.dueNow,+ )}`+ : t('billing.websiteAddonNoImmediateCharge')}+ </Text>+ </div>+ <div>+ <Text as='p' size='xs' colour='muted'>+ {t('billing.websiteAddonRecurring')}+ </Text>+ <Text+ as='p'+ size='sm'+ weight='semibold'+ className='mt-1'+ >+ {currentWebsiteAddonPreview.quantity > 0+ ? `${currency.symbol}${formatBillingPrice(+ selectedWebsiteAddonRecurringAmount,+ )}/${t(+ selectedWebsiteAddonBillingInterval ===+ 'yearly'+ ? 'pricing.intervals.year'+ : 'pricing.intervals.month',+ )}`+ : t('billing.websiteAddonNoNextCharge')}+ </Text>+ </div>+ <div>+ <Text as='p' size='xs' colour='muted'>+ {t('billing.websiteAddonNextCharge')}+ </Text>+ <Text+ as='p'+ size='sm'+ weight='semibold'+ className='mt-1'+ >+ {formatBillingDate(+ currentWebsiteAddonPreview.nextChargeDate,+ ) || t('billing.websiteAddonNoNextCharge')}+ </Text>+ </div>+ {currentWebsiteAddonPreview.effectiveDate ? (+ <div>+ <Text as='p' size='xs' colour='muted'>+ {t('billing.websiteAddonEffectiveOn')}+ </Text>+ <Text+ as='p'+ size='sm'+ weight='semibold'+ className='mt-1'+ >+ {formatBillingDate(+ currentWebsiteAddonPreview.effectiveDate,+ )}+ </Text>+ </div>+ ) : null}+ </div>+ </div>+ ) : null}++ <div className='mt-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between'>+ <Text as='p' size='xs' colour='muted'>+ {t('billing.websiteAddonMaxSelfServe')}</Text><Button- to={routes.contact}- variant='secondary'size='lg'- className='mt-4 gap-1'+ onClick={onWebsiteAddonUpdate}+ loading={isWebsiteAddonSubmitting}+ disabled={+ isWebsiteAddonDisabled ||+ !hasWebsiteAddonChanges ||+ isWebsiteAddonPreviewLoading ||+ !!websiteAddonPreviewError+ }>- {t('billing.requestAddon')}- <ArrowRightIcon className='size-4' />+ {t('billing.websiteAddonSave')}</Button></div>+ </div>- <div>- <Text as='h4' size='base' weight='semibold'>- {t('billing.sessionReplayAddonTitle')}- </Text>- <Text- as='p'- size='sm'- colour='secondary'- className='mt-1'- >- {t('billing.sessionReplayAddonDescription', {- amount:- sessionReplayAddon.quantity.toLocaleString(),- })}- </Text>- <Text- as='p'- size='lg'- weight='bold'- className='mt-4'- >- {currency.symbol}- {formatBillingPrice(sessionReplayAddonPrice)}+ <div className='rounded-lg border border-gray-200 p-4 dark:border-slate-800'>+ <div className='flex items-start justify-between gap-3'>+ <div>+ <Text as='h4' size='base' weight='semibold'>+ {t('billing.sessionReplayAddonTitle')}+ </Text><Text- as='span'+ as='p'size='sm'- weight='medium'colour='secondary'+ className='mt-1'>- /{t('pricing.intervals.month')}+ {t('billing.sessionReplayAddonDescription', {+ amount:+ sessionReplayAddon.quantity.toLocaleString(),+ })}</Text>- </Text>- <Button- to={routes.contact}- variant='secondary'- size='lg'- className='mt-4 gap-1'+ </div>+ <Text+ as='span'+ size='xs'+ weight='semibold'+ className='shrink-0 rounded-md bg-slate-100 px-2 py-1 text-slate-700 dark:bg-slate-800 dark:text-slate-200'>- {t('billing.requestAddon')}- <ArrowRightIcon className='size-4' />- </Button>+ {t('billing.comingSoon')}+ </Text></div>+ <Text+ as='p'+ size='lg'+ weight='bold'+ className='mt-4'+ >+ {currency.symbol}+ {formatBillingPrice(sessionReplayAddonPrice)}+ <Text+ as='span'+ size='sm'+ weight='medium'+ colour='secondary'+ >+ /{t('pricing.intervals.month')}+ </Text>+ </Text>+ <Text+ as='p'+ size='sm'+ colour='secondary'+ className='mt-3'+ >+ {t('billing.sessionReplayAddonComingSoon')}+ </Text></div>- </SettingsSection>- ) : null}+ </div>+ </SettingsSection></>)}</>diff --git a/web/app/routes/user-settings.tsx b/web/app/routes/user-settings.tsxindex d3d5d542f..83c75db2c 100644--- a/web/app/routes/user-settings.tsx+++ b/web/app/routes/user-settings.tsx@@ -103,6 +103,34 @@ export interface UserSettingsActionData {data?: unknown}+export interface WebsiteAddonPreview {+ code: 'websites'+ quantity: number+ currentQuantity: number+ pendingQuantity: number | null+ billingInterval: 'monthly' | 'yearly'+ currentBillingInterval: 'monthly' | 'yearly' | null+ pendingBillingInterval: 'monthly' | 'yearly' | null+ currency: string+ dueNow: number+ recurringAmount: number+ nextChargeDate: string | null+ effectiveDate: string | null+ includedWebsites: number+ totalWebsites: number+ activeExtraWebsites: number+ changeType:+ | 'none'+ | 'new'+ | 'increase'+ | 'decrease'+ | 'cancel'+ | 'interval_change'+ | 'reactivate'+ isLegacy: boolean+ status: 'active' | 'past_due' | 'cancelled' | null+}+const resolveCatalogSelection = (formData: FormData) => {const rawPlanType = formData.get('planType')?.toString()const rawEventTier = formData.get('eventTier')?.toString()@@ -219,8 +247,12 @@ export async function action({ request }: ActionFunctionArgs) {})if (result.error) {+ const error = Array.isArray(result.error)+ ? result.error[0]+ : (result.error as string)+return data<UserSettingsActionData>(- { intent, error: result.error as string },+ { intent, error },{ status: 400 },)}@@ -241,8 +273,12 @@ export async function action({ request }: ActionFunctionArgs) {)if (result.error) {+ const error = Array.isArray(result.error)+ ? result.error[0]+ : (result.error as string)+return data<UserSettingsActionData>(- { intent, error: result.error as string },+ { intent, error },{ status: 400 },)}@@ -445,6 +481,58 @@ export async function action({ request }: ActionFunctionArgs) {)}+ case 'preview-website-addon': {+ const quantity = Number(formData.get('quantity'))+ const billingInterval = formData.get('billingInterval')?.toString()++ const result = await serverFetch<WebsiteAddonPreview>(+ request,+ 'user/addons/websites/preview',+ {+ method: 'POST',+ body: { quantity, billingInterval },+ },+ )++ if (result.error) {+ return data<UserSettingsActionData>(+ { intent, error: result.error as string },+ { status: 400 },+ )+ }++ return data<UserSettingsActionData>(+ { intent, success: true, data: result.data },+ { headers: createHeadersWithCookies(result.cookies) },+ )+ }++ case 'update-website-addon': {+ const quantity = Number(formData.get('quantity'))+ const billingInterval = formData.get('billingInterval')?.toString()++ const result = await serverFetch<User>(+ request,+ 'user/addons/websites',+ {+ method: 'PUT',+ body: { quantity, billingInterval },+ },+ )++ if (result.error) {+ return data<UserSettingsActionData>(+ { intent, error: result.error as string },+ { status: 400 },+ )+ }++ return data<UserSettingsActionData>(+ { intent, success: true, user: result.data as User },+ { headers: createHeadersWithCookies(result.cookies) },+ )+ }+case 'accept-project-share': {const shareId = formData.get('shareId')?.toString()diff --git a/web/app/ui/Select.tsx b/web/app/ui/Select.tsxindex 072870d43..2db4ad435 100644--- a/web/app/ui/Select.tsx+++ b/web/app/ui/Select.tsx@@ -32,6 +32,7 @@ interface SelectProps<T> {onSelect: (item: T) => voidselectedItem?: Twrap?: boolean+ disabled?: boolean}function Select<T>({@@ -54,6 +55,7 @@ function Select<T>({selectedItem,hintClassName,wrap,+ disabled,}: SelectProps<T>) {const isItemSelected = (item: T): boolean => {if (!selectedItem) return false@@ -76,6 +78,7 @@ function Select<T>({id={id || ''}value={selectedItem}onChange={onSelect}+ disabled={disabled}>{({ open }) => (<>@@ -111,6 +114,8 @@ function Select<T>({aria-describedby={hintId}className={cx('relative w-full rounded-md border-0 bg-white py-2 pr-9 pl-3 text-left text-sm font-medium text-gray-900 ring-1 ring-gray-300 transition-[background-color,box-shadow] duration-150 ease-out ring-inset hover:ring-gray-400 focus-visible:ring-2 focus-visible:ring-slate-900 focus-visible:outline-hidden dark:bg-slate-950 dark:text-gray-50 dark:ring-slate-700/80 dark:hover:ring-slate-600 dark:focus-visible:ring-slate-300',+ disabled &&+ 'cursor-not-allowed opacity-60 hover:ring-gray-300 dark:hover:ring-slate-700/80',buttonClassName,)}>diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 6c2a16fdf..0c0337358 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -2898,7 +2898,44 @@"sessionReplayAddonTitle": "Additional session replays","sessionReplayAddonDescription": "Add {{amount}} recorded sessions per month. Session replay pricing is temporary while the feature is finalised.","activeAddonAmount": "{{amount}} active",- "requestAddon": "Request add-on"+ "requestAddon": "Request add-on",+ "comingSoon": "Coming soon",+ "websiteAddonUpdated": "Website add-on updated.",+ "websiteAddonRequiresSubscription": "You need an active paid subscription before you can buy website add-ons.",+ "websiteAddonUnavailableDuringTrial": "Website add-ons become available after your trial ends and the paid subscription starts.",+ "websiteAddonUnavailableCancelled": "Website add-ons are unavailable while your subscription is scheduled for cancellation.",+ "websiteAddonUnavailableSuspended": "Website add-ons are unavailable while billing is suspended. Update your payment details first.",+ "websiteAddonLegacyManaged": "This account has a legacy website add-on. Contact support to move it to self-serve billing.",+ "legacyWebsiteAddon": "This account has a legacy website add-on. Contact support to move it to self-serve billing.",+ "invalidWebsiteAddonQuantity": "Choose website add-ons from 0 to 1,000 extra websites in steps of 50.",+ "invalidWebsiteAddonBillingInterval": "Choose monthly or yearly billing for this add-on.",+ "websiteAddonUsage": "Usage",+ "websiteAddonIncluded": "Included",+ "websiteAddonPurchased": "Purchased extra",+ "websiteAddonActive": "Active",+ "websiteAddonPending": "Scheduled",+ "websiteAddonPastDue": "Past due",+ "websiteAddonLegacy": "Legacy",+ "websiteAddonQuantity": "Extra websites",+ "websiteAddonBillingInterval": "Billing interval",+ "websiteAddonMonthly": "Monthly",+ "websiteAddonYearly": "Yearly",+ "websiteAddonYearlyDiscount": "Yearly billing is 10x monthly, so two months are free.",+ "websiteAddonDecreaseQuantity": "Decrease extra websites",+ "websiteAddonIncreaseQuantity": "Increase extra websites",+ "extraWebsitesAmount": "+{{amount}} websites",+ "noAdditionalWebsites": "No additional websites",+ "websiteAddonDueNow": "Due now",+ "websiteAddonRecurring": "Recurring",+ "websiteAddonNextCharge": "Next charge",+ "websiteAddonEffectiveOn": "Effective on",+ "websiteAddonNoImmediateCharge": "No immediate charge",+ "websiteAddonNoNextCharge": "No next charge",+ "websiteAddonNextRenewal": "the next renewal",+ "websiteAddonPendingChange": "A scheduled add-on change will take effect on {{date}}. Select a new quantity or update the current settings to replace it.",+ "websiteAddonSave": "Update add-on",+ "websiteAddonMaxSelfServe": "Self-serve add-ons are capped at 1,000 extra websites. Contact support for more.",+ "sessionReplayAddonComingSoon": "Self-serve session replay add-ons are coming soon."},"modals": {"paidFeature": {