📈 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
Replay addons
Blue Mousea5892962886c
diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.tsindex e967284d5..d14e8ec44 100644--- a/backend/apps/cloud/src/project/project.service.ts+++ b/backend/apps/cloud/src/project/project.service.ts@@ -210,6 +210,7 @@ export class ProjectService {'admin.planCode','admin.planType','admin.entitlementOverrides',+ 'admin.addonOverrides','organisation.id','organisationMembers.role','organisationMembers.confirmed',@@ -1028,6 +1029,50 @@ export class ProjectService {return info as IUsageInfoRedis}+ async getMonthlySessionReplayUsage(uid: string): Promise<number> {+ const projects = await this.find({+ where: {+ admin: { id: uid },+ },+ select: ['id'],+ })++ if (_isEmpty(projects)) {+ return 0+ }++ const monthStart = dayjs+ .utc()+ .startOf('month')+ .format('YYYY-MM-DD HH:mm:ss')+ const CHUNK_SIZE = 5000+ const pids = _map(projects, 'id')+ let usage = 0++ for (let i = 0; i < pids.length; i += CHUNK_SIZE) {+ const pidChunk = pids.slice(i, i + CHUNK_SIZE)++ const { data } = await clickhouse+ .query({+ query: `+ SELECT uniqExact(concat(toString(psid), ':', replayId)) AS usage+ FROM session_replay_chunks+ WHERE pid IN {pids:Array(FixedString(12))}+ AND created >= {monthStart:DateTime}+ `,+ query_params: {+ pids: pidChunk,+ monthStart,+ },+ })+ .then((resultSet) => resultSet.json<{ usage: number }>())++ usage += Number(data[0]?.usage) || 0+ }++ return usage+ }+async clearProjectsRedisCache(uid: string): Promise<void> {const projects = await this.find({where: {diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.tsindex 16d10f5f9..b7ce82bea 100644--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts@@ -704,7 +704,10 @@ export class TaskManagerService {async (pid, index) => {const projectData = data[pid] || {}const topCountry = topCountries[pid]?.cc || null- const errorStats = errorCounts[pid] || { count: 0, uniqueErrors: 0 }+ const errorStats = errorCounts[pid] || {+ count: 0,+ uniqueErrors: 0,+ }const pidTotalSessions = totalSessions[pid] || 0const projectGoals = await this.goalService.findByProject(pid)@@ -1449,7 +1452,10 @@ export class TaskManagerService {@Cron(CronExpression.EVERY_HOUR)async processWebsiteAddonRenewals() {- await this.userService.processDueWebsiteAddonRenewals().catch((reason) => {+ await Promise.all([+ this.userService.processDueWebsiteAddonRenewals(),+ this.userService.processDueSessionReplayAddonRenewals(),+ ]).catch((reason) => {this.logger.error(`[CRON WORKER](processWebsiteAddonRenewals) Error occured: ${reason}`,)@@ -1473,6 +1479,9 @@ export class TaskManagerService {await this.userService.clearWebsiteAddonsForCancelledSubscription(user.id,)+ await this.userService.clearSessionReplayAddonsForCancelledSubscription(+ 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.tsindex 92fe24dd1..9331adfd1 100644--- a/backend/apps/cloud/src/user/dto/update-website-addon.dto.ts+++ b/backend/apps/cloud/src/user/dto/update-website-addon.dto.ts@@ -14,3 +14,15 @@ export class UpdateWebsiteAddonDTO {@IsIn([BillingFrequency.Monthly, BillingFrequency.Yearly])billingInterval: BillingFrequency}++export class UpdateSessionReplayAddonDTO {+ @ApiProperty({ example: 5000, minimum: 0, maximum: 100000 })+ @IsInt()+ @Min(0)+ @Max(100000)+ 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.entity.ts b/backend/apps/cloud/src/user/entities/user-addon.entity.tsindex a52a7157b..4836a1577 100644--- a/backend/apps/cloud/src/user/entities/user-addon.entity.ts+++ b/backend/apps/cloud/src/user/entities/user-addon.entity.ts@@ -13,6 +13,7 @@ import { User, BillingFrequency } from './user.entity'export enum UserAddonCode {websites = 'websites',+ sessionReplays = 'session_replays',}export enum UserAddonStatus {diff --git a/backend/apps/cloud/src/user/entities/user.entity.ts b/backend/apps/cloud/src/user/entities/user.entity.tsindex a64e60a65..ef6d1cfdf 100644--- a/backend/apps/cloud/src/user/entities/user.entity.ts+++ b/backend/apps/cloud/src/user/entities/user.entity.ts@@ -191,15 +191,18 @@ export const getSessionReplayQuota = (planCode?: PlanCode | nullplanType?: PlanType | nullentitlementOverrides?: Record<string, unknown> | null+ addonOverrides?: Record<string, unknown> | null} | null,): number | 'custom' => {const replayOverride = getNumericLimitOverride(user?.entitlementOverrides,'sessionReplaysIncluded',)+ const replayAddons =+ getNumericLimitOverride(user?.addonOverrides, 'sessionReplays') || 0if (typeof replayOverride === 'number') {- return replayOverride+ return replayOverride + replayAddons}const effectivePlanType = getEffectivePlanType(user)@@ -210,10 +213,13 @@ export const getSessionReplayQuota = (}if (entitlements.sessionReplaysIncluded === 'byEventTier') {- return PLUS_SESSION_REPLAY_QUOTA[user?.planCode || PlanCode.none] || 0+ return (+ (PLUS_SESSION_REPLAY_QUOTA[user?.planCode || PlanCode.none] || 0) ++ replayAddons+ )}- return entitlements.sessionReplaysIncluded+ return entitlements.sessionReplaysIncluded + replayAddons}export const getSessionReplayRetentionEntitlement = (diff --git a/backend/apps/cloud/src/user/interfaces/usage-info.ts b/backend/apps/cloud/src/user/interfaces/usage-info.tsindex b7446ae85..080fe26d4 100644--- a/backend/apps/cloud/src/user/interfaces/usage-info.ts+++ b/backend/apps/cloud/src/user/interfaces/usage-info.ts@@ -15,5 +15,6 @@ export interface IUsageInfoBreakdown extends IUsageInfoRedis {export interface IUsageInfo extends IUsageInfoBreakdown {projects: number+ sessionReplays: numberlast30Days: IUsageInfoBreakdown}diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.tsindex 41a7f9c07..26e6eccf1 100644--- a/backend/apps/cloud/src/user/user.controller.ts+++ b/backend/apps/cloud/src/user/user.controller.ts@@ -65,7 +65,10 @@ 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 {+ UpdateSessionReplayAddonDTO,+ UpdateWebsiteAddonDTO,+} from './dto/update-website-addon.dto'import { checkRateLimit, getIPDetails, getIPFromHeaders } from '../common/utils'import {IUsageInfo,@@ -142,7 +145,10 @@ export class UserController {const sanitizedUser = this.userService.omitSensitiveData(user,- ) as Partial<User> & { websiteAddon?: unknown }+ ) as Partial<User> & {+ websiteAddon?: unknown+ sessionReplayAddon?: unknown+ }sanitizedUser.sharedProjects = sharedProjectssanitizedUser.organisationMemberships = organisationMemberships@@ -150,6 +156,8 @@ export class UserController {uid,user,)+ sanitizedUser.sessionReplayAddon =+ await this.userService.getSessionReplayAddonSummary(uid, user)return {user: sanitizedUser,@@ -643,7 +651,9 @@ export class UserController {)const url = `${isDevelopment ? request.headers.origin : PRODUCTION_ORIGIN}/verify/${token.id}`- await this.userService.update(id, { emailRequests: 1 + user.emailRequests })+ await this.userService.update(id, {+ emailRequests: 1 + user.emailRequests,+ })await this.mailerService.sendEmail(user.email, LetterTemplate.SignUp, {url,})@@ -837,15 +847,18 @@ export class UserController {@Get('usageinfo')async getUsageInfo(@CurrentUserId() uid: string): Promise<IUsageInfo> {- const [rawInfo, rawLast30DaysInfo, projects] = await Promise.all([- this.projectService.getRedisUsageInfo(uid),- this.projectService.getRedisUsageInfo(uid, 'last30Days'),- this.projectService.countByAdminId(uid),- ])+ const [rawInfo, rawLast30DaysInfo, projects, sessionReplays] =+ await Promise.all([+ this.projectService.getRedisUsageInfo(uid),+ this.projectService.getRedisUsageInfo(uid, 'last30Days'),+ this.projectService.countByAdminId(uid),+ this.projectService.getMonthlySessionReplayUsage(uid),+ ])return {...formatUsageInfo(rawInfo),projects,+ sessionReplays,last30Days: formatUsageInfo(rawLast30DaysInfo),}}@@ -923,6 +936,39 @@ export class UserController {return user}+ @ApiBearerAuth()+ @Post('addons/session-replays/preview')+ async previewSessionReplayAddon(+ @CurrentUserId() id: string,+ @Body() body: UpdateSessionReplayAddonDTO,+ ): Promise<any> {+ this.logger.log({ body, id }, 'POST /addons/session-replays/preview')++ return this.userService.previewSessionReplayAddon(+ id,+ body.quantity,+ body.billingInterval,+ )+ }++ @ApiBearerAuth()+ @Put('addons/session-replays')+ async updateSessionReplayAddon(+ @CurrentUserId() id: string,+ @Body() body: UpdateSessionReplayAddonDTO,+ ): Promise<Partial<User>> {+ this.logger.log({ body, id }, 'PUT /addons/session-replays')++ const user = await this.userService.updateSessionReplayAddon(+ 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.service.ts b/backend/apps/cloud/src/user/user.service.tsindex fc298f65c..e6851458c 100644--- a/backend/apps/cloud/src/user/user.service.ts+++ b/backend/apps/cloud/src/user/user.service.ts@@ -130,6 +130,13 @@ const WEBSITE_ADDON_MONTHLY_PRICE: Record<string, number> = {EUR: 7,GBP: 6,}+const SESSION_REPLAY_ADDON_BUNDLE_SIZE = 5000+const SESSION_REPLAY_ADDON_MAX_QUANTITY = 100000+const SESSION_REPLAY_ADDON_MONTHLY_PRICE: Record<string, number> = {+ USD: 19,+ EUR: 17,+ GBP: 15,+}const WEBSITE_ADDON_CURRENCIES = ['USD', 'EUR', 'GBP']type WebsiteAddonChangeType =@@ -162,6 +169,27 @@ interface WebsiteAddonPreview {status: UserAddonStatus | null}+interface SessionReplayAddonPreview {+ code: UserAddonCode.sessionReplays+ 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+ includedSessionReplays: number | 'custom'+ totalSessionReplays: number | 'custom'+ activeExtraSessionReplays: number+ changeType: WebsiteAddonChangeType+ isLegacy: boolean+ status: UserAddonStatus | null+}+interface WebsiteAddonSummary {code: UserAddonCode.websitesquantity: number@@ -177,6 +205,21 @@ interface WebsiteAddonSummary {failedChargeAttempts: number}+interface SessionReplayAddonSummary {+ code: UserAddonCode.sessionReplays+ quantity: number+ pendingQuantity: number | null+ billingInterval: BillingFrequency | null+ pendingBillingInterval: BillingFrequency | null+ currency: string | null+ status: UserAddonStatus | 'legacy' | null+ periodEnd: string | null+ nextChargeDate: string | null+ recurringAmount: number | null+ isLegacy: boolean+ failedChargeAttempts: number+}+type CdnFileResponse =| string| {@@ -302,6 +345,10 @@ export class UserService {)}+ private getSessionReplayAddonOverrideQuantity(user: Partial<User>): number {+ return this.getNumericOverride(user?.addonOverrides, 'sessionReplays') || 0+ }+private getMoneyValue(value?: string | null): number | null {if (value === null || value === undefined) {return null@@ -337,13 +384,21 @@ export class UserService {private async getLockedWebsiteAddon(manager: EntityManager,userId: string,+ ): Promise<UserAddon | null> {+ return this.getLockedAddon(manager, userId, UserAddonCode.websites)+ }++ private async getLockedAddon(+ manager: EntityManager,+ userId: string,+ code: UserAddonCode,): Promise<UserAddon | null> {return manager.getRepository(UserAddon).createQueryBuilder('addon').setLock('pessimistic_write').where('addon.userId = :userId', { userId })- .andWhere('addon.code = :code', { code: UserAddonCode.websites })+ .andWhere('addon.code = :code', { code }).getOne()}@@ -370,6 +425,26 @@ export class UserService {)}+ private getIncludedSessionReplayLimit(+ user: Partial<User>,+ ): number | 'custom' {+ const replayOverride = this.getNumericOverride(+ user?.entitlementOverrides,+ 'sessionReplaysIncluded',+ )++ if (typeof replayOverride === 'number') {+ return replayOverride+ }++ const addonQuantity = this.getSessionReplayAddonOverrideQuantity(user)+ const totalQuota = getSessionReplayQuota(user)++ return totalQuota === 'custom'+ ? totalQuota+ : Math.max(0, totalQuota - addonQuantity)+ }+private getWebsiteAddonCurrency(user: User): string {return typeof user.tierCurrency === 'string' &&WEBSITE_ADDON_CURRENCIES.includes(user.tierCurrency)@@ -395,6 +470,21 @@ export class UserService {return this.roundMoney(bundles * monthlyPrice * intervalMultiplier)}+ private getSessionReplayAddonAmount(+ quantity: number,+ billingInterval: BillingFrequency,+ currency: string,+ ): number {+ const monthlyPrice =+ SESSION_REPLAY_ADDON_MONTHLY_PRICE[currency] ||+ SESSION_REPLAY_ADDON_MONTHLY_PRICE.USD+ const bundles = quantity / SESSION_REPLAY_ADDON_BUNDLE_SIZE+ const intervalMultiplier =+ billingInterval === BillingFrequency.Yearly ? 10 : 1++ return this.roundMoney(bundles * monthlyPrice * intervalMultiplier)+ }+private getWebsiteAddonPeriodEnd(from: Date,billingInterval: BillingFrequency,@@ -457,6 +547,58 @@ export class UserService {}}+ private validateSessionReplayAddonSelection(+ quantity: number,+ billingInterval: BillingFrequency,+ ) {+ if (+ !Number.isInteger(quantity) ||+ quantity < 0 ||+ quantity > SESSION_REPLAY_ADDON_MAX_QUANTITY ||+ quantity % SESSION_REPLAY_ADDON_BUNDLE_SIZE !== 0+ ) {+ throw new BadRequestException('invalidSessionReplayAddonQuantity')+ }++ if (+ ![BillingFrequency.Monthly, BillingFrequency.Yearly].includes(+ billingInterval,+ )+ ) {+ throw new BadRequestException('invalidSessionReplayAddonBillingInterval')+ }+ }++ private validateSessionReplayAddonEligibility(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('sessionReplayAddonRequiresSubscription')+ }++ if (isTrialingPaidPlan) {+ throw new BadRequestException('sessionReplayAddonUnavailableDuringTrial')+ }++ if (user.cancellationEffectiveDate) {+ throw new BadRequestException('sessionReplayAddonUnavailableCancelled')+ }++ if (user.isAccountBillingSuspended) {+ throw new BadRequestException('sessionReplayAddonUnavailableSuspended')+ }++ if (getSessionReplayQuota(user) === 'custom') {+ throw new BadRequestException('sessionReplayAddonUnavailableCustom')+ }+ }+private async getWebsiteAddon(userId: string): Promise<UserAddon | null> {return this.userAddonRepository.findOne({where: {@@ -466,6 +608,17 @@ export class UserService {})}+ private async getSessionReplayAddon(+ userId: string,+ ): Promise<UserAddon | null> {+ return this.userAddonRepository.findOne({+ where: {+ userId,+ code: UserAddonCode.sessionReplays,+ },+ })+ }+private getProratedWebsiteAddonAmount(addon: UserAddon,addedQuantity: number,@@ -494,6 +647,34 @@ export class UserService {return this.roundMoney(fullAmount * Math.min(1, remainingMs / totalMs))}+ private getProratedSessionReplayAddonAmount(+ addon: UserAddon,+ addedQuantity: number,+ currency: string,+ ): number {+ const fullAmount = this.getSessionReplayAddonAmount(+ 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,@@ -627,6 +808,156 @@ export class UserService {return this.buildWebsiteAddonPreview(user, addon, quantity, billingInterval)}+ private buildSessionReplayAddonPreview(+ user: User,+ addon: UserAddon | null,+ quantity: number,+ billingInterval: BillingFrequency,+ ): SessionReplayAddonPreview {+ const legacyQuantity = addon+ ? 0+ : this.getSessionReplayAddonOverrideQuantity(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 includedSessionReplays = this.getIncludedSessionReplayLimit(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.sessionReplays,+ quantity: currentQuantity,+ currentQuantity,+ pendingQuantity: null,+ billingInterval,+ currentBillingInterval: null,+ pendingBillingInterval: null,+ currency,+ dueNow: 0,+ recurringAmount: 0,+ nextChargeDate: null,+ effectiveDate: null,+ includedSessionReplays,+ totalSessionReplays:+ includedSessionReplays === 'custom'+ ? includedSessionReplays+ : includedSessionReplays + currentQuantity,+ activeExtraSessionReplays: 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.getSessionReplayAddonAmount(+ quantity,+ billingInterval,+ currency,+ )+ }+ } else if (quantity > currentQuantity) {+ changeType = 'increase'+ dueNow = this.getProratedSessionReplayAddonAmount(+ 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 displayedExtraSessionReplays =+ changeType === 'decrease' || changeType === 'cancel'+ ? currentQuantity+ : quantity++ return {+ code: UserAddonCode.sessionReplays,+ quantity,+ currentQuantity,+ pendingQuantity: addon?.pendingQuantity ?? null,+ billingInterval,+ currentBillingInterval,+ pendingBillingInterval: addon?.pendingBillingInterval ?? null,+ currency,+ dueNow,+ recurringAmount: this.getSessionReplayAddonAmount(+ quantity,+ billingInterval,+ currency,+ ),+ nextChargeDate: this.formatAddonDate(nextChargeDate),+ effectiveDate,+ includedSessionReplays,+ totalSessionReplays:+ includedSessionReplays === 'custom'+ ? includedSessionReplays+ : includedSessionReplays + displayedExtraSessionReplays,+ activeExtraSessionReplays: currentQuantity,+ changeType,+ isLegacy,+ status: addon?.status || null,+ }+ }++ async previewSessionReplayAddon(+ userId: string,+ quantity: number,+ billingInterval: BillingFrequency,+ ): Promise<SessionReplayAddonPreview> {+ this.validateSessionReplayAddonSelection(quantity, billingInterval)++ const user = await this.findOne({ where: { id: userId } })+ if (!user) {+ throw new BadRequestException('User not found')+ }++ this.validateSessionReplayAddonEligibility(user)++ const addon = await this.getSessionReplayAddon(userId)+ return this.buildSessionReplayAddonPreview(+ user,+ addon,+ quantity,+ billingInterval,+ )+ }+private async syncWebsiteAddonEntitlements(user: User,quantity: number,@@ -671,12 +1002,54 @@ export class UserService {await this.syncWebsiteAddonEntitlements(user, addonQuantity)}- private getPaddleErrorMessage(data: any): string {- if (typeof data?.error === 'string') {- return data.error- }-- if (typeof data?.response?.message === 'string') {+ private async syncSessionReplayAddonEntitlements(+ user: User,+ quantity: number,+ manager?: EntityManager,+ ): Promise<void> {+ const addonOverrides = { ...(user.addonOverrides || {}) }++ if (quantity > 0) {+ addonOverrides.sessionReplays = quantity+ } else {+ delete addonOverrides.sessionReplays+ }++ const update = {+ addonOverrides: Object.keys(addonOverrides).length+ ? addonOverrides+ : null,+ }++ if (manager) {+ await manager.getRepository(User).update(user.id, update)+ return+ }++ await this.update(user.id, update)+ }++ async refreshSessionReplayAddonEntitlements(userId: string): Promise<void> {+ const user = await this.findOne({ where: { id: userId } })+ if (!user) {+ return+ }++ const addon = await this.getSessionReplayAddon(userId)+ const addonQuantity =+ addon && addon.status !== UserAddonStatus.cancelled+ ? addon.quantity+ : this.getSessionReplayAddonOverrideQuantity(user)++ await this.syncSessionReplayAddonEntitlements(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}@@ -875,6 +1248,164 @@ export class UserService {}}+ private buildSessionReplayAddonChargeKey(+ addon: UserAddon,+ user: User,+ kind: UserAddonChargeKind,+ amount: number,+ quantity: number,+ previousQuantity: number | null,+ billingInterval: BillingFrequency,+ periodStart: Date | null,+ periodEnd: Date | null,+ ): string {+ return [+ 'session-replay-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 chargeSessionReplayAddon(+ addon: UserAddon,+ user: User,+ kind: UserAddonChargeKind,+ amount: number,+ quantity: number,+ previousQuantity: number | null,+ billingInterval: BillingFrequency,+ periodStart: Date | null,+ periodEnd: Date | null,+ manager?: EntityManager,+ ): Promise<UserAddonCharge> {+ const chargeRepository = this.getAddonChargeRepository(manager)+ const chargeName = `${quantity.toLocaleString()} additional session replays for Swetrix (${billingInterval})`+ const idempotencyKey = this.buildSessionReplayAddonChargeKey(+ 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('sessionReplayAddonChargeInProgress')+ }++ 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('sessionReplayAddonChargeInProgress')+ }+ }++ if (!charge) {+ throw new InternalServerErrorException('Unable to create add-on charge')+ }++ try {+ const response = await this.createPaddleOneOffCharge(+ user.subID,+ amount,+ chargeName,+ )++ const update = {+ 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,+ failureReason: null,+ }++ await chargeRepository.update(charge.id, update)++ return {+ ...charge,+ ...update,+ } as UserAddonCharge+ } catch (reason) {+ await chargeRepository.update(charge.id, {+ status: UserAddonChargeStatus.failed,+ failureReason:+ reason instanceof Error ? reason.message : 'Paddle charge failed',+ })++ throw reason+ }+ }+async getWebsiteAddonSummary(userId: string,user?: User,@@ -935,6 +1466,67 @@ export class UserService {} as Partial<User>}+ async getSessionReplayAddonSummary(+ userId: string,+ user?: User,+ ): Promise<SessionReplayAddonSummary | null> {+ const [addon, resolvedUser] = await Promise.all([+ this.getSessionReplayAddon(userId),+ user ? Promise.resolve(user) : this.findOne({ where: { id: userId } }),+ ])++ if (addon) {+ return {+ code: UserAddonCode.sessionReplays,+ 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),+ recurringAmount: this.getMoneyValue(addon.recurringAmount),+ isLegacy: false,+ failedChargeAttempts: addon.failedChargeAttempts,+ }+ }++ const legacyQuantity = resolvedUser+ ? this.getSessionReplayAddonOverrideQuantity(resolvedUser)+ : 0++ if (!legacyQuantity) {+ return null+ }++ return {+ code: UserAddonCode.sessionReplays,+ quantity: legacyQuantity,+ pendingQuantity: null,+ billingInterval: null,+ pendingBillingInterval: null,+ currency: resolvedUser?.tierCurrency || null,+ status: 'legacy',+ periodEnd: null,+ nextChargeDate: null,+ recurringAmount: null,+ isLegacy: true,+ failedChargeAttempts: 0,+ }+ }++ async getUserWithAddonSummaries(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),+ sessionReplayAddon: await this.getSessionReplayAddonSummary(userId, user),+ } as Partial<User>+ }+async updateWebsiteAddon(userId: string,quantity: number,@@ -1082,20 +1674,174 @@ export class UserService {}})- return this.getUserWithWebsiteAddonSummary(userId)+ return this.getUserWithAddonSummaries(userId)}- private async cancelWebsiteAddonNow(addon: UserAddon): Promise<void> {- await this.userAddonRepository.update(addon.id, {- quantity: 0,- pendingQuantity: null,- pendingBillingInterval: null,- recurringAmount: null,- nextChargeDate: null,- status: UserAddonStatus.cancelled,- failedChargeAttempts: 0,- lastChargeFailedAt: null,- cancelledAt: new Date(),+ async updateSessionReplayAddon(+ userId: string,+ quantity: number,+ billingInterval: BillingFrequency,+ ): Promise<Partial<User>> {+ this.validateSessionReplayAddonSelection(quantity, billingInterval)++ await this.usersRepository.manager.transaction(async (manager) => {+ const user = await this.getLockedUser(manager, userId)+ if (!user) {+ throw new BadRequestException('User not found')+ }++ this.validateSessionReplayAddonEligibility(user)++ const addonRepository = manager.getRepository(UserAddon)+ let addon = await this.getLockedAddon(+ manager,+ userId,+ UserAddonCode.sessionReplays,+ )+ if (!addon && this.getSessionReplayAddonOverrideQuantity(user) > 0) {+ throw new BadRequestException('legacySessionReplayAddon')+ }++ const preview = this.buildSessionReplayAddonPreview(+ user,+ addon,+ quantity,+ billingInterval,+ )++ if (preview.changeType === 'none') {+ if (+ addon &&+ (addon.pendingQuantity !== null ||+ addon.pendingBillingInterval !== null)+ ) {+ await addonRepository.update(addon.id, {+ pendingQuantity: null,+ pendingBillingInterval: null,+ })+ }++ return+ }++ const now = new Date()++ if (!addon) {+ addon = await addonRepository.save(+ addonRepository.create({+ userId,+ code: UserAddonCode.sessionReplays,+ 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+ 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.chargeSessionReplayAddon(+ addon,+ user,+ isInactiveAddon+ ? UserAddonChargeKind.initial+ : UserAddonChargeKind.prorated,+ preview.dueNow,+ quantity,+ currentQuantity,+ isInactiveAddon ? billingInterval : addon.billingInterval,+ chargePeriodStart,+ chargePeriodEnd,+ manager,+ )+ }++ if (isInactiveAddon) {+ const periodEnd = this.getWebsiteAddonPeriodEnd(now, billingInterval)+ const recurringAmount = this.getSessionReplayAddonAmount(+ quantity,+ billingInterval,+ preview.currency,+ )++ 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.syncSessionReplayAddonEntitlements(user, quantity, manager)+ } else if (quantity > currentQuantity) {+ const activeBillingInterval = addon.billingInterval+ const recurringAmount = this.getSessionReplayAddonAmount(+ quantity,+ activeBillingInterval,+ preview.currency,+ )++ 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.syncSessionReplayAddonEntitlements(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.getUserWithAddonSummaries(userId)+ }++ private async cancelWebsiteAddonNow(addon: UserAddon): Promise<void> {+ await this.userAddonRepository.update(addon.id, {+ quantity: 0,+ pendingQuantity: null,+ pendingBillingInterval: null,+ recurringAmount: null,+ nextChargeDate: null,+ status: UserAddonStatus.cancelled,+ failedChargeAttempts: 0,+ lastChargeFailedAt: null,+ cancelledAt: new Date(),})const user =@@ -1146,6 +1892,69 @@ export class UserService {}}+ private async cancelSessionReplayAddonNow(addon: UserAddon): Promise<void> {+ await this.userAddonRepository.update(addon.id, {+ quantity: 0,+ pendingQuantity: null,+ pendingBillingInterval: null,+ recurringAmount: 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.syncSessionReplayAddonEntitlements(user, 0)+ }+ }++ async scheduleSessionReplayAddonCancellation(+ userId: string,+ effectiveDate?: string | Date | null,+ ): Promise<void> {+ const addon = await this.getSessionReplayAddon(userId)+ if (!addon || addon.status === UserAddonStatus.cancelled) {+ return+ }++ const effective = effectiveDate ? dayjs.utc(effectiveDate) : null+ if (effective && effective.isBefore(dayjs.utc())) {+ await this.cancelSessionReplayAddonNow(addon)+ return+ }++ await this.userAddonRepository.update(addon.id, {+ pendingQuantity: 0,+ nextChargeDate:+ effective &&+ (!addon.nextChargeDate || effective.isBefore(addon.nextChargeDate))+ ? effective.toDate()+ : addon.nextChargeDate,+ })+ }++ async clearSessionReplayAddonsForCancelledSubscription(+ userId: string,+ ): Promise<void> {+ const addons = await this.userAddonRepository.find({+ where: { userId, code: UserAddonCode.sessionReplays },+ relations: ['user'],+ })++ await Promise.all(+ addons.map((addon) => this.cancelSessionReplayAddonNow(addon)),+ )++ const user = await this.findOne({ where: { id: userId } })+ if (user) {+ await this.syncSessionReplayAddonEntitlements(user, 0)+ }+ }+private async handleWebsiteAddonRenewalFailure(addon: UserAddon,reason: Error,@@ -1277,6 +2086,139 @@ export class UserService {}}+ private async handleSessionReplayAddonRenewalFailure(+ 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,+ recurringAmount: shouldRemoveCapacity ? null : addon.recurringAmount,+ 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.syncSessionReplayAddonEntitlements(user, 0)+ }+ }++ console.error('[ERROR] (processSessionReplayAddonRenewal):', reason)+ }++ private async processSessionReplayAddonRenewal(+ 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.sessionReplays,+ status: addon.status,+ nextChargeDate: LessThan(claimStartedAt),+ },+ {+ nextChargeDate: claimUntil,+ },+ )++ if (!claimResult.affected) {+ return+ }++ const user = addon.user++ if (!user || !user.subID || user.cancellationEffectiveDate) {+ await this.cancelSessionReplayAddonNow(addon)+ return+ }++ const targetQuantity = addon.pendingQuantity ?? addon.quantity+ const targetBillingInterval =+ addon.pendingBillingInterval || addon.billingInterval++ if (targetQuantity <= 0) {+ await this.cancelSessionReplayAddonNow(addon)+ return+ }++ const periodStart = dueDate+ const periodEnd = this.getWebsiteAddonPeriodEnd(+ periodStart,+ targetBillingInterval,+ )+ const amount = this.getSessionReplayAddonAmount(+ targetQuantity,+ targetBillingInterval,+ addon.currency,+ )++ try {+ const charge = await this.chargeSessionReplayAddon(+ addon,+ user,+ UserAddonChargeKind.renewal,+ amount,+ targetQuantity,+ addon.quantity,+ targetBillingInterval,+ periodStart,+ periodEnd,+ )+ const recurringAmount = this.getSessionReplayAddonAmount(+ 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.syncSessionReplayAddonEntitlements(user, targetQuantity)+ } catch (reason) {+ await this.handleSessionReplayAddonRenewalFailure(+ addon,+ reason instanceof Error ? reason : new Error(String(reason)),+ )+ }+ }+async processDueWebsiteAddonRenewals(): Promise<void> {const dueAddons = await this.userAddonRepository.find({where: [@@ -1299,6 +2241,28 @@ export class UserService {)}+ async processDueSessionReplayAddonRenewals(): Promise<void> {+ const dueAddons = await this.userAddonRepository.find({+ where: [+ {+ code: UserAddonCode.sessionReplays,+ status: UserAddonStatus.active,+ nextChargeDate: LessThan(new Date()),+ },+ {+ code: UserAddonCode.sessionReplays,+ status: UserAddonStatus.past_due,+ nextChargeDate: LessThan(new Date()),+ },+ ],+ relations: ['user'],+ })++ await Promise.allSettled(+ dueAddons.map((addon) => this.processSessionReplayAddonRenewal(addon)),+ )+ }+omitSensitiveData(user: Partial<User>): Partial<User> {const maxEventsCount = ACCOUNT_PLANS[user?.planCode]?.monthlyUsageLimit || 0const effectivePlanType = getEffectivePlanType(user)@@ -1312,6 +2276,8 @@ export class UserService {numberOverride(addonOverrides, 'websites') ||numberOverride(addonOverrides, 'additionalWebsites') ||0+ const purchasedSessionReplayAddons =+ numberOverride(addonOverrides, 'sessionReplays') || 0const websiteOverride = numberOverride(entitlementOverrides, 'websites')const apiOverride = numberOverride(entitlementOverrides,@@ -1346,6 +2312,7 @@ export class UserService {: user?.maxApiKeyRequestsPerHour,sessionReplaysIncluded,purchasedWebsiteAddons,+ purchasedSessionReplayAddons,}return _omit(enhancedUser, [@@ -1843,6 +2810,7 @@ export class UserService {await this.update(id, updateParams)await this.refreshWebsiteAddonEntitlements(id)+ await this.refreshSessionReplayAddonEntitlements(id)}async generatePayLink(diff --git a/backend/apps/cloud/src/webhook/webhook.controller.ts b/backend/apps/cloud/src/webhook/webhook.controller.tsindex e6df53c09..a3de3b824 100644--- a/backend/apps/cloud/src/webhook/webhook.controller.ts+++ b/backend/apps/cloud/src/webhook/webhook.controller.ts@@ -197,6 +197,9 @@ export class WebhookController {await this.userService.update(currentUser.id, updateParams)await this.userService.refreshWebsiteAddonEntitlements(currentUser.id)+ await this.userService.refreshSessionReplayAddonEntitlements(+ currentUser.id,+ )await this.projectService.clearProjectsRedisCache(currentUser.id)if (body.alert_name === 'subscription_created' && isTrialing) {@@ -239,6 +242,10 @@ export class WebhookController {user.id,cancellationEffectiveDate,)+ await this.userService.scheduleSessionReplayAddonCancellation(+ user.id,+ cancellationEffectiveDate,+ )}if (user?.email) {diff --git a/backend/migrations/mysql/2026_06_04_session_replay_addons.sql b/backend/migrations/mysql/2026_06_04_session_replay_addons.sqlnew file mode 100644index 000000000..b2fbc0d73--- /dev/null+++ b/backend/migrations/mysql/2026_06_04_session_replay_addons.sql@@ -0,0 +1,2 @@+ALTER TABLE `user_addon`+ MODIFY COLUMN `code` enum('websites','session_replays') NOT NULL;diff --git a/web/app/lib/models/Usageinfo.ts b/web/app/lib/models/Usageinfo.tsindex 7312a0daa..58b364c62 100644--- a/web/app/lib/models/Usageinfo.ts+++ b/web/app/lib/models/Usageinfo.ts@@ -12,5 +12,6 @@ interface UsageInfoBreakdown {export interface UsageInfo extends UsageInfoBreakdown {projects: number+ sessionReplays: numberlast30Days: UsageInfoBreakdown}diff --git a/web/app/lib/models/User.ts b/web/app/lib/models/User.tsindex 8892e75ac..cec386990 100644--- a/web/app/lib/models/User.ts+++ b/web/app/lib/models/User.ts@@ -50,6 +50,21 @@ interface WebsiteAddon {failedChargeAttempts: number}+interface SessionReplayAddon {+ code: 'session_replays'+ 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+ recurringAmount: number | null+ isLegacy: boolean+ failedChargeAttempts: number+}+enum OnboardingStep {LANGUAGE = 'language',WELCOME = 'welcome',@@ -104,7 +119,9 @@ export interface User {maxApiKeyRequestsPerHour: numbersessionReplaysIncluded: number | stringpurchasedWebsiteAddons: number+ purchasedSessionReplayAddons: numberwebsiteAddon?: WebsiteAddon | null+ sessionReplayAddon?: SessionReplayAddon | nulltierCurrency: 'USD' | 'EUR' | 'GBP' | nullshowLiveVisitorsInTitle: booleanreceiveLoginNotifications: booleandiff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsxindex 8a237fa44..d4e93c76a 100644--- a/web/app/pages/UserSettings/UserSettings.tsx+++ b/web/app/pages/UserSettings/UserSettings.tsx@@ -67,6 +67,7 @@ import PaidFeature from '~/modals/PaidFeature'import { useAuth } from '~/providers/AuthProvider'import { useTheme } from '~/providers/ThemeProvider'import type {+ SessionReplayAddonPreview,UserSettingsActionData,UserSettingsLoaderData,WebsiteAddonPreview,@@ -191,6 +192,7 @@ const DEFAULT_USAGE_INFO: UsageInfo = {customEvents: 0,captcha: 0,projects: 0,+ sessionReplays: 0,trafficPerc: 0,errorsPerc: 0,customEventsPerc: 0,@@ -212,6 +214,10 @@ const WEBSITE_ADDON_QUANTITY_OPTIONS = Array.from({ length: 21 },(_, index) => index * 50,)+const SESSION_REPLAY_ADDON_QUANTITY_OPTIONS = Array.from(+ { length: 21 },+ (_, index) => index * 5000,+)const formatBillingPrice = (amount: number) =>Number.isInteger(amount) ? amount.toFixed(0) : amount.toFixed(2)@@ -270,6 +276,8 @@ const UserSettings = () => {const metainfoFetcher = useFetcher<UserSettingsActionData>()const websiteAddonFetcher = useFetcher<UserSettingsActionData>()const websiteAddonPreviewFetcher = useFetcher<UserSettingsActionData>()+ const sessionReplayAddonFetcher = useFetcher<UserSettingsActionData>()+ const sessionReplayAddonPreviewFetcher = useFetcher<UserSettingsActionData>()// Stable submit handle for the preview fetcher. Effects must depend on this,// not on the fetcher object (whose identity changes on every state transition@@ -281,6 +289,15 @@ const UserSettings = () => {websiteAddonPreviewFetcherRef.current.submit(...args),[],)+ const sessionReplayAddonPreviewFetcherRef = useRef(+ sessionReplayAddonPreviewFetcher,+ )+ sessionReplayAddonPreviewFetcherRef.current = sessionReplayAddonPreviewFetcher+ const sessionReplayAddonPreviewSubmit = useCallback(+ (...args: Parameters<typeof sessionReplayAddonPreviewFetcher.submit>) =>+ sessionReplayAddonPreviewFetcherRef.current.submit(...args),+ [],+ )const [searchParams, setSearchParams] = useSearchParams()@@ -317,7 +334,9 @@ const UserSettings = () => {maxApiKeyRequestsPerHour = 0,sessionReplaysIncluded = 0,purchasedWebsiteAddons = 0,+ purchasedSessionReplayAddons = 0,websiteAddon,+ sessionReplayAddon,isAccountBillingSuspended,} = user || ({} as Partial<User>)@@ -359,6 +378,13 @@ const UserSettings = () => {const currentWebsiteAddonBillingInterval = (websiteAddon?.billingInterval ||'monthly') as BillingIntervalconst isWebsiteAddonLegacy = !!websiteAddon?.isLegacy+ const sessionReplayAddonBundle = ADDONS.sessionReplayBundles[0]+ const sessionReplayAddonPrice = sessionReplayAddonBundle.monthly[currencyCode]+ const activeSessionReplayAddonQuantity =+ sessionReplayAddon?.quantity ?? purchasedSessionReplayAddons+ const currentSessionReplayAddonBillingInterval =+ (sessionReplayAddon?.billingInterval || 'monthly') as BillingInterval+ const isSessionReplayAddonLegacy = !!sessionReplayAddon?.isLegacyconst isTrialEnded = (() => {if (!trialEndDate) {@@ -441,6 +467,31 @@ const UserSettings = () => {})}+ const onSessionReplayAddonModalOpen = () => {+ setSelectedSessionReplayAddonQuantity(activeSessionReplayAddonQuantity)+ setSelectedSessionReplayAddonBillingInterval(+ currentSessionReplayAddonBillingInterval,+ )+ setIsSessionReplayAddonModalOpened(true)+ }++ const onSessionReplayAddonModalClose = () => {+ if (isSessionReplayAddonSubmitting) return+ setIsSessionReplayAddonModalOpened(false)+ }++ const onSessionReplayAddonUpdate = () => {+ const formData = new FormData()+ formData.set('intent', 'update-session-replay-addon')+ formData.set('quantity', String(selectedSessionReplayAddonQuantity))+ formData.set('billingInterval', selectedSessionReplayAddonBillingInterval)++ sessionReplayAddonFetcher.submit(formData, {+ method: 'POST',+ action: '/user-settings',+ })+ }+const tabs = getTabs(t)const sidebarGroups = useMemo<SettingsTabGroup<SettingsTab>[]>(() => [@@ -505,6 +556,16 @@ const UserSettings = () => {] = useState<BillingInterval>(currentWebsiteAddonBillingInterval)const [isWebsiteAddonModalOpened, setIsWebsiteAddonModalOpened] =useState(false)+ const [+ selectedSessionReplayAddonQuantity,+ setSelectedSessionReplayAddonQuantity,+ ] = useState(activeSessionReplayAddonQuantity)+ const [+ selectedSessionReplayAddonBillingInterval,+ setSelectedSessionReplayAddonBillingInterval,+ ] = useState<BillingInterval>(currentSessionReplayAddonBillingInterval)+ const [isSessionReplayAddonModalOpened, setIsSessionReplayAddonModalOpened] =+ useState(false)const [showModal, setShowModal] = useState(false)const [showAPIDeleteModal, setShowAPIDeleteModal] = useState(false)const translatedFrequencies = useMemo(@@ -524,6 +585,8 @@ const UserSettings = () => {const lastHandledWebsiteAddonData = useRef<UserSettingsActionData | null>(null,)+ const lastHandledSessionReplayAddonData =+ useRef<UserSettingsActionData | null>(null)const shouldHandleFetcherData =useDeduplicateFetcherResponse<UserSettingsActionData>()const profileUpdateToast = useRef('profileSettings.updated')@@ -541,6 +604,8 @@ const UserSettings = () => {const isSubmitting = fetcher.state === 'submitting'const isWebsiteAddonSubmitting = websiteAddonFetcher.state !== 'idle'+ const isSessionReplayAddonSubmitting =+ sessionReplayAddonFetcher.state !== 'idle'const websiteAddonPreview = useMemo(() => {if (websiteAddonPreviewFetcher.data?.success &&@@ -646,6 +711,135 @@ const UserSettings = () => {const canSelectYearlyWebsiteAddon = user?.billingFrequency === 'yearly'const activeWebsiteAddonRecurringAmount =websiteAddon?.recurringAmount ?? null+ const sessionReplayAddonPreview = useMemo(() => {+ if (+ sessionReplayAddonPreviewFetcher.data?.success &&+ sessionReplayAddonPreviewFetcher.data.intent ===+ 'preview-session-replay-addon'+ ) {+ return sessionReplayAddonPreviewFetcher.data+ .data as SessionReplayAddonPreview+ }++ return null+ }, [sessionReplayAddonPreviewFetcher.data])+ const isSessionReplayAddonPreviewLoading =+ sessionReplayAddonPreviewFetcher.state !== 'idle'+ const currentSessionReplayAddonPreview = useMemo(() => {+ if (+ sessionReplayAddonPreview?.quantity ===+ selectedSessionReplayAddonQuantity &&+ sessionReplayAddonPreview.billingInterval ===+ selectedSessionReplayAddonBillingInterval+ ) {+ return sessionReplayAddonPreview+ }++ return null+ }, [+ sessionReplayAddonPreview,+ selectedSessionReplayAddonQuantity,+ selectedSessionReplayAddonBillingInterval,+ ])+ const hasPendingSessionReplayAddonChange =+ (sessionReplayAddon?.pendingQuantity ?? null) !== null ||+ (sessionReplayAddon?.pendingBillingInterval ?? null) !== null+ const sessionReplayAddonDisabledReason = useMemo(() => {+ if (isTrial) {+ return t('billing.sessionReplayAddonUnavailableDuringTrial')+ }++ if (!isSubscriber) {+ return t('billing.sessionReplayAddonRequiresSubscription')+ }++ if (cancellationEffectiveDate) {+ return t('billing.sessionReplayAddonUnavailableCancelled')+ }++ if (isAccountBillingSuspended) {+ return t('billing.sessionReplayAddonUnavailableSuspended')+ }++ if (sessionReplaysIncluded === 'custom') {+ return t('billing.sessionReplayAddonUnavailableCustom')+ }++ if (isSessionReplayAddonLegacy) {+ return t('billing.sessionReplayAddonLegacyManaged')+ }++ return null+ }, [+ isSubscriber,+ isTrial,+ cancellationEffectiveDate,+ isAccountBillingSuspended,+ sessionReplaysIncluded,+ isSessionReplayAddonLegacy,+ t,+ ])+ const isSessionReplayAddonDisabled = !!sessionReplayAddonDisabledReason+ const hasSessionReplayAddonChanges =+ selectedSessionReplayAddonQuantity !== activeSessionReplayAddonQuantity ||+ selectedSessionReplayAddonBillingInterval !==+ currentSessionReplayAddonBillingInterval ||+ hasPendingSessionReplayAddonChange+ const sessionReplayAddonPreviewError =+ sessionReplayAddonPreviewFetcher.data?.intent ===+ 'preview-session-replay-addon' &&+ sessionReplayAddonPreviewFetcher.data.error+ ? sessionReplayAddonPreviewFetcher.data.error+ : null+ const sessionReplayAddonPreviewErrorMessage = sessionReplayAddonPreviewError+ ? (() => {+ const billingTranslated = t(`billing.${sessionReplayAddonPreviewError}`)+ const apiTranslated = t(+ `apiNotifications.${sessionReplayAddonPreviewError}`,+ )++ return billingTranslated !== `billing.${sessionReplayAddonPreviewError}`+ ? billingTranslated+ : apiTranslated !==+ `apiNotifications.${sessionReplayAddonPreviewError}`+ ? apiTranslated+ : sessionReplayAddonPreviewError+ })()+ : null+ const includedSessionReplayLimit =+ currentSessionReplayAddonPreview?.includedSessionReplays ??+ (typeof sessionReplaysIncluded === 'number'+ ? Math.max(0, sessionReplaysIncluded - activeSessionReplayAddonQuantity)+ : sessionReplaysIncluded)+ const displayedSessionReplayLimit =+ currentSessionReplayAddonPreview?.totalSessionReplays ??+ sessionReplaysIncluded+ const displayedSessionReplayLimitLabel =+ typeof displayedSessionReplayLimit === 'number'+ ? displayedSessionReplayLimit.toLocaleString()+ : displayedSessionReplayLimit === 'custom'+ ? t('pricing.custom')+ : displayedSessionReplayLimit || '0'+ const displayedSessionReplayUsage =+ typeof displayedSessionReplayLimit === 'number' &&+ displayedSessionReplayLimit > 0+ ? Math.min(+ 100,+ _round(+ ((usageInfo.sessionReplays || 0) / displayedSessionReplayLimit) *+ 100,+ 2,+ ),+ )+ : 0+ const selectedSessionReplayAddonRecurringAmount =+ currentSessionReplayAddonPreview?.recurringAmount ??+ sessionReplayAddonPrice *+ (selectedSessionReplayAddonQuantity / sessionReplayAddonBundle.quantity) *+ (selectedSessionReplayAddonBillingInterval === 'yearly' ? 10 : 1)+ const canSelectYearlySessionReplayAddon = user?.billingFrequency === 'yearly'+ const activeSessionReplayAddonRecurringAmount =+ sessionReplayAddon?.recurringAmount ?? nullconst formatBillingDate = useCallback((date?: string | null) => {@@ -669,6 +863,17 @@ const UserSettings = () => {setSelectedWebsiteAddonBillingInterval(currentWebsiteAddonBillingInterval)}, [activeWebsiteAddonQuantity, currentWebsiteAddonBillingInterval, user?.id])+ useEffect(() => {+ setSelectedSessionReplayAddonQuantity(activeSessionReplayAddonQuantity)+ setSelectedSessionReplayAddonBillingInterval(+ currentSessionReplayAddonBillingInterval,+ )+ }, [+ activeSessionReplayAddonQuantity,+ currentSessionReplayAddonBillingInterval,+ user?.id,+ ])+useEffect(() => {if (activeTab !== TAB_MAPPING.BILLING ||@@ -700,6 +905,34 @@ const UserSettings = () => {websiteAddonPreviewSubmit,])+ useEffect(() => {+ if (+ activeTab !== TAB_MAPPING.BILLING ||+ !user?.id ||+ isSessionReplayAddonDisabled ||+ !isSessionReplayAddonModalOpened+ ) {+ return+ }++ const formData = new FormData()+ formData.set('intent', 'preview-session-replay-addon')+ formData.set('quantity', String(selectedSessionReplayAddonQuantity))+ formData.set('billingInterval', selectedSessionReplayAddonBillingInterval)+ sessionReplayAddonPreviewSubmit(formData, {+ method: 'POST',+ action: '/user-settings',+ })+ }, [+ activeTab,+ user?.id,+ isSessionReplayAddonDisabled,+ isSessionReplayAddonModalOpened,+ selectedSessionReplayAddonQuantity,+ selectedSessionReplayAddonBillingInterval,+ sessionReplayAddonPreviewSubmit,+ ])+useEffect(() => {if (fetcher.state !== 'idle' || !fetcher.data) returnif (!shouldHandleFetcherData(fetcher.data)) return@@ -840,6 +1073,55 @@ const UserSettings = () => {loadUser,])+ useEffect(() => {+ if (+ sessionReplayAddonFetcher.state !== 'idle' ||+ !sessionReplayAddonFetcher.data ||+ lastHandledSessionReplayAddonData.current ===+ sessionReplayAddonFetcher.data+ ) {+ return+ }++ lastHandledSessionReplayAddonData.current = sessionReplayAddonFetcher.data++ if (+ sessionReplayAddonFetcher.data.success &&+ sessionReplayAddonFetcher.data.intent === 'update-session-replay-addon' &&+ sessionReplayAddonFetcher.data.user+ ) {+ mergeUser(sessionReplayAddonFetcher.data.user)+ toast.success(t('billing.sessionReplayAddonUpdated'))+ loadUser()+ setIsSessionReplayAddonModalOpened(false)+ return+ }++ if (sessionReplayAddonFetcher.data.error) {+ const translated = t(+ `apiNotifications.${sessionReplayAddonFetcher.data.error}`,+ )+ const billingTranslated = t(+ `billing.${sessionReplayAddonFetcher.data.error}`,+ )++ toast.error(+ billingTranslated !== `billing.${sessionReplayAddonFetcher.data.error}`+ ? billingTranslated+ : translated !==+ `apiNotifications.${sessionReplayAddonFetcher.data.error}`+ ? translated+ : sessionReplayAddonFetcher.data.error,+ )+ }+ }, [+ sessionReplayAddonFetcher.data,+ sessionReplayAddonFetcher.state,+ mergeUser,+ t,+ loadUser,+ ])+const flushProfileAutosave = useCallback(() => {const autosave = pendingProfileAutosave.currentif (profileAutosaveFetcher.state !== 'idle' || !autosave) return@@ -1993,8 +2275,11 @@ const UserSettings = () => {weight='semibold'className='mt-1'>- {t('billing.perMonthQuota', {- amount: replayLimitLabel,+ {t('billing.sessionReplayUsageSummary', {+ used: (+ usageInfo.sessionReplays || 0+ ).toLocaleString(),+ total: replayLimitLabel,})}</Text><Text@@ -2003,7 +2288,12 @@ const UserSettings = () => {colour='secondary'className='mt-1'>- {t('billing.recordedSessionsQuota')}+ {activeSessionReplayAddonQuantity+ ? t('billing.addedSessionReplays', {+ amount:+ activeSessionReplayAddonQuantity.toLocaleString(),+ })+ : t('billing.recordedSessionsQuota')}</Text></div>@@ -2248,28 +2538,124 @@ const UserSettings = () => {</Button></div>- <div className='border-t border-gray-200 dark:border-slate-800 mt-4' />- <div className='pt-4'>+ <div className='mt-4 border-t border-gray-200 dark:border-slate-800' />+ <div className='max-w-2xl pt-4'><Text as='h4' size='base' weight='semibold'>- {t('billing.sessionReplayCapacityTitle')}+ {t('billing.sessionReplayAddonTitle')}</Text><Textas='p'size='sm'colour='secondary'- className='mt-1 max-w-xl'+ className='mt-1'>- {t('billing.sessionReplayCapacityDescription', {- quota: replayLimitLabel,+ {t('billing.sessionReplayAddonDescription', {+ amount: sessionReplayAddonBundle.quantity,+ bundlePrice: `${currency.symbol}${formatBillingPrice(+ sessionReplayAddonPrice,+ )}`,})}</Text>++ <div className='mt-5'>+ <div className='flex items-end justify-between gap-4'>+ <Text as='p' size='base' weight='bold'>+ {t('billing.sessionReplayUsageSummary', {+ used: (+ usageInfo.sessionReplays || 0+ ).toLocaleString(),+ total: displayedSessionReplayLimitLabel,+ })}+ </Text>+ <Text as='p' size='sm' colour='secondary'>+ {t('billing.xPercentUsed', {+ percentage: displayedSessionReplayUsage,+ })}+ </Text>+ </div>+ <div className='mt-2 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: `${displayedSessionReplayUsage}%`,+ }}+ />+ </div>+ <div className='mt-2 flex flex-wrap gap-x-4 gap-y-1'>+ <Text as='p' size='xs' colour='secondary'>+ {t('billing.sessionReplayAddonIncludedCount', {+ count:+ typeof includedSessionReplayLimit === 'number'+ ? includedSessionReplayLimit.toLocaleString()+ : t('pricing.custom'),+ })}+ </Text>+ <Text as='p' size='xs' colour='secondary'>+ {activeSessionReplayAddonQuantity+ ? t(+ 'billing.sessionReplayAddonPurchasedCount',+ {+ count:+ activeSessionReplayAddonQuantity.toLocaleString(),+ },+ )+ : t('billing.noAdditionalSessionReplays')}+ </Text>+ </div>+ </div>++ {activeSessionReplayAddonQuantity > 0 &&+ activeSessionReplayAddonRecurringAmount !== null ? (+ <Text+ as='p'+ size='sm'+ colour='secondary'+ className='mt-4'+ >+ {t('billing.sessionReplayAddonActiveSummary', {+ count:+ activeSessionReplayAddonQuantity.toLocaleString(),+ amount: `${currency.symbol}${formatBillingPrice(+ activeSessionReplayAddonRecurringAmount,+ )}`,+ interval: t(+ currentSessionReplayAddonBillingInterval ===+ 'yearly'+ ? 'pricing.intervals.year'+ : 'pricing.intervals.month',+ ),+ })}+ </Text>+ ) : null}++ {hasPendingSessionReplayAddonChange &&+ !sessionReplayAddonDisabledReason ? (+ <Alert variant='warning' className='mt-4'>+ {t('billing.sessionReplayAddonPendingChange', {+ date:+ formatBillingDate(+ sessionReplayAddon?.nextChargeDate ||+ sessionReplayAddon?.periodEnd,+ ) || t('billing.sessionReplayAddonNextRenewal'),+ })}+ </Alert>+ ) : null}++ {sessionReplayAddonDisabledReason ? (+ <Alert variant='info' className='mt-4'>+ {sessionReplayAddonDisabledReason}+ </Alert>+ ) : null}+<Button- variant='secondary'size='lg'className='mt-5 gap-1'- to={routes.billing_choose_plan}+ onClick={onSessionReplayAddonModalOpen}+ disabled={isSessionReplayAddonDisabled}>- {t('billing.sessionReplayCapacityCta')}+ {activeSessionReplayAddonQuantity > 0+ ? t('billing.sessionReplayAddonManage')+ : t('billing.sessionReplayAddonBuy')}<ArrowRightIcon className='size-4' /></Button></div>@@ -2660,6 +3046,184 @@ const UserSettings = () => {}/>+ <Modal+ onClose={onSessionReplayAddonModalClose}+ onSubmit={onSessionReplayAddonUpdate}+ submitText={t('billing.sessionReplayAddonSave')}+ closeText={t('common.cancel')}+ title={t('billing.sessionReplayAddonTitle')}+ size='medium'+ overflowVisible+ isLoading={isSessionReplayAddonSubmitting}+ submitDisabled={+ isSessionReplayAddonDisabled ||+ !hasSessionReplayAddonChanges ||+ isSessionReplayAddonPreviewLoading ||+ !!sessionReplayAddonPreviewError+ }+ isOpened={isSessionReplayAddonModalOpened}+ message={+ <div className='space-y-5 text-left'>+ <Text as='p' size='sm' colour='secondary'>+ {t('billing.sessionReplayAddonDescription', {+ amount: sessionReplayAddonBundle.quantity,+ bundlePrice: `${currency.symbol}${formatBillingPrice(+ sessionReplayAddonPrice,+ )}`,+ })}+ </Text>++ <Select<number>+ label={t('billing.sessionReplayAddonQuantity')}+ className='w-full'+ selectedItem={selectedSessionReplayAddonQuantity}+ items={SESSION_REPLAY_ADDON_QUANTITY_OPTIONS}+ onSelect={setSelectedSessionReplayAddonQuantity}+ title={+ selectedSessionReplayAddonQuantity+ ? t('billing.extraSessionReplaysAmount', {+ amount:+ selectedSessionReplayAddonQuantity.toLocaleString(),+ })+ : t('billing.noAdditionalSessionReplays')+ }+ labelExtractor={(amount) =>+ amount+ ? t('billing.extraSessionReplaysAmount', {+ amount: amount.toLocaleString(),+ })+ : t('billing.noAdditionalSessionReplays')+ }+ keyExtractor={(amount) => String(amount)}+ />++ <div>+ <Text as='p' size='sm' weight='medium' colour='primary'>+ {t('billing.sessionReplayAddonBillingInterval')}+ </Text>+ <div className='mt-1.5 grid grid-cols-2 gap-1 rounded-lg bg-gray-100 p-1 dark:bg-slate-900'>+ {(['monthly', 'yearly'] as BillingInterval[]).map(+ (interval) => {+ const isActive =+ selectedSessionReplayAddonBillingInterval === interval+ const isDisabled =+ interval === 'yearly' &&+ !canSelectYearlySessionReplayAddon++ return (+ <button+ key={interval}+ type='button'+ aria-pressed={isActive}+ disabled={isDisabled}+ onClick={() =>+ setSelectedSessionReplayAddonBillingInterval(interval)+ }+ className={cx(+ 'flex items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors',+ isActive+ ? 'bg-white text-slate-900 shadow-sm ring-1 ring-gray-200 dark:bg-slate-950 dark:text-gray-50 dark:ring-slate-700'+ : 'text-gray-600 hover:text-slate-900 dark:text-gray-400 dark:hover:text-gray-100',+ isDisabled &&+ 'cursor-not-allowed opacity-50 hover:text-gray-600 dark:hover:text-gray-400',+ )}+ >+ {interval === 'monthly'+ ? t('billing.sessionReplayAddonMonthly')+ : t('billing.sessionReplayAddonYearly')}+ {interval === 'yearly' ? (+ <span className='rounded-full bg-emerald-500/15 px-1.5 py-0.5 text-[11px] font-semibold text-emerald-700 dark:text-emerald-300'>+ {t('billing.sessionReplayAddonYearlySavings')}+ </span>+ ) : null}+ </button>+ )+ },+ )}+ </div>+ <Text as='p' size='xs' colour='secondary' className='mt-1.5'>+ {canSelectYearlySessionReplayAddon+ ? t('billing.sessionReplayAddonYearlyDiscount')+ : t('billing.sessionReplayAddonYearlyOnlyNote')}+ </Text>+ </div>++ {sessionReplayAddonPreviewErrorMessage ? (+ <Alert variant='error'>+ {sessionReplayAddonPreviewErrorMessage}+ </Alert>+ ) : null}++ <div className='rounded-lg bg-gray-50 p-4 ring-1 ring-gray-200 dark:bg-slate-900/60 dark:ring-slate-800'>+ {isSessionReplayAddonPreviewLoading &&+ !currentSessionReplayAddonPreview ? (+ <div className='flex justify-center py-2'>+ <Loader />+ </div>+ ) : currentSessionReplayAddonPreview ? (+ <div className='space-y-3'>+ <div className='flex items-center justify-between gap-4'>+ <Text as='span' size='sm' colour='secondary'>+ {t('billing.sessionReplayAddonDueNow')}+ </Text>+ <Text as='span' size='sm' weight='semibold'>+ {currentSessionReplayAddonPreview.dueNow > 0+ ? `${currency.symbol}${formatBillingPrice(+ currentSessionReplayAddonPreview.dueNow,+ )}`+ : t('billing.sessionReplayAddonNoImmediateCharge')}+ </Text>+ </div>+ <div className='flex items-center justify-between gap-4'>+ <Text as='span' size='sm' colour='secondary'>+ {t('billing.sessionReplayAddonRecurring')}+ </Text>+ <Text as='span' size='sm' weight='semibold'>+ {currentSessionReplayAddonPreview.quantity > 0+ ? `${currency.symbol}${formatBillingPrice(+ selectedSessionReplayAddonRecurringAmount,+ )}/${t(+ selectedSessionReplayAddonBillingInterval ===+ 'yearly'+ ? 'pricing.intervals.year'+ : 'pricing.intervals.month',+ )}`+ : t('billing.sessionReplayAddonNoNextCharge')}+ </Text>+ </div>+ <div className='flex items-center justify-between gap-4'>+ <Text as='span' size='sm' colour='secondary'>+ {t('billing.sessionReplayAddonNextCharge')}+ </Text>+ <Text as='span' size='sm' weight='semibold'>+ {formatBillingDate(+ currentSessionReplayAddonPreview.nextChargeDate,+ ) || t('billing.sessionReplayAddonNoNextCharge')}+ </Text>+ </div>+ {currentSessionReplayAddonPreview.effectiveDate ? (+ <div className='flex items-center justify-between gap-4'>+ <Text as='span' size='sm' colour='secondary'>+ {t('billing.sessionReplayAddonEffectiveOn')}+ </Text>+ <Text as='span' size='sm' weight='semibold'>+ {formatBillingDate(+ currentSessionReplayAddonPreview.effectiveDate,+ )}+ </Text>+ </div>+ ) : null}+ </div>+ ) : (+ <Text as='p' size='sm' colour='secondary'>+ {t('billing.sessionReplayAddonNoChangesHint')}+ </Text>+ )}+ </div>+ </div>+ }+ />+<ModalonClose={() => {if (!isCancellingSubscription) {diff --git a/web/app/routes/user-settings.tsx b/web/app/routes/user-settings.tsxindex 33e982f47..263cadb35 100644--- a/web/app/routes/user-settings.tsx+++ b/web/app/routes/user-settings.tsx@@ -131,6 +131,34 @@ export interface WebsiteAddonPreview {status: 'active' | 'past_due' | 'cancelled' | null}+export interface SessionReplayAddonPreview {+ code: 'session_replays'+ 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+ includedSessionReplays: number | 'custom'+ totalSessionReplays: number | 'custom'+ activeExtraSessionReplays: 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()@@ -523,6 +551,58 @@ export async function action({ request }: ActionFunctionArgs) {)}+ case 'preview-session-replay-addon': {+ const quantity = Number(formData.get('quantity'))+ const billingInterval = formData.get('billingInterval')?.toString()++ const result = await serverFetch<SessionReplayAddonPreview>(+ request,+ 'user/addons/session-replays/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-session-replay-addon': {+ const quantity = Number(formData.get('quantity'))+ const billingInterval = formData.get('billingInterval')?.toString()++ const result = await serverFetch<User>(+ request,+ 'user/addons/session-replays',+ {+ 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/public/locales/en.json b/web/public/locales/en.jsonindex b116fc46d..b436920dd 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -2987,7 +2987,9 @@"sessionReplays": "Session replays","sessionReplaysAddonTooltip": "Need more recorded sessions? Session replay add-ons can extend this monthly quota.","perMonthQuota": "{{amount}} / month",+ "sessionReplayUsageSummary": "{{used}} of {{total}} session replays","recordedSessionsQuota": "Recorded sessions quota",+ "addedSessionReplays": "+{{amount}} added","api": "API","perHourQuota": "{{amount}} / hour","currentRateLimit": "Current rate limit",@@ -2996,7 +2998,7 @@"websiteAddonTitle": "Additional websites","websiteAddonDescription": "Add websites in chunks of {{amount}} at {{unitPrice}} per website per month.","sessionReplayAddonTitle": "Additional session replays",- "sessionReplayAddonDescription": "Add {{amount}} recorded sessions per month. Session replay pricing is temporary while the feature is finalised.",+ "sessionReplayAddonDescription": "Add recorded sessions in chunks of {{amount}} at {{bundlePrice}} per month.","sessionReplayCapacityTitle": "Session replay capacity","sessionReplayCapacityDescription": "Your current plan includes {{quota}} recorded sessions per month. For higher capacity or longer retention, choose a larger Plus plan or contact us for a custom entitlement.","sessionReplayCapacityCta": "Review replay plans",@@ -3012,6 +3014,17 @@"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.",+ "sessionReplayAddonUpdated": "Session replay add-on updated.",+ "sessionReplayAddonRequiresSubscription": "You need an active paid subscription before you can buy session replay add-ons.",+ "sessionReplayAddonUnavailableDuringTrial": "Session replay add-ons become available after your trial ends and the paid subscription starts.",+ "sessionReplayAddonUnavailableCancelled": "Session replay add-ons are unavailable while your subscription is scheduled for cancellation.",+ "sessionReplayAddonUnavailableSuspended": "Session replay add-ons are unavailable while billing is suspended. Update your payment details first.",+ "sessionReplayAddonUnavailableCustom": "This account has a custom session replay quota. Contact support to adjust it.",+ "sessionReplayAddonLegacyManaged": "This account has a legacy session replay add-on. Contact support to move it to self-serve billing.",+ "legacySessionReplayAddon": "This account has a legacy session replay add-on. Contact support to move it to self-serve billing.",+ "invalidSessionReplayAddonQuantity": "Choose session replay add-ons from 0 to 100,000 extra recorded sessions in steps of 5,000.",+ "invalidSessionReplayAddonBillingInterval": "Choose monthly or yearly billing for this add-on.",+ "sessionReplayAddonChargeInProgress": "A session replay add-on charge is already in progress. Try again in a moment.","websiteAddonUsage": "Usage","websiteAddonIncluded": "Included","websiteAddonPurchased": "Purchased extra",@@ -3033,7 +3046,7 @@"websiteAddonPurchasedCount": "+{{count}} purchased","websiteAddonActiveSummary": "You're paying {{amount}} / {{interval}} for {{count}} extra websites.","websiteAddonManage": "Manage websites",- "websiteAddonBuy": "Buy websites",+ "websiteAddonBuy": "Buy more websites","websiteAddonNoChangesHint": "Choose a different amount to preview pricing.","extraWebsitesAmount": "+{{amount}} websites","noAdditionalWebsites": "No additional websites",@@ -3046,6 +3059,30 @@"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",+ "sessionReplayAddonQuantity": "Extra session replays",+ "sessionReplayAddonBillingInterval": "Billing interval",+ "sessionReplayAddonMonthly": "Monthly",+ "sessionReplayAddonYearly": "Yearly",+ "sessionReplayAddonYearlyDiscount": "Yearly billing is 10x monthly, so two months are free.",+ "sessionReplayAddonYearlySavings": "2 months free",+ "sessionReplayAddonYearlyOnlyNote": "Yearly add-on billing is available on yearly subscriptions, so this add-on will be billed monthly.",+ "sessionReplayAddonIncludedCount": "{{count}} included",+ "sessionReplayAddonPurchasedCount": "+{{count}} purchased",+ "sessionReplayAddonActiveSummary": "You're paying {{amount}} / {{interval}} for {{count}} extra session replays.",+ "sessionReplayAddonManage": "Manage replays",+ "sessionReplayAddonBuy": "Buy more replays",+ "sessionReplayAddonNoChangesHint": "Choose a different amount to preview pricing.",+ "extraSessionReplaysAmount": "+{{amount}} session replays",+ "noAdditionalSessionReplays": "No additional session replays",+ "sessionReplayAddonDueNow": "Due now",+ "sessionReplayAddonRecurring": "Recurring",+ "sessionReplayAddonNextCharge": "Next charge",+ "sessionReplayAddonEffectiveOn": "Effective on",+ "sessionReplayAddonNoImmediateCharge": "No immediate charge",+ "sessionReplayAddonNoNextCharge": "No next charge",+ "sessionReplayAddonNextRenewal": "the next renewal",+ "sessionReplayAddonPendingChange": "A scheduled session replay add-on change will take effect on {{date}}. Select a new quantity or update the current settings to replace it.",+ "sessionReplayAddonSave": "Update add-on","sessionReplayAddonComingSoon": "Self-serve session replay add-ons are coming soon."},"modals": {