Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

feat: Revenue analytics

Blue Mouse61bbf7cfa3d2
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index 652151bdb..91a1d5d85 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -97,6 +97,17 @@ import { LiveVisitorsDto } from './dto/live-visitors.dto'
import { GetHeartbeatStatsDto } from './dto/get-heartbeat-stats'
import { GetKeywordsDto } from './dto/get-keywords.dto'
import { GSCService } from '../project/gsc.service'
+import {
+ GetProfileIdDto,
+ GetSessionIdDto,
+ LogPaymentDto,
+} from '../revenue/dto/payment-log.dto'
+import { RevenueService } from '../revenue/revenue.service'
+import {
+ RevenueType,
+ RevenueStatus,
+ RevenueProvider,
+} from '../revenue/interfaces/revenue.interface'
dayjs.extend(utc)
dayjs.extend(dayjsTimezone)
@@ -204,6 +215,7 @@ export class AnalyticsController {
private readonly analyticsService: AnalyticsService,
private readonly logger: AppLoggerService,
private readonly gscService: GSCService,
+ private readonly revenueService: RevenueService,
) {}
@ApiBearerAuth()
@@ -2290,4 +2302,133 @@ export class AnalyticsController {
return { ...result, appliedFilters, timeBucket: timeBucketForAllTime }
}
+
+ // Revenue attribution endpoints
+
+ @Post('profile-id')
+ @Public()
+ async getOrCreateProfileId(
+ @Body() dto: GetProfileIdDto,
+ @Headers() headers,
+ @Ip() reqIP,
+ ): Promise<{ profileId: string | null }> {
+ const { 'user-agent': userAgent } = headers
+ const { pid } = dto
+
+ try {
+ const ip = getIPFromHeaders(headers, true) || reqIP || ''
+
+ const profileId = await this.analyticsService.generateProfileId(
+ pid,
+ userAgent,
+ ip,
+ )
+
+ return { profileId }
+ } catch (error) {
+ this.logger.error({ error, pid }, 'Error generating profile ID')
+ return { profileId: null }
+ }
+ }
+
+ @Post('session-id')
+ @Public()
+ async getOrCreateSessionId(
+ @Body() dto: GetSessionIdDto,
+ @Headers() headers,
+ @Ip() reqIP,
+ ): Promise<{ sessionId: string | null }> {
+ const { 'user-agent': userAgent } = headers
+ const { pid } = dto
+
+ try {
+ const ip = getIPFromHeaders(headers, true) || reqIP || ''
+
+ const { psid } = await this.analyticsService.getSessionId(
+ pid,
+ userAgent,
+ ip,
+ )
+
+ // If no session exists, generate one
+ if (!psid) {
+ const [, newPsid] =
+ await this.analyticsService.generateAndStoreSessionId(
+ pid,
+ userAgent,
+ ip,
+ )
+ return { sessionId: newPsid }
+ }
+
+ return { sessionId: psid }
+ } catch (error) {
+ this.logger.error({ error, pid }, 'Error generating session ID')
+ return { sessionId: null }
+ }
+ }
+
+ @Post('payment')
+ @Public()
+ async logPayment(
+ @Body() dto: LogPaymentDto,
+ @Headers() headers,
+ @Ip() reqIP,
+ ): Promise<{ success: boolean }> {
+ const { 'user-agent': userAgent, origin } = headers
+
+ try {
+ const ip = getIPFromHeaders(headers, true) || reqIP || ''
+
+ // Validate the project exists
+ await this.analyticsService.validate({ pid: dto.pid } as any, origin, ip)
+
+ // Generate profileId and sessionId if not provided
+ let profileId = dto.profileId
+ let sessionId = dto.sessionId
+
+ if (!profileId) {
+ profileId = await this.analyticsService.generateProfileId(
+ dto.pid,
+ userAgent,
+ ip,
+ )
+ }
+
+ if (!sessionId) {
+ const { psid } = await this.analyticsService.getSessionId(
+ dto.pid,
+ userAgent,
+ ip,
+ )
+ sessionId = psid || undefined
+ }
+
+ // Insert the payment event into ClickHouse
+ await this.revenueService.insertTransaction({
+ pid: dto.pid,
+ transactionId: dto.transactionId || `manual_${Date.now()}`,
+ provider: RevenueProvider.PADDLE, // Default to paddle for now
+ type: RevenueType.SALE,
+ status: RevenueStatus.COMPLETED,
+ amount: dto.amount || 0,
+ originalAmount: dto.amount || 0,
+ originalCurrency: dto.currency || 'USD',
+ currency: dto.currency || 'USD',
+ profileId: profileId || null,
+ sessionId: sessionId || null,
+ customerEmail: null,
+ productId: null,
+ productName: null,
+ metadata: dto.metadata || {},
+ created: new Date(),
+ syncedAt: new Date(),
+ })
+
+ return { success: true }
+ } catch (error) {
+ this.logger.error({ error, pid: dto.pid }, 'Error logging payment')
+ return { success: false }
+ }
+ }
}
diff --git a/backend/apps/cloud/src/analytics/analytics.module.ts b/backend/apps/cloud/src/analytics/analytics.module.ts
index cc8e53eb6..30b0d8a56 100644
--- a/backend/apps/cloud/src/analytics/analytics.module.ts
+++ b/backend/apps/cloud/src/analytics/analytics.module.ts
@@ -9,6 +9,7 @@ import { Salt } from './entities/salt.entity'
import { UserModule } from '../user/user.module'
import { AppLoggerModule } from '../logger/logger.module'
import { ProjectModule } from '../project/project.module'
+import { RevenueModule } from '../revenue/revenue.module'
@Module({
imports: [
@@ -16,6 +17,7 @@ import { ProjectModule } from '../project/project.module'
forwardRef(() => UserModule),
AppLoggerModule,
ProjectModule,
+ forwardRef(() => RevenueModule),
],
providers: [AnalyticsService, SaltService, HeartbeatGateway],
exports: [AnalyticsService, SaltService],
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index ba5d0c657..a04bd00fd 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -4246,16 +4246,34 @@ export class AnalyticsService {
}
return _map(pages, (page: IPageflow) => {
- if (!page.metadata) {
- return page
+ const processedMetadata = page.metadata
+ ? _map(page.metadata, ([key, value]: [string, string]) => ({
+ key,
+ value,
+ }))
+ : undefined
+
+ // For sale and refund events, extract amount and currency from metadata
+ if (
+ (page.type === 'sale' || page.type === 'refund') &&
+ processedMetadata
+ ) {
+ const amountEntry = processedMetadata.find(m => m.key === 'amount')
+ const currencyEntry = processedMetadata.find(m => m.key === 'currency')
+
+ return {
+ ...page,
+ metadata: processedMetadata.filter(
+ m => m.key !== 'amount' && m.key !== 'currency',
+ ),
+ amount: amountEntry ? parseFloat(amountEntry.value) : undefined,
+ currency: currencyEntry ? currencyEntry.value : undefined,
+ }
}
return {
...page,
- metadata: _map(page.metadata, ([key, value]: [string, string]) => ({
- key,
- value,
- })),
+ metadata: processedMetadata,
}
})
}
@@ -4269,56 +4287,79 @@ export class AnalyticsService {
WITH events_with_meta AS (
SELECT
'pageview' AS type,
- pg AS value,
+ toString(pg) AS value,
toTimeZone(analytics.created, {timezone:String}) AS created,
pid,
- psid,
+ toString(analytics.psid) AS psid,
groupArrayIf(tuple(meta.key, meta.value), notEmpty(meta.key) AND notEmpty(meta.value)) AS metadata
FROM analytics
LEFT ARRAY JOIN meta.key, meta.value
WHERE
pid = {pid:FixedString(12)}
AND analytics.psid IS NOT NULL
- AND CAST(analytics.psid AS String) = {psid:String}
+ AND toString(analytics.psid) = {psid:String}
GROUP BY type, value, created, pid, psid
UNION ALL
SELECT
'event' AS type,
- ev AS value,
+ toString(ev) AS value,
toTimeZone(customEV.created, {timezone:String}) AS created,
pid,
- psid,
+ toString(customEV.psid) AS psid,
groupArrayIf(tuple(meta.key, meta.value), notEmpty(meta.key) AND notEmpty(meta.value)) AS metadata
FROM customEV
LEFT ARRAY JOIN meta.key, meta.value
WHERE
pid = {pid:FixedString(12)}
AND customEV.psid IS NOT NULL
- AND CAST(customEV.psid AS String) = {psid:String}
+ AND toString(customEV.psid) = {psid:String}
GROUP BY type, value, created, pid, psid
UNION ALL
SELECT
'error' AS type,
- errors.name AS value,
+ toString(errors.name) AS value,
toTimeZone(errors.created, {timezone:String}) AS created,
pid,
- psid,
+ toString(errors.psid) AS psid,
[
tuple('message', COALESCE(errors.message, '')),
- tuple('lineno', CAST(COALESCE(errors.lineno, 0), 'String')),
- tuple('colno', CAST(COALESCE(errors.colno, 0), 'String')),
+ tuple('lineno', toString(COALESCE(errors.lineno, 0))),
+ tuple('colno', toString(COALESCE(errors.colno, 0))),
tuple('filename', COALESCE(errors.filename, ''))
] AS metadata
FROM errors
WHERE
pid = {pid:FixedString(12)}
AND errors.psid IS NOT NULL
- AND CAST(errors.psid AS String) = {psid:String}
+ AND toString(errors.psid) = {psid:String}
GROUP BY type, value, created, pid, psid, errors.message, errors.lineno, errors.colno, errors.filename
+
+ UNION ALL
+
+ SELECT
+ revenue.type AS type,
+ COALESCE(toString(revenue.product_name), toString(revenue.product_id), if(revenue.type = 'refund', 'Refund', 'Sale')) AS value,
+ toTimeZone(revenue.created, {timezone:String}) AS created,
+ pid,
+ toString(revenue.session_id) AS psid,
+ [
+ tuple('amount', toString(revenue.amount)),
+ tuple('currency', toString(revenue.currency)),
+ tuple('transaction_id', toString(revenue.transaction_id)),
+ tuple('status', toString(revenue.status)),
+ tuple('provider', toString(revenue.provider))
+ ] AS metadata
+ FROM revenue
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND revenue.session_id IS NOT NULL
+ AND toString(revenue.session_id) = {psid:String}
+ AND revenue.type IN ('sale', 'refund')
+ GROUP BY type, value, created, pid, psid, revenue.product_name, revenue.product_id, revenue.amount, revenue.currency, revenue.transaction_id, revenue.status, revenue.provider
)
SELECT
@@ -4336,7 +4377,8 @@ export class AnalyticsService {
FROM analytics
WHERE
pid = {pid:FixedString(12)}
- AND CAST(psid, 'String') = {psid:String}
+ AND psid IS NOT NULL
+ AND toString(psid) = {psid:String}
ORDER BY created ASC
LIMIT 1;
`
@@ -4347,7 +4389,8 @@ export class AnalyticsService {
FROM sessions FINAL
WHERE
pid = {pid:FixedString(12)}
- AND CAST(psid, 'String') = {psid:String}
+ AND psid IS NOT NULL
+ AND toString(psid) = {psid:String}
`
const paramsData = {
@@ -4394,7 +4437,8 @@ export class AnalyticsService {
FROM analytics
WHERE
pid = {pid:FixedString(12)}
- AND CAST(psid, 'String') = {psid:String}
+ AND psid IS NOT NULL
+ AND toString(psid) = {psid:String}
LIMIT 1;
`
@@ -4433,7 +4477,7 @@ export class AnalyticsService {
timeBucket,
from,
to,
- "AND psid IS NOT NULL AND CAST(psid, 'String') = {psid:String}",
+ 'AND psid IS NOT NULL AND toString(psid) = {psid:String}',
{
params: {
...paramsData.params,
@@ -4542,6 +4586,18 @@ export class AnalyticsService {
AND created BETWEEN {groupFrom:String} AND {groupTo:String}
GROUP BY psidCasted, pid
),
+ revenue_totals AS (
+ SELECT
+ CAST(session_id, 'String') AS psidCasted,
+ pid,
+ sum(CASE WHEN type = 'sale' THEN amount ELSE 0 END) - sum(CASE WHEN type = 'refund' THEN abs(amount) ELSE 0 END) as revenue,
+ sum(CASE WHEN type = 'refund' THEN abs(amount) ELSE 0 END) as refunds
+ FROM revenue
+ WHERE pid = {pid:FixedString(12)} AND session_id IS NOT NULL
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ AND type IN ('sale', 'refund')
+ GROUP BY psidCasted, pid
+ ),
session_duration_agg AS (
SELECT
CAST(psid, 'String') AS psidCasted,
@@ -4570,6 +4626,8 @@ export class AnalyticsService {
COALESCE(pc.count, 0) AS pageviews,
COALESCE(ec.count, 0) AS customEvents,
COALESCE(errc.count, 0) AS errors,
+ toFloat64(COALESCE(rt.revenue, toDecimal64(0, 4))) AS revenue,
+ toFloat64(COALESCE(rt.refunds, toDecimal64(0, 4))) AS refunds,
dsf.sessionStart,
dsf.lastActivity,
if(dateDiff('second', dsf.lastActivity, now()) < ${LIVE_SESSION_THRESHOLD_SECONDS}, 1, 0) AS isLive,
@@ -4581,6 +4639,7 @@ export class AnalyticsService {
LEFT JOIN pageview_counts pc ON dsf.psidCasted = pc.psidCasted AND dsf.pid = pc.pid
LEFT JOIN event_counts ec ON dsf.psidCasted = ec.psidCasted AND dsf.pid = ec.pid
LEFT JOIN error_counts errc ON dsf.psidCasted = errc.psidCasted AND dsf.pid = errc.pid
+ LEFT JOIN revenue_totals rt ON dsf.psidCasted = rt.psidCasted AND dsf.pid = rt.pid
LEFT JOIN session_duration_agg sda ON dsf.psidCasted = sda.psidCasted AND dsf.pid = sda.pid
LEFT JOIN first_session_per_profile fsp ON sda.profileId = fsp.profileId
WHERE dsf.psidCasted IS NOT NULL
@@ -4758,6 +4817,18 @@ export class AnalyticsService {
AND profileId = {profileId:String}
`
+ // Query for total revenue from profile (only sales, not refunds)
+ const queryRevenue = `
+ SELECT
+ sum(amount) AS totalRevenue,
+ any(currency) AS revenueCurrency
+ FROM revenue
+ WHERE pid = {pid:FixedString(12)}
+ AND profile_id = {profileId:String}
+ AND type = 'sale'
+ AND status = 'completed'
+ `
+
const params = { pid, profileId }
const [
@@ -4766,6 +4837,7 @@ export class AnalyticsService {
pageviewsResult,
eventsResult,
detailsResult,
+ revenueResult,
] = await Promise.all([
clickhouse
.query({ query: querySessionCount, query_params: params })
@@ -4782,6 +4854,9 @@ export class AnalyticsService {
clickhouse
.query({ query: queryDetails, query_params: params })
.then(resultSet => resultSet.json()),
+ clickhouse
+ .query({ query: queryRevenue, query_params: params })
+ .then(resultSet => resultSet.json()),
])
const sessionCount = (sessionCountResult.data[0] || {}) as Record<
@@ -4792,6 +4867,7 @@ export class AnalyticsService {
const pageviews = (pageviewsResult.data[0] || {}) as Record<string, any>
const events = (eventsResult.data[0] || {}) as Record<string, any>
const details = (detailsResult.data[0] || {}) as Record<string, any>
+ const revenue = (revenueResult.data[0] || {}) as Record<string, any>
return {
profileId,
@@ -4802,6 +4878,8 @@ export class AnalyticsService {
firstSeen: sessionCount.firstSeen,
lastSeen: sessionCount.lastSeen,
avgDuration: avgDuration.avgDuration || 0,
+ totalRevenue: revenue.totalRevenue || 0,
+ revenueCurrency: revenue.revenueCurrency || null,
...details,
}
}
diff --git a/backend/apps/cloud/src/analytics/interfaces/index.ts b/backend/apps/cloud/src/analytics/interfaces/index.ts
index 1618907f5..432b148eb 100644
--- a/backend/apps/cloud/src/analytics/interfaces/index.ts
+++ b/backend/apps/cloud/src/analytics/interfaces/index.ts
@@ -181,7 +181,7 @@ export interface IOverallPerformance {
}
export interface IPageflow {
- type: 'pageview' | 'event'
+ type: 'pageview' | 'event' | 'error' | 'sale' | 'refund'
value: string
created: string
metadata?: [string, string][]
diff --git a/backend/apps/cloud/src/app.module.ts b/backend/apps/cloud/src/app.module.ts
index 9ecdc2b35..dbf6f3a0f 100644
--- a/backend/apps/cloud/src/app.module.ts
+++ b/backend/apps/cloud/src/app.module.ts
@@ -33,6 +33,7 @@ import { HealthModule } from './health/health.module'
import { AppController } from './app.controller'
import { isPrimaryNode, isPrimaryClusterNode } from './common/utils'
import { OrganisationModule } from './organisation/organisation.module'
+import { RevenueModule } from './revenue/revenue.module'
const modules = [
SentryModule.forRoot(),
@@ -90,6 +91,7 @@ const modules = [
OgImageModule,
HealthModule,
OrganisationModule,
+ RevenueModule,
]
@Module({
diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.ts
index c56d33a49..81b4c755b 100644
--- a/backend/apps/cloud/src/project/entity/project.entity.ts
+++ b/backend/apps/cloud/src/project/entity/project.entity.ts
@@ -171,4 +171,17 @@ export class Project {
@Column('varchar', { nullable: true, default: null, length: 256 })
gscAccountEmail: string | null
+
+ // Revenue / Payment provider integration
+ @Column('text', { nullable: true, default: null })
+ paddleApiKeyEnc: string | null
+
+ @Column('varchar', { nullable: true, default: null, length: 3 })
+ revenueCurrency: string | null
+
+ @Column('text', { nullable: true, default: null })
+ paddleApiKeyPermissions: string | null
+
+ @Column('datetime', { nullable: true, default: null })
+ revenueLastSyncAt: Date | null
}
diff --git a/backend/apps/cloud/src/revenue/adapters/paddle.adapter.ts b/backend/apps/cloud/src/revenue/adapters/paddle.adapter.ts
new file mode 100644
index 000000000..632af2cc6
--- /dev/null
+++ b/backend/apps/cloud/src/revenue/adapters/paddle.adapter.ts
@@ -0,0 +1,387 @@
+import { Injectable } from '@nestjs/common'
+import { AppLoggerService } from '../../logger/logger.service'
+import { RevenueService } from '../revenue.service'
+import {
+ RevenueProvider,
+ RevenueType,
+ RevenueStatus,
+ RevenueTransaction,
+} from '../interfaces/revenue.interface'
+
+interface PaddleTransaction {
+ id: string
+ status: string
+ customer_id: string | null
+ currency_code: string
+ details: {
+ totals: {
+ total: string
+ subtotal: string
+ tax: string
+ }
+ line_items?: {
+ product: {
+ id: string
+ name: string
+ }
+ price: {
+ id: string
+ billing_cycle: {
+ interval: string
+ frequency: number
+ } | null
+ }
+ }[]
+ }
+ checkout: {
+ url: string | null
+ } | null
+ custom_data?: {
+ swetrix_profile_id?: string
+ swetrix_session_id?: string
+ [key: string]: unknown
+ }
+ created_at: string
+ updated_at: string
+ billed_at: string | null
+}
+
+interface PaddleAdjustment {
+ id: string
+ transaction_id: string
+ action: string
+ status: string
+ totals: {
+ total: string
+ subtotal: string
+ tax: string
+ currency_code: string
+ }
+ reason: string
+ created_at: string
+}
+
+interface PaddleListResponse<T> {
+ data: T[]
+ meta: {
+ request_id: string
+ pagination?: {
+ per_page: number
+ next?: string
+ has_more: boolean
+ estimated_total?: number
+ }
+ }
+}
+
+@Injectable()
+export class PaddleAdapter {
+ // TODO: Change to api.paddle.com when merging to main
+ private readonly baseUrl = 'https://sandbox-api.paddle.com'
+
+ constructor(
+ private readonly logger: AppLoggerService,
+ private readonly revenueService: RevenueService,
+ ) {}
+
+ async validateApiKey(apiKey: string): Promise<boolean> {
+ try {
+ const response = await fetch(`${this.baseUrl}/event-types`, {
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ })
+
+ return response.ok
+ } catch (error) {
+ this.logger.error({ error }, 'Failed to validate Paddle API key')
+ return false
+ }
+ }
+
+ async syncTransactions(
+ projectId: string,
+ apiKey: string,
+ currency: string,
+ lastSyncAt?: Date,
+ ): Promise<number> {
+ let syncedCount = 0
+
+ try {
+ // Small overlap window to avoid missing edge updates due to timestamp truncation
+ // and provider-side timing differences.
+ const effectiveLastSyncAt =
+ lastSyncAt instanceof Date && !isNaN(lastSyncAt.getTime())
+ ? new Date(lastSyncAt.getTime() - 60 * 1000)
+ : undefined
+
+ // Fetch transactions
+ const transactions = await this.fetchTransactions(
+ apiKey,
+ effectiveLastSyncAt,
+ )
+
+ for (const transaction of transactions) {
+ await this.processTransaction(projectId, transaction, currency)
+ syncedCount++
+ }
+
+ // Fetch adjustments (refunds)
+ const adjustments = await this.fetchAdjustments(
+ apiKey,
+ effectiveLastSyncAt,
+ )
+
+ for (const adjustment of adjustments) {
+ await this.processAdjustment(projectId, adjustment, currency)
+ syncedCount++
+ }
+
+ this.logger.log({ projectId, syncedCount }, 'Paddle sync completed')
+ } catch (error) {
+ this.logger.error(
+ { error, projectId },
+ 'Failed to sync Paddle transactions',
+ )
+ throw error
+ }
+
+ return syncedCount
+ }
+
+ private async fetchTransactions(
+ apiKey: string,
+ after?: Date,
+ ): Promise<PaddleTransaction[]> {
+ const transactions: PaddleTransaction[] = []
+ let cursor: string | undefined
+
+ do {
+ const params = new URLSearchParams({
+ per_page: '50',
+ })
+
+ // Paddle API: pass each status value separately
+ params.append('status', 'completed')
+ params.append('status', 'billed')
+
+ if (after && after instanceof Date && !isNaN(after.getTime())) {
+ // Use RFC 3339 format without milliseconds
+ params.append(
+ 'updated_at[gte]',
+ after.toISOString().split('.')[0] + 'Z',
+ )
+ }
+
+ if (cursor && cursor.length > 0) {
+ params.append('after', cursor)
+ }
+
+ const response = await fetch(
+ `${this.baseUrl}/transactions?${params.toString()}`,
+ {
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ },
+ )
+
+ if (!response.ok) {
+ const errorText = await response.text()
+ this.logger.error(
+ { status: response.status, error: errorText },
+ 'Paddle API error fetching transactions',
+ )
+ throw new Error(`Paddle API error: ${response.status}`)
+ }
+
+ const data: PaddleListResponse<PaddleTransaction> = await response.json()
+ transactions.push(...data.data)
+
+ // Only set cursor if has_more is true and next is valid
+ cursor =
+ data.meta.pagination?.has_more && data.meta.pagination?.next
+ ? data.meta.pagination.next
+ : undefined
+ } while (cursor)
+
+ return transactions
+ }
+
+ private async fetchAdjustments(
+ apiKey: string,
+ after?: Date,
+ ): Promise<PaddleAdjustment[]> {
+ const adjustments: PaddleAdjustment[] = []
+ let cursor: string | undefined
+
+ do {
+ const params = new URLSearchParams({
+ action: 'refund',
+ status: 'approved',
+ per_page: '50',
+ })
+
+ if (after && after instanceof Date && !isNaN(after.getTime())) {
+ // Use RFC 3339 format without milliseconds
+ params.append(
+ 'updated_at[gte]',
+ after.toISOString().split('.')[0] + 'Z',
+ )
+ }
+
+ if (cursor && cursor.length > 0) {
+ params.append('after', cursor)
+ }
+
+ const response = await fetch(
+ `${this.baseUrl}/adjustments?${params.toString()}`,
+ {
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ },
+ )
+
+ if (!response.ok) {
+ const errorText = await response.text()
+ this.logger.error(
+ { status: response.status, error: errorText },
+ 'Paddle API error fetching adjustments',
+ )
+ throw new Error(`Paddle API error: ${response.status}`)
+ }
+
+ const data: PaddleListResponse<PaddleAdjustment> = await response.json()
+ adjustments.push(...data.data)
+
+ // Only set cursor if has_more is true and next is valid
+ cursor =
+ data.meta.pagination?.has_more && data.meta.pagination?.next
+ ? data.meta.pagination.next
+ : undefined
+ } while (cursor)
+
+ return adjustments
+ }
+
+ private async processTransaction(
+ projectId: string,
+ transaction: PaddleTransaction,
+ targetCurrency: string,
+ ): Promise<void> {
+ const originalAmount = parseFloat(transaction.details.totals.total) / 100
+ const originalCurrency = transaction.currency_code
+
+ // Determine transaction type
+ let type = RevenueType.SALE
+ const lineItems = transaction.details.line_items || []
+ if (lineItems.some(item => item?.price?.billing_cycle != null)) {
+ type = RevenueType.SUBSCRIPTION
+ }
+
+ // Convert currency if needed (simplified - in production, use real exchange rates)
+ const amount = this.convertCurrency(
+ originalAmount,
+ originalCurrency,
+ targetCurrency,
+ )
+
+ const productName = lineItems[0]?.product?.name || null
+ const productId = lineItems[0]?.product?.id || null
+
+ // Extract attribution data from custom_data
+ const profileId = transaction.custom_data?.swetrix_profile_id || null
+ const sessionId = transaction.custom_data?.swetrix_session_id || null
+
+ const revenueTransaction: RevenueTransaction = {
+ pid: projectId,
+ transactionId: transaction.id,
+ provider: RevenueProvider.PADDLE,
+ type,
+ status: RevenueStatus.COMPLETED,
+ amount,
+ originalAmount,
+ originalCurrency,
+ currency: targetCurrency,
+ profileId,
+ sessionId,
+ customerEmail: null, // Would need to fetch customer to get email
+ productId,
+ productName,
+ metadata: transaction.custom_data || {},
+ created: new Date(transaction.billed_at || transaction.created_at),
+ syncedAt: new Date(),
+ }
+
+ await this.revenueService.insertTransaction(revenueTransaction)
+ }
+
+ private async processAdjustment(
+ projectId: string,
+ adjustment: PaddleAdjustment,
+ targetCurrency: string,
+ ): Promise<void> {
+ const originalAmount = parseFloat(adjustment.totals.total) / 100
+ const originalCurrency = adjustment.totals.currency_code
+
+ const amount = this.convertCurrency(
+ originalAmount,
+ originalCurrency,
+ targetCurrency,
+ )
+
+ const revenueTransaction: RevenueTransaction = {
+ pid: projectId,
+ transactionId: adjustment.id,
+ provider: RevenueProvider.PADDLE,
+ type: RevenueType.REFUND,
+ status: RevenueStatus.REFUNDED,
+ amount: -Math.abs(amount), // Refunds are negative
+ originalAmount: -Math.abs(originalAmount),
+ originalCurrency,
+ currency: targetCurrency,
+ profileId: null,
+ sessionId: null,
+ customerEmail: null,
+ productId: null,
+ productName: adjustment.reason || 'Refund',
+ metadata: { originalTransactionId: adjustment.transaction_id },
+ created: new Date(adjustment.created_at),
+ syncedAt: new Date(),
+ }
+
+ await this.revenueService.insertTransaction(revenueTransaction)
+ }
+
+ private convertCurrency(
+ amount: number,
+ fromCurrency: string,
+ toCurrency: string,
+ ): number {
+ if (fromCurrency === toCurrency) {
+ return amount
+ }
+
+ // Simplified conversion rates - in production, use a real exchange rate API
+ // These are approximate rates as of late 2024
+ const rates: Record<string, number> = {
+ USD: 1,
+ EUR: 1.08,
+ GBP: 1.27,
+ CAD: 0.74,
+ AUD: 0.66,
+ JPY: 0.0067,
+ }
+
+ const fromRate = rates[fromCurrency] || 1
+ const toRate = rates[toCurrency] || 1
+
+ // Convert to USD first, then to target currency
+ const usdAmount = amount * fromRate
+ return usdAmount / toRate
+ }
+}
diff --git a/backend/apps/cloud/src/revenue/dto/connect-paddle.dto.ts b/backend/apps/cloud/src/revenue/dto/connect-paddle.dto.ts
new file mode 100644
index 000000000..f24339604
--- /dev/null
+++ b/backend/apps/cloud/src/revenue/dto/connect-paddle.dto.ts
@@ -0,0 +1,43 @@
+import { ApiProperty } from '@nestjs/swagger'
+import {
+ IsNotEmpty,
+ IsString,
+ IsOptional,
+ Length,
+ Matches,
+} from 'class-validator'
+
+export class ConnectPaddleDto {
+ @ApiProperty({
+ description: 'Paddle API key (pdl_live_*, pdl_test_* or pdl_sdbx_*)',
+ example: 'pdl_live_xxxxxxxxxxxxxxxx',
+ })
+ @IsNotEmpty()
+ @IsString()
+ @Matches(/^pdl_(live|test|sdbx)_/, {
+ message:
+ 'Invalid Paddle API key format. Key should start with pdl_live_ or pdl_test_',
+ })
+ apiKey: string
+
+ @ApiProperty({
+ description: 'Currency code for revenue reporting (ISO 4217)',
+ example: 'USD',
+ default: 'USD',
+ })
+ @IsOptional()
+ @IsString()
+ @Length(3, 3)
+ currency?: string
+}
+
+export class UpdateRevenueCurrencyDto {
+ @ApiProperty({
+ description: 'Currency code for revenue reporting (ISO 4217)',
+ example: 'USD',
+ })
+ @IsNotEmpty()
+ @IsString()
+ @Length(3, 3)
+ currency: string
+}
diff --git a/backend/apps/cloud/src/revenue/dto/get-revenue.dto.ts b/backend/apps/cloud/src/revenue/dto/get-revenue.dto.ts
new file mode 100644
index 000000000..e5ec9816a
--- /dev/null
+++ b/backend/apps/cloud/src/revenue/dto/get-revenue.dto.ts
@@ -0,0 +1,71 @@
+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'
+import {
+ IsNotEmpty,
+ IsString,
+ IsOptional,
+ IsInt,
+ Min,
+ Max,
+} from 'class-validator'
+import { Transform, Type } from 'class-transformer'
+
+export class GetRevenueDto {
+ @ApiProperty({ description: 'Project ID' })
+ @IsNotEmpty()
+ @IsString()
+ pid: string
+
+ @ApiProperty({ description: 'Time period', example: '7d' })
+ @IsNotEmpty()
+ @IsString()
+ period: string
+
+ @ApiPropertyOptional({ description: 'Start date for custom period' })
+ @IsOptional()
+ @IsString()
+ from?: string
+
+ @ApiPropertyOptional({ description: 'End date for custom period' })
+ @IsOptional()
+ @IsString()
+ to?: string
+
+ @ApiPropertyOptional({ description: 'Timezone', default: 'UTC' })
+ @IsOptional()
+ @IsString()
+ timezone?: string
+
+ @ApiPropertyOptional({ description: 'Time bucket for chart data' })
+ @IsOptional()
+ @IsString()
+ timeBucket?: string
+}
+
+export class GetRevenueTransactionsDto extends GetRevenueDto {
+ @ApiPropertyOptional({ description: 'Number of items to take', default: 20 })
+ @IsOptional()
+ @Type(() => Number)
+ @IsInt()
+ @Min(1)
+ @Max(100)
+ take?: number
+
+ @ApiPropertyOptional({ description: 'Number of items to skip', default: 0 })
+ @IsOptional()
+ @Type(() => Number)
+ @IsInt()
+ @Min(0)
+ skip?: number
+
+ @ApiPropertyOptional({
+ description: 'Filter by type (sale, refund, subscription)',
+ })
+ @IsOptional()
+ @IsString()
+ type?: string
+
+ @ApiPropertyOptional({ description: 'Filter by status' })
+ @IsOptional()
+ @IsString()
+ status?: string
+}
diff --git a/backend/apps/cloud/src/revenue/dto/payment-log.dto.ts b/backend/apps/cloud/src/revenue/dto/payment-log.dto.ts
new file mode 100644
index 000000000..81a6fffab
--- /dev/null
+++ b/backend/apps/cloud/src/revenue/dto/payment-log.dto.ts
@@ -0,0 +1,52 @@
+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'
+import { IsNotEmpty, IsString, IsOptional, IsNumber } from 'class-validator'
+
+export class GetProfileIdDto {
+ @ApiProperty({ description: 'Project ID' })
+ @IsNotEmpty()
+ @IsString()
+ pid: string
+}
+
+export class GetSessionIdDto {
+ @ApiProperty({ description: 'Project ID' })
+ @IsNotEmpty()
+ @IsString()
+ pid: string
+}
+
+export class LogPaymentDto {
+ @ApiProperty({ description: 'Project ID' })
+ @IsNotEmpty()
+ @IsString()
+ pid: string
+
+ @ApiPropertyOptional({ description: 'Profile ID for attribution' })
+ @IsOptional()
+ @IsString()
+ profileId?: string
+
+ @ApiPropertyOptional({ description: 'Session ID for attribution' })
+ @IsOptional()
+ @IsString()
+ sessionId?: string
+
+ @ApiPropertyOptional({ description: 'Transaction ID' })
+ @IsOptional()
+ @IsString()
+ transactionId?: string
+
+ @ApiPropertyOptional({ description: 'Payment amount' })
+ @IsOptional()
+ @IsNumber()
+ amount?: number
+
+ @ApiPropertyOptional({ description: 'Currency code' })
+ @IsOptional()
+ @IsString()
+ currency?: string
+
+ @ApiPropertyOptional({ description: 'Additional metadata' })
+ @IsOptional()
+ metadata?: Record<string, string | number | boolean>
+}
diff --git a/backend/apps/cloud/src/revenue/dto/revenue-stats.dto.ts b/backend/apps/cloud/src/revenue/dto/revenue-stats.dto.ts
new file mode 100644
index 000000000..c2f28ab7c
--- /dev/null
+++ b/backend/apps/cloud/src/revenue/dto/revenue-stats.dto.ts
@@ -0,0 +1,130 @@
+import { ApiProperty } from '@nestjs/swagger'
+
+export class RevenueStatsDto {
+ @ApiProperty({ description: 'Total revenue in the period' })
+ totalRevenue: number
+
+ @ApiProperty({ description: 'Number of sales' })
+ salesCount: number
+
+ @ApiProperty({ description: 'Number of refunds' })
+ refundsCount: number
+
+ @ApiProperty({ description: 'Total refund amount' })
+ refundsAmount: number
+
+ @ApiProperty({ description: 'Average order value' })
+ averageOrderValue: number
+
+ @ApiProperty({ description: 'Currency code' })
+ currency: string
+
+ @ApiProperty({ description: 'Monthly Recurring Revenue (estimated)' })
+ mrr: number
+
+ @ApiProperty({ description: 'Percentage change from previous period' })
+ revenueChange: number
+}
+
+export class RevenueChartDto {
+ @ApiProperty({ description: 'X-axis labels (dates)' })
+ x: string[]
+
+ @ApiProperty({ description: 'Revenue values' })
+ revenue: number[]
+
+ @ApiProperty({ description: 'Sales count values' })
+ salesCount: number[]
+
+ @ApiProperty({ description: 'Refunds amount values' })
+ refundsAmount: number[]
+}
+
+export class RevenueTransactionDto {
+ @ApiProperty({ description: 'Transaction ID from payment provider' })
+ transactionId: string
+
+ @ApiProperty({ description: 'Payment provider (paddle, stripe)' })
+ provider: string
+
+ @ApiProperty({ description: 'Transaction type (sale, refund, subscription)' })
+ type: string
+
+ @ApiProperty({ description: 'Transaction status' })
+ status: string
+
+ @ApiProperty({ description: 'Amount in project currency' })
+ amount: number
+
+ @ApiProperty({ description: 'Currency code' })
+ currency: string
+
+ @ApiProperty({ description: 'Original amount before conversion' })
+ originalAmount: number
+
+ @ApiProperty({ description: 'Original currency' })
+ originalCurrency: string
+
+ @ApiProperty({ description: 'Customer email (if available)' })
+ customerEmail?: string
+
+ @ApiProperty({ description: 'Product name (if available)' })
+ productName?: string
+
+ @ApiProperty({ description: 'Profile ID for attribution' })
+ profileId?: string
+
+ @ApiProperty({ description: 'Session ID for attribution' })
+ sessionId?: string
+
+ @ApiProperty({ description: 'Transaction date' })
+ created: string
+}
+
+export class RevenueBreakdownItemDto {
+ @ApiProperty({ description: 'Breakdown category name' })
+ name: string
+
+ @ApiProperty({ description: 'Total revenue' })
+ revenue: number
+
+ @ApiProperty({ description: 'Number of transactions' })
+ count: number
+}
+
+export class RevenueBreakdownDto {
+ @ApiProperty({
+ description: 'Revenue by source/referrer',
+ type: [RevenueBreakdownItemDto],
+ })
+ bySource: RevenueBreakdownItemDto[]
+
+ @ApiProperty({
+ description: 'Revenue by country',
+ type: [RevenueBreakdownItemDto],
+ })
+ byCountry: RevenueBreakdownItemDto[]
+
+ @ApiProperty({
+ description: 'Revenue by product',
+ type: [RevenueBreakdownItemDto],
+ })
+ byProduct: RevenueBreakdownItemDto[]
+}
+
+export class RevenueStatusDto {
+ @ApiProperty({ description: 'Whether Paddle is connected' })
+ connected: boolean
+
+ @ApiProperty({ description: 'Payment provider name', required: false })
+ provider?: string
+
+ @ApiProperty({
+ description: 'Currency for revenue reporting',
+ required: false,
+ })
+ currency?: string
+
+ @ApiProperty({ description: 'Last sync timestamp', required: false })
+ lastSyncAt?: string
+}
diff --git a/backend/apps/cloud/src/revenue/interfaces/revenue.interface.ts b/backend/apps/cloud/src/revenue/interfaces/revenue.interface.ts
new file mode 100644
index 000000000..99bb6da79
--- /dev/null
+++ b/backend/apps/cloud/src/revenue/interfaces/revenue.interface.ts
@@ -0,0 +1,74 @@
+export enum RevenueProvider {
+ PADDLE = 'paddle',
+ STRIPE = 'stripe',
+}
+
+export enum RevenueType {
+ SALE = 'sale',
+ REFUND = 'refund',
+ SUBSCRIPTION = 'subscription',
+}
+
+export enum RevenueStatus {
+ COMPLETED = 'completed',
+ REFUNDED = 'refunded',
+ PENDING = 'pending',
+}
+
+export interface RevenueTransaction {
+ pid: string
+ transactionId: string
+ provider: RevenueProvider
+ type: RevenueType
+ status: RevenueStatus
+ amount: number
+ originalAmount: number
+ originalCurrency: string
+ currency: string
+ profileId?: string | null
+ sessionId?: string | null
+ customerEmail?: string | null
+ productId?: string | null
+ productName?: string | null
+ metadata?: Record<string, unknown>
+ created: Date
+ syncedAt: Date
+}
+
+export interface RevenueStats {
+ totalRevenue: number
+ salesCount: number
+ refundsCount: number
+ refundsAmount: number
+ averageOrderValue: number
+ currency: string
+}
+
+export interface RevenueChartData {
+ x: string[]
+ revenue: number[]
+ salesCount: number[]
+ refundsAmount: number[]
+}
+
+export interface RevenueBreakdown {
+ bySource: { name: string; revenue: number; count: number }[]
+ byCountry: { name: string; revenue: number; count: number }[]
+ byProduct: { name: string; revenue: number; count: number }[]
+}
+
+export interface PaddleApiKey {
+ permissions: string[]
+ createdAt: Date
+}
+
+export const PADDLE_REQUIRED_PERMISSIONS = [
+ 'transaction.read',
+ 'subscription.read',
+ 'customer.read',
+ 'product.read',
+ 'price.read',
+]
+
+// TODO: Change to vendors.paddle.com when merging to main
+export const PADDLE_API_KEY_CREATE_URL = `https://sandbox-vendors.paddle.com/authentication-v2`
diff --git a/backend/apps/cloud/src/revenue/revenue.controller.ts b/backend/apps/cloud/src/revenue/revenue.controller.ts
new file mode 100644
index 000000000..bf0c5bcec
--- /dev/null
+++ b/backend/apps/cloud/src/revenue/revenue.controller.ts
@@ -0,0 +1,367 @@
+import {
+ Controller,
+ Get,
+ Post,
+ Delete,
+ Query,
+ Param,
+ Body,
+ NotFoundException,
+ ForbiddenException,
+ BadRequestException,
+} from '@nestjs/common'
+import { ApiTags, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'
+import _isEmpty from 'lodash/isEmpty'
+
+import { ProjectService } from '../project/project.service'
+import { AppLoggerService } from '../logger/logger.service'
+import {
+ AnalyticsService,
+ getLowestPossibleTimeBucket,
+} from '../analytics/analytics.service'
+import { Auth } from '../auth/decorators'
+import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
+import { RevenueService } from './revenue.service'
+import { PaddleAdapter } from './adapters/paddle.adapter'
+import {
+ ConnectPaddleDto,
+ UpdateRevenueCurrencyDto,
+} from './dto/connect-paddle.dto'
+import { GetRevenueDto, GetRevenueTransactionsDto } from './dto/get-revenue.dto'
+import {
+ RevenueStatsDto,
+ RevenueChartDto,
+ RevenueTransactionDto,
+ RevenueBreakdownDto,
+ RevenueStatusDto,
+} from './dto/revenue-stats.dto'
+
+@ApiTags('Revenue')
+@Controller('project')
+export class RevenueController {
+ constructor(
+ private readonly revenueService: RevenueService,
+ private readonly paddleAdapter: PaddleAdapter,
+ private readonly projectService: ProjectService,
+ private readonly analyticsService: AnalyticsService,
+ private readonly logger: AppLoggerService,
+ ) {}
+
+ @ApiBearerAuth()
+ @Get('/:pid/revenue/status')
+ @Auth()
+ @ApiResponse({ status: 200, type: RevenueStatusDto })
+ async getRevenueStatus(
+ @CurrentUserId() userId: string,
+ @Param('pid') pid: string,
+ ): Promise<RevenueStatusDto> {
+ this.logger.log({ userId, pid }, 'GET /project/:pid/revenue/status')
+
+ const project = await this.projectService.getFullProject(pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project not found')
+ }
+
+ this.projectService.allowedToView(project, userId)
+
+ return this.revenueService.getRevenueStatus(project)
+ }
+
+ @ApiBearerAuth()
+ @Post('/:pid/revenue/connect')
+ @Auth()
+ @ApiResponse({ status: 201 })
+ async connectPaddle(
+ @CurrentUserId() userId: string,
+ @Param('pid') pid: string,
+ @Body() dto: ConnectPaddleDto,
+ ) {
+ this.logger.log({ userId, pid }, 'POST /project/:pid/revenue/connect')
+
+ const project = await this.projectService.getFullProject(pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project not found')
+ }
+
+ this.projectService.allowedToManage(
+ project,
+ userId,
+ 'You are not allowed to manage revenue settings for this project',
+ )
+
+ // Validate API key with Paddle
+ const isValid = await this.paddleAdapter.validateApiKey(dto.apiKey)
+ if (!isValid) {
+ throw new BadRequestException(
+ 'Invalid Paddle API key. Please check your key and try again.',
+ )
+ }
+
+ const result = await this.revenueService.connectPaddle(
+ pid,
+ dto.apiKey,
+ dto.currency || 'USD',
+ )
+
+ if (!result.success) {
+ throw new BadRequestException(result.message)
+ }
+
+ return { success: true }
+ }
+
+ @ApiBearerAuth()
+ @Delete('/:pid/revenue/disconnect')
+ @Auth()
+ @ApiResponse({ status: 204 })
+ async disconnectPaddle(
+ @CurrentUserId() userId: string,
+ @Param('pid') pid: string,
+ ) {
+ this.logger.log({ userId, pid }, 'DELETE /project/:pid/revenue/disconnect')
+
+ const project = await this.projectService.getFullProject(pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project not found')
+ }
+
+ this.projectService.allowedToManage(
+ project,
+ userId,
+ 'You are not allowed to manage revenue settings for this project',
+ )
+
+ await this.revenueService.disconnectPaddle(pid)
+ }
+
+ @ApiBearerAuth()
+ @Post('/:pid/revenue/currency')
+ @Auth()
+ async updateCurrency(
+ @CurrentUserId() userId: string,
+ @Param('pid') pid: string,
+ @Body() dto: UpdateRevenueCurrencyDto,
+ ) {
+ this.logger.log(
+ { userId, pid, currency: dto.currency },
+ 'POST /project/:pid/revenue/currency',
+ )
+
+ const project = await this.projectService.getFullProject(pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project not found')
+ }
+
+ this.projectService.allowedToManage(
+ project,
+ userId,
+ 'You are not allowed to manage revenue settings for this project',
+ )
+
+ await this.revenueService.updateCurrency(pid, dto.currency)
+
+ return { success: true }
+ }
+
+ @ApiBearerAuth()
+ @Post('/:pid/revenue/sync')
+ @Auth()
+ async syncRevenue(
+ @CurrentUserId() userId: string,
+ @Param('pid') pid: string,
+ ) {
+ this.logger.log({ userId, pid }, 'POST /project/:pid/revenue/sync')
+
+ const project = await this.projectService.getFullProject(pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project not found')
+ }
+
+ this.projectService.allowedToManage(
+ project,
+ userId,
+ 'You are not allowed to manage revenue settings for this project',
+ )
+
+ if (!project.paddleApiKeyEnc) {
+ throw new BadRequestException('Paddle is not connected to this project')
+ }
+
+ const apiKey = this.revenueService.getPaddleApiKey(project)
+ if (!apiKey) {
+ throw new BadRequestException('Failed to decrypt Paddle API key')
+ }
+
+ const count = await this.paddleAdapter.syncTransactions(
+ pid,
+ apiKey,
+ project.revenueCurrency || 'USD',
+ project.revenueLastSyncAt || undefined,
+ )
+
+ await this.revenueService.updateLastSyncAt(pid)
+
+ return { success: true, transactionsSynced: count }
+ }
+}
+
+@ApiTags('Revenue Analytics')
+@Controller('log/revenue')
+export class RevenueAnalyticsController {
+ constructor(
+ private readonly revenueService: RevenueService,
+ private readonly projectService: ProjectService,
+ private readonly analyticsService: AnalyticsService,
+ private readonly logger: AppLoggerService,
+ ) {}
+
+ @ApiBearerAuth()
+ @Get('/')
+ @Auth()
+ @ApiResponse({ status: 200 })
+ async getRevenueStats(
+ @CurrentUserId() userId: string,
+ @Query() dto: GetRevenueDto,
+ ): Promise<{
+ stats: RevenueStatsDto
+ chart: RevenueChartDto
+ }> {
+ this.logger.log({ userId, ...dto }, 'GET /log/revenue')
+
+ const project = await this.projectService.getFullProject(dto.pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project not found')
+ }
+
+ this.projectService.allowedToView(project, userId)
+
+ if (!project.paddleApiKeyEnc) {
+ throw new BadRequestException(
+ 'Revenue tracking is not configured for this project',
+ )
+ }
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(dto.timezone)
+ const timeBucket =
+ dto.timeBucket ||
+ getLowestPossibleTimeBucket(dto.period, dto.from, dto.to)
+
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ dto.from,
+ dto.to,
+ timeBucket as any,
+ dto.period,
+ safeTimezone,
+ )
+
+ const { xShifted } = this.analyticsService.generateXAxis(
+ timeBucket as any,
+ groupFromUTC,
+ groupToUTC,
+ safeTimezone,
+ )
+
+ const currency = project.revenueCurrency || 'USD'
+
+ const [stats, chart] = await Promise.all([
+ this.revenueService.getRevenueStats(
+ dto.pid,
+ groupFromUTC,
+ groupToUTC,
+ currency,
+ ),
+ this.revenueService.getRevenueChart(
+ dto.pid,
+ groupFromUTC,
+ groupToUTC,
+ timeBucket,
+ safeTimezone,
+ xShifted,
+ ),
+ ])
+
+ return { stats, chart }
+ }
+
+ @ApiBearerAuth()
+ @Get('/transactions')
+ @Auth()
+ @ApiResponse({ status: 200 })
+ async getRevenueTransactions(
+ @CurrentUserId() userId: string,
+ @Query() dto: GetRevenueTransactionsDto,
+ ): Promise<{ transactions: RevenueTransactionDto[]; total: number }> {
+ this.logger.log({ userId, ...dto }, 'GET /log/revenue/transactions')
+
+ const project = await this.projectService.getFullProject(dto.pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project not found')
+ }
+
+ this.projectService.allowedToView(project, userId)
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(dto.timezone)
+ const timeBucket = getLowestPossibleTimeBucket(dto.period, dto.from, dto.to)
+
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ dto.from,
+ dto.to,
+ timeBucket as any,
+ dto.period,
+ safeTimezone,
+ )
+
+ return this.revenueService.getRevenueTransactions(
+ dto.pid,
+ groupFromUTC,
+ groupToUTC,
+ dto.take || 20,
+ dto.skip || 0,
+ dto.type,
+ dto.status,
+ )
+ }
+
+ @ApiBearerAuth()
+ @Get('/breakdown')
+ @Auth()
+ @ApiResponse({ status: 200, type: RevenueBreakdownDto })
+ async getRevenueBreakdown(
+ @CurrentUserId() userId: string,
+ @Query() dto: GetRevenueDto,
+ ): Promise<RevenueBreakdownDto> {
+ this.logger.log({ userId, ...dto }, 'GET /log/revenue/breakdown')
+
+ const project = await this.projectService.getFullProject(dto.pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project not found')
+ }
+
+ this.projectService.allowedToView(project, userId)
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(dto.timezone)
+ const timeBucket = getLowestPossibleTimeBucket(dto.period, dto.from, dto.to)
+
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ dto.from,
+ dto.to,
+ timeBucket as any,
+ dto.period,
+ safeTimezone,
+ )
+
+ return this.revenueService.getRevenueBreakdown(
+ dto.pid,
+ groupFromUTC,
+ groupToUTC,
+ )
+ }
+}
diff --git a/backend/apps/cloud/src/revenue/revenue.module.ts b/backend/apps/cloud/src/revenue/revenue.module.ts
new file mode 100644
index 000000000..3fc5e54cd
--- /dev/null
+++ b/backend/apps/cloud/src/revenue/revenue.module.ts
@@ -0,0 +1,26 @@
+import { Module, forwardRef } from '@nestjs/common'
+import { TypeOrmModule } from '@nestjs/typeorm'
+
+import { ProjectModule } from '../project/project.module'
+import { AppLoggerModule } from '../logger/logger.module'
+import { AnalyticsModule } from '../analytics/analytics.module'
+import { Project } from '../project/entity/project.entity'
+import { RevenueService } from './revenue.service'
+import {
+ RevenueController,
+ RevenueAnalyticsController,
+} from './revenue.controller'
+import { PaddleAdapter } from './adapters/paddle.adapter'
+
+@Module({
+ imports: [
+ TypeOrmModule.forFeature([Project]),
+ forwardRef(() => ProjectModule),
+ AppLoggerModule,
+ forwardRef(() => AnalyticsModule),
+ ],
+ providers: [RevenueService, PaddleAdapter],
+ exports: [RevenueService, PaddleAdapter],
+ controllers: [RevenueController, RevenueAnalyticsController],
+})
+export class RevenueModule {}
diff --git a/backend/apps/cloud/src/revenue/revenue.service.ts b/backend/apps/cloud/src/revenue/revenue.service.ts
new file mode 100644
index 000000000..499650997
--- /dev/null
+++ b/backend/apps/cloud/src/revenue/revenue.service.ts
@@ -0,0 +1,642 @@
+import { Injectable } from '@nestjs/common'
+import { InjectRepository } from '@nestjs/typeorm'
+import { Repository } from 'typeorm'
+import _round from 'lodash/round'
+import dayjs from 'dayjs'
+import * as crypto from 'crypto'
+
+import { Project } from '../project/entity/project.entity'
+import { clickhouse } from '../common/integrations/clickhouse'
+import { AppLoggerService } from '../logger/logger.service'
+import {
+ RevenueTransaction,
+ PADDLE_REQUIRED_PERMISSIONS,
+} from './interfaces/revenue.interface'
+import {
+ RevenueStatsDto,
+ RevenueChartDto,
+ RevenueTransactionDto,
+ RevenueBreakdownDto,
+} from './dto/revenue-stats.dto'
+
+const timeBucketConversion: Record<string, string> = {
+ minute: 'toStartOfMinute',
+ hour: 'toStartOfHour',
+ day: 'toStartOfDay',
+ month: 'toStartOfMonth',
+ year: 'toStartOfYear',
+}
+
+@Injectable()
+export class RevenueService {
+ private readonly encryptionKey: Buffer
+
+ constructor(
+ @InjectRepository(Project)
+ private readonly projectRepository: Repository<Project>,
+ private readonly logger: AppLoggerService,
+ ) {
+ // Use a 32-byte key from JWT_ACCESS_TOKEN_SECRET
+ const secret = process.env.JWT_ACCESS_TOKEN_SECRET || 'default-secret-key'
+ this.encryptionKey = crypto.scryptSync(secret, 'revenue-salt', 32)
+ }
+
+ private encrypt(text: string): string {
+ const iv = crypto.randomBytes(16)
+ const cipher = crypto.createCipheriv('aes-256-cbc', this.encryptionKey, iv)
+ let encrypted = cipher.update(text, 'utf8', 'hex')
+ encrypted += cipher.final('hex')
+ return iv.toString('hex') + ':' + encrypted
+ }
+
+ private decrypt(encryptedText: string): string {
+ const [ivHex, encrypted] = encryptedText.split(':')
+ const iv = Buffer.from(ivHex, 'hex')
+ const decipher = crypto.createDecipheriv(
+ 'aes-256-cbc',
+ this.encryptionKey,
+ iv,
+ )
+ let decrypted = decipher.update(encrypted, 'hex', 'utf8')
+ decrypted += decipher.final('utf8')
+ return decrypted
+ }
+
+ async connectPaddle(
+ projectId: string,
+ apiKey: string,
+ currency: string = 'USD',
+ ): Promise<{ success: boolean; message?: string }> {
+ try {
+ // Encrypt the API key before storing
+ const encryptedKey = this.encrypt(apiKey)
+
+ await this.projectRepository.update(projectId, {
+ paddleApiKeyEnc: encryptedKey,
+ revenueCurrency: currency,
+ paddleApiKeyPermissions: JSON.stringify(PADDLE_REQUIRED_PERMISSIONS),
+ revenueLastSyncAt: null,
+ })
+
+ return { success: true }
+ } catch (error) {
+ this.logger.error({ error, projectId }, 'Failed to connect Paddle')
+ return { success: false, message: 'Failed to save Paddle configuration' }
+ }
+ }
+
+ async disconnectPaddle(projectId: string): Promise<void> {
+ await this.projectRepository.update(projectId, {
+ paddleApiKeyEnc: null,
+ paddleApiKeyPermissions: null,
+ revenueLastSyncAt: null,
+ })
+ }
+
+ async getRevenueStatus(project: Project): Promise<{
+ connected: boolean
+ provider?: string
+ currency?: string
+ lastSyncAt?: string
+ }> {
+ const connected = !!project.paddleApiKeyEnc
+ return {
+ connected,
+ provider: connected ? 'paddle' : undefined,
+ currency: project.revenueCurrency || undefined,
+ lastSyncAt: project.revenueLastSyncAt?.toISOString() || undefined,
+ }
+ }
+
+ async updateCurrency(projectId: string, currency: string): Promise<void> {
+ await this.projectRepository.update(projectId, {
+ revenueCurrency: currency,
+ })
+ }
+
+ getPaddleApiKey(project: Project): string | null {
+ if (!project.paddleApiKeyEnc) {
+ return null
+ }
+ try {
+ return this.decrypt(project.paddleApiKeyEnc)
+ } catch {
+ return null
+ }
+ }
+
+ async getRevenueStats(
+ projectId: string,
+ groupFromUTC: string,
+ groupToUTC: string,
+ currency: string,
+ ): Promise<RevenueStatsDto> {
+ // Get current period stats
+ const statsQuery = `
+ SELECT
+ sum(CASE WHEN type = 'sale' THEN amount ELSE 0 END) as totalRevenue,
+ count(CASE WHEN type = 'sale' THEN 1 ELSE NULL END) as salesCount,
+ count(CASE WHEN type = 'refund' THEN 1 ELSE NULL END) as refundsCount,
+ sum(CASE WHEN type = 'refund' THEN abs(amount) ELSE 0 END) as refundsAmount,
+ sum(CASE WHEN type = 'subscription' THEN amount ELSE 0 END) as subscriptionRevenue
+ FROM (
+ SELECT
+ pid,
+ transaction_id,
+ argMax(type, synced_at) as type,
+ argMax(amount, synced_at) as amount,
+ argMax(created, synced_at) as created_at
+ FROM revenue
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND revenue.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY pid, transaction_id
+ ) AS latest
+ `
+
+ const { data: statsData } = await clickhouse
+ .query({
+ query: statsQuery,
+ query_params: {
+ pid: projectId,
+ groupFrom: groupFromUTC,
+ groupTo: groupToUTC,
+ },
+ })
+ .then(resultSet =>
+ resultSet.json<{
+ totalRevenue: number
+ salesCount: number
+ refundsCount: number
+ refundsAmount: number
+ subscriptionRevenue: number
+ }>(),
+ )
+
+ const stats = statsData[0] || {
+ totalRevenue: 0,
+ salesCount: 0,
+ refundsCount: 0,
+ refundsAmount: 0,
+ subscriptionRevenue: 0,
+ }
+
+ // Calculate average order value
+ const averageOrderValue =
+ stats.salesCount > 0
+ ? _round(stats.totalRevenue / stats.salesCount, 2)
+ : 0
+
+ // Estimate MRR from subscription revenue (simple calculation)
+ // In a real implementation, this would need more sophisticated logic
+ const mrr = _round(stats.subscriptionRevenue, 2)
+
+ // Get previous period stats for comparison
+ const periodDays = dayjs(groupToUTC).diff(dayjs(groupFromUTC), 'day') || 1
+ const previousFrom = dayjs(groupFromUTC)
+ .subtract(periodDays, 'day')
+ .format('YYYY-MM-DD HH:mm:ss')
+
+ const { data: previousData } = await clickhouse
+ .query({
+ query: statsQuery,
+ query_params: {
+ pid: projectId,
+ groupFrom: previousFrom,
+ groupTo: groupFromUTC,
+ },
+ })
+ .then(resultSet => resultSet.json<{ totalRevenue: number }>())
+
+ const previousRevenue = previousData[0]?.totalRevenue || 0
+ const revenueChange =
+ previousRevenue > 0
+ ? _round(
+ ((stats.totalRevenue - previousRevenue) / previousRevenue) * 100,
+ 2,
+ )
+ : stats.totalRevenue > 0
+ ? 100
+ : 0
+
+ return {
+ totalRevenue: _round(stats.totalRevenue, 2),
+ salesCount: stats.salesCount,
+ refundsCount: stats.refundsCount,
+ refundsAmount: _round(stats.refundsAmount, 2),
+ averageOrderValue,
+ currency,
+ mrr,
+ revenueChange,
+ }
+ }
+
+ async getRevenueChart(
+ projectId: string,
+ groupFromUTC: string,
+ groupToUTC: string,
+ timeBucket: string,
+ timezone: string,
+ xAxis: string[],
+ ): Promise<RevenueChartDto> {
+ const timeBucketFunc = timeBucketConversion[timeBucket] || 'toStartOfDay'
+ const [selector, groupBy] = this.getGroupSubquery(timeBucket)
+
+ const chartQuery = `
+ SELECT
+ ${selector},
+ sum(CASE WHEN type = 'sale' THEN amount ELSE 0 END) as revenue,
+ count(CASE WHEN type = 'sale' THEN 1 ELSE NULL END) as salesCount,
+ sum(CASE WHEN type = 'refund' THEN abs(amount) ELSE 0 END) as refundsAmount
+ FROM (
+ SELECT
+ pid,
+ transaction_id,
+ argMax(type, synced_at) as type,
+ argMax(amount, synced_at) as amount,
+ argMax(created, synced_at) as created_at,
+ ${timeBucketFunc}(toTimeZone(argMax(created, synced_at), {timezone:String})) as tz_created
+ FROM revenue
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND revenue.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY pid, transaction_id
+ ) as subquery
+ GROUP BY ${groupBy}
+ ORDER BY ${groupBy}
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query: chartQuery,
+ query_params: {
+ pid: projectId,
+ groupFrom: groupFromUTC,
+ groupTo: groupToUTC,
+ timezone,
+ },
+ })
+ .then(resultSet =>
+ resultSet.json<{
+ year: number
+ month?: number
+ day?: number
+ hour?: number
+ minute?: number
+ revenue: number
+ salesCount: number
+ refundsAmount: number
+ }>(),
+ )
+
+ // Initialize arrays with zeros
+ const revenue = Array(xAxis.length).fill(0)
+ const salesCount = Array(xAxis.length).fill(0)
+ const refundsAmount = Array(xAxis.length).fill(0)
+
+ // Fill in actual data
+ for (const row of data) {
+ const dateString = this.generateDateString(row)
+ const index = xAxis.indexOf(dateString)
+
+ if (index !== -1) {
+ revenue[index] = _round(row.revenue, 2)
+ salesCount[index] = row.salesCount
+ refundsAmount[index] = _round(row.refundsAmount, 2)
+ }
+ }
+
+ return {
+ x: xAxis,
+ revenue,
+ salesCount,
+ refundsAmount,
+ }
+ }
+
+ async getRevenueTransactions(
+ projectId: string,
+ groupFromUTC: string,
+ groupToUTC: string,
+ take: number = 20,
+ skip: number = 0,
+ type?: string,
+ status?: string,
+ ): Promise<{ transactions: RevenueTransactionDto[]; total: number }> {
+ const params: Record<string, unknown> = {
+ pid: projectId,
+ groupFrom: groupFromUTC,
+ groupTo: groupToUTC,
+ }
+
+ // Build filters for the "latest-per-transaction" view
+ const filters: string[] = []
+ if (type) {
+ filters.push(`type = {type:String}`)
+ params.type = type
+ }
+
+ if (status) {
+ filters.push(`status = {status:String}`)
+ params.status = status
+ }
+
+ const filtersSql = filters.length ? `WHERE ${filters.join(' AND ')}` : ''
+
+ if (type) {
+ // handled above
+ }
+
+ if (status) {
+ // handled above
+ }
+
+ // Get total count
+ const countQuery = `
+ SELECT count(*) as total
+ FROM (
+ SELECT
+ pid,
+ transaction_id,
+ argMax(provider, synced_at) as provider,
+ argMax(type, synced_at) as type,
+ argMax(status, synced_at) as status,
+ argMax(amount, synced_at) as amount,
+ argMax(currency, synced_at) as currency,
+ argMax(original_amount, synced_at) as original_amount,
+ argMax(original_currency, synced_at) as original_currency,
+ argMax(customer_email, synced_at) as customer_email,
+ argMax(product_name, synced_at) as product_name,
+ argMax(profile_id, synced_at) as profile_id,
+ argMax(session_id, synced_at) as session_id,
+ argMax(created, synced_at) as created_at
+ FROM revenue
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND revenue.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY pid, transaction_id
+ ) AS latest
+ ${filtersSql}
+ `
+ const { data: countData } = await clickhouse
+ .query({ query: countQuery, query_params: params })
+ .then(resultSet => resultSet.json<{ total: number }>())
+
+ // Get transactions
+ const transactionsQuery = `
+ SELECT
+ transaction_id,
+ provider,
+ type,
+ status,
+ amount,
+ currency,
+ original_amount,
+ original_currency,
+ customer_email,
+ product_name,
+ profile_id,
+ session_id,
+ created_at as created
+ FROM (
+ SELECT
+ pid,
+ transaction_id,
+ argMax(provider, synced_at) as provider,
+ argMax(type, synced_at) as type,
+ argMax(status, synced_at) as status,
+ argMax(amount, synced_at) as amount,
+ argMax(currency, synced_at) as currency,
+ argMax(original_amount, synced_at) as original_amount,
+ argMax(original_currency, synced_at) as original_currency,
+ argMax(customer_email, synced_at) as customer_email,
+ argMax(product_name, synced_at) as product_name,
+ argMax(profile_id, synced_at) as profile_id,
+ argMax(session_id, synced_at) as session_id,
+ argMax(created, synced_at) as created_at
+ FROM revenue
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND revenue.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY pid, transaction_id
+ ) AS latest
+ ${filtersSql}
+ ORDER BY created_at DESC
+ LIMIT {take:UInt32} OFFSET {skip:UInt32}
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query: transactionsQuery,
+ query_params: { ...params, take, skip },
+ })
+ .then(resultSet =>
+ resultSet.json<{
+ transaction_id: string
+ provider: string
+ type: string
+ status: string
+ amount: number
+ currency: string
+ original_amount: number
+ original_currency: string
+ customer_email: string | null
+ product_name: string | null
+ profile_id: string | null
+ session_id: string | null
+ created: string
+ }>(),
+ )
+
+ const transactions: RevenueTransactionDto[] = data.map(row => ({
+ transactionId: row.transaction_id,
+ provider: row.provider,
+ type: row.type,
+ status: row.status,
+ amount: _round(row.amount, 2),
+ currency: row.currency,
+ originalAmount: _round(row.original_amount, 2),
+ originalCurrency: row.original_currency,
+ customerEmail: row.customer_email || undefined,
+ productName: row.product_name || undefined,
+ profileId: row.profile_id || undefined,
+ sessionId: row.session_id || undefined,
+ created: row.created,
+ }))
+
+ return {
+ transactions,
+ total: countData[0]?.total || 0,
+ }
+ }
+
+ async getRevenueBreakdown(
+ projectId: string,
+ groupFromUTC: string,
+ groupToUTC: string,
+ ): Promise<RevenueBreakdownDto> {
+ const params = {
+ pid: projectId,
+ groupFrom: groupFromUTC,
+ groupTo: groupToUTC,
+ }
+
+ // By product
+ const byProductQuery = `
+ SELECT
+ COALESCE(product_name, 'Unknown') as name,
+ sum(CASE WHEN type = 'sale' THEN amount ELSE 0 END) as revenue,
+ count(CASE WHEN type = 'sale' THEN 1 ELSE NULL END) as count
+ FROM (
+ SELECT
+ pid,
+ transaction_id,
+ argMax(product_name, synced_at) as product_name,
+ argMax(type, synced_at) as type,
+ argMax(amount, synced_at) as amount,
+ argMax(created, synced_at) as created_at
+ FROM revenue
+ WHERE pid = {pid:FixedString(12)}
+ AND revenue.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY pid, transaction_id
+ ) AS latest
+ GROUP BY name
+ ORDER BY revenue DESC
+ LIMIT 10
+ `
+
+ const { data: byProductData } = await clickhouse
+ .query({ query: byProductQuery, query_params: params })
+ .then(resultSet =>
+ resultSet.json<{ name: string; revenue: number; count: number }>(),
+ )
+
+ // For source and country, we'd need to join with analytics table
+ // For now, return empty arrays - these will be populated when we have attribution
+ return {
+ bySource: [],
+ byCountry: [],
+ byProduct: byProductData.map(row => ({
+ name: row.name,
+ revenue: _round(row.revenue, 2),
+ count: row.count,
+ })),
+ }
+ }
+
+ async insertTransaction(transaction: RevenueTransaction): Promise<void> {
+ // Format date for ClickHouse DateTime (YYYY-MM-DD HH:mm:ss)
+ const formatDateForCH = (date: Date): string => {
+ return date
+ .toISOString()
+ .replace('T', ' ')
+ .replace(/\.\d{3}Z$/, '')
+ }
+
+ await clickhouse.insert({
+ table: 'revenue',
+ values: [
+ {
+ pid: transaction.pid,
+ transaction_id: transaction.transactionId,
+ provider: transaction.provider,
+ type: transaction.type,
+ status: transaction.status,
+ amount: transaction.amount,
+ original_amount: transaction.originalAmount,
+ original_currency: transaction.originalCurrency,
+ currency: transaction.currency,
+ profile_id: transaction.profileId || null,
+ session_id: transaction.sessionId || null,
+ customer_email: transaction.customerEmail || null,
+ product_id: transaction.productId || null,
+ product_name: transaction.productName || null,
+ metadata: JSON.stringify(transaction.metadata || {}),
+ created: formatDateForCH(transaction.created),
+ synced_at: formatDateForCH(transaction.syncedAt),
+ },
+ ],
+ format: 'JSONEachRow',
+ })
+ }
+
+ async updateLastSyncAt(projectId: string): Promise<void> {
+ await this.projectRepository.update(projectId, {
+ revenueLastSyncAt: new Date(),
+ })
+ }
+
+ private getGroupSubquery(
+ timeBucket: string,
+ ): [selector: string, groupBy: string] {
+ if (timeBucket === 'minute') {
+ return [
+ 'toYear(tz_created) as year, toMonth(tz_created) as month, toDayOfMonth(tz_created) as day, toHour(tz_created) as hour, toMinute(tz_created) as minute',
+ 'year, month, day, hour, minute',
+ ]
+ }
+
+ if (timeBucket === 'hour') {
+ return [
+ 'toYear(tz_created) as year, toMonth(tz_created) as month, toDayOfMonth(tz_created) as day, toHour(tz_created) as hour',
+ 'year, month, day, hour',
+ ]
+ }
+
+ if (timeBucket === 'day') {
+ return [
+ 'toYear(tz_created) as year, toMonth(tz_created) as month, toDayOfMonth(tz_created) as day',
+ 'year, month, day',
+ ]
+ }
+
+ if (timeBucket === 'month') {
+ return [
+ 'toYear(tz_created) as year, toMonth(tz_created) as month',
+ 'year, month',
+ ]
+ }
+
+ // year
+ return ['toYear(tz_created) as year', 'year']
+ }
+
+ private generateDateString(row: { [key: string]: number }): string {
+ const { year, month, day, hour, minute } = row
+
+ let dateString = `${year}`
+
+ if (typeof month === 'number') {
+ if (month < 10) {
+ dateString += `-0${month}`
+ } else {
+ dateString += `-${month}`
+ }
+ }
+
+ if (typeof day === 'number') {
+ if (day < 10) {
+ dateString += `-0${day}`
+ } else {
+ dateString += `-${day}`
+ }
+ }
+
+ if (typeof hour === 'number') {
+ const strMinute =
+ typeof minute === 'number'
+ ? minute < 10
+ ? `0${minute}`
+ : minute
+ : '00'
+
+ if (hour < 10) {
+ dateString += ` 0${hour}:${strMinute}:00`
+ } else {
+ dateString += ` ${hour}:${strMinute}:00`
+ }
+ }
+
+ return dateString
+ }
+}
diff --git a/backend/apps/cloud/src/task-manager/task-manager.module.ts b/backend/apps/cloud/src/task-manager/task-manager.module.ts
index 358535db0..376830b97 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.module.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.module.ts
@@ -15,6 +15,7 @@ import { Message } from '../integrations/telegram/entities/message.entity'
import { DiscordModule } from '../integrations/discord/discord.module'
import { SlackModule } from '../integrations/slack/slack.module'
import { GoalModule } from '../goal/goal.module'
+import { RevenueModule } from '../revenue/revenue.module'
@Module({
imports: [
@@ -31,6 +32,7 @@ import { GoalModule } from '../goal/goal.module'
DiscordModule,
SlackModule,
GoalModule,
+ RevenueModule,
],
providers: [TaskManagerService, TelegramService],
exports: [TaskManagerService],
diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.ts
index a453529dc..6a2ff7c51 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts
@@ -59,6 +59,8 @@ import { getRandomTip } from '../common/utils'
import { AppLoggerService } from '../logger/logger.service'
import { DiscordService } from '../integrations/discord/discord.service'
import { SlackService } from '../integrations/slack/slack.service'
+import { RevenueService } from '../revenue/revenue.service'
+import { PaddleAdapter } from '../revenue/adapters/paddle.adapter'
dayjs.extend(utc)
@@ -323,6 +325,8 @@ export class TaskManagerService {
private readonly slackService: SlackService,
private readonly saltService: SaltService,
private readonly goalService: GoalService,
+ private readonly revenueService: RevenueService,
+ private readonly paddleAdapter: PaddleAdapter,
) {}
/**
@@ -1076,6 +1080,57 @@ export class TaskManagerService {
await this.saltService.regenerateExpiredSalts()
}
+ // Sync revenue data from payment providers every 30 minutes
+ @Cron(CronExpression.EVERY_30_MINUTES)
+ async syncRevenueData() {
+ // Find all projects with Paddle connected
+ const projects = await this.projectService.find({
+ where: {
+ paddleApiKeyEnc: Not(IsNull()),
+ admin: {
+ planCode: Not(PlanCode.none),
+ dashboardBlockReason: IsNull(),
+ },
+ },
+ relations: ['admin'],
+ })
+
+ if (_isEmpty(projects)) {
+ return
+ }
+
+ const promises = _map(projects, async project => {
+ try {
+ const apiKey = this.revenueService.getPaddleApiKey(project)
+ if (!apiKey) {
+ this.logger.warn(
+ `[CRON WORKER](syncRevenueData) Failed to decrypt Paddle API key for project ${project.id}`,
+ )
+ return
+ }
+
+ await this.paddleAdapter.syncTransactions(
+ project.id,
+ apiKey,
+ project.revenueCurrency || 'USD',
+ project.revenueLastSyncAt || undefined,
+ )
+
+ await this.revenueService.updateLastSyncAt(project.id)
+ } catch (error) {
+ this.logger.error(
+ `[CRON WORKER](syncRevenueData) Error syncing project ${project.id}: ${error}`,
+ )
+ }
+ })
+
+ await Promise.allSettled(promises).catch(reason => {
+ this.logger.error(
+ `[CRON WORKER](syncRevenueData) Error occured: ${reason}`,
+ )
+ })
+ }
+
// EVERY SUNDAY AT 2:30 AM
@Cron('30 02 * * 0')
async weeklyReportsHandler() {
diff --git a/backend/migrations/clickhouse/2025_12_15_revenue.js b/backend/migrations/clickhouse/2025_12_15_revenue.js
new file mode 100644
index 000000000..979d00431
--- /dev/null
+++ b/backend/migrations/clickhouse/2025_12_15_revenue.js
@@ -0,0 +1,30 @@
+const { queriesRunner, dbName } = require('./setup')
+
+const queries = [
+ // Revenue table for storing payment/transaction data from payment providers
+ `CREATE TABLE IF NOT EXISTS ${dbName}.revenue
+ (
+ pid FixedString(12),
+ transaction_id String CODEC(ZSTD(3)),
+ provider LowCardinality(String),
+ type LowCardinality(String),
+ status LowCardinality(String),
+ amount Decimal64(4),
+ original_amount Decimal64(4),
+ original_currency LowCardinality(String),
+ currency LowCardinality(String),
+ profile_id Nullable(String) CODEC(ZSTD(3)),
+ session_id Nullable(String) CODEC(ZSTD(3)),
+ customer_email Nullable(String) CODEC(ZSTD(3)),
+ product_id Nullable(String) CODEC(ZSTD(3)),
+ product_name Nullable(String) CODEC(ZSTD(3)),
+ metadata String DEFAULT '{}' CODEC(ZSTD(3)),
+ created DateTime('UTC') CODEC(Delta(4), LZ4),
+ synced_at DateTime('UTC') CODEC(Delta(4), LZ4)
+ )
+ ENGINE = ReplacingMergeTree(synced_at)
+ PARTITION BY toYYYYMM(created)
+ ORDER BY (pid, transaction_id);`,
+]
+
+queriesRunner(queries)
diff --git a/backend/migrations/clickhouse/initialise_database.js b/backend/migrations/clickhouse/initialise_database.js
index fe8e4ebc3..b623f713b 100644
--- a/backend/migrations/clickhouse/initialise_database.js
+++ b/backend/migrations/clickhouse/initialise_database.js
@@ -206,6 +206,31 @@ const CLICKHOUSE_INIT_QUERIES = [
ENGINE = MergeTree()
PARTITION BY toYYYYMM(created)
ORDER BY (pid, created);`,
+
+ // Revenue table for storing payment/transaction data from payment providers
+ `CREATE TABLE IF NOT EXISTS ${dbName}.revenue
+ (
+ pid FixedString(12),
+ transaction_id String CODEC(ZSTD(3)),
+ provider LowCardinality(String),
+ type LowCardinality(String),
+ status LowCardinality(String),
+ amount Decimal64(4),
+ original_amount Decimal64(4),
+ original_currency LowCardinality(String),
+ currency LowCardinality(String),
+ profile_id Nullable(String) CODEC(ZSTD(3)),
+ session_id Nullable(String) CODEC(ZSTD(3)),
+ customer_email Nullable(String) CODEC(ZSTD(3)),
+ product_id Nullable(String) CODEC(ZSTD(3)),
+ product_name Nullable(String) CODEC(ZSTD(3)),
+ metadata String DEFAULT '{}' CODEC(ZSTD(3)),
+ created DateTime('UTC') CODEC(Delta(4), LZ4),
+ synced_at DateTime('UTC') CODEC(Delta(4), LZ4)
+ )
+ ENGINE = ReplacingMergeTree(synced_at)
+ PARTITION BY toYYYYMM(created)
+ ORDER BY (pid, transaction_id);`,
]
const initialiseDatabase = async () => {
diff --git a/backend/migrations/mysql/2025_12_15_revenue.sql b/backend/migrations/mysql/2025_12_15_revenue.sql
new file mode 100644
index 000000000..25c388567
--- /dev/null
+++ b/backend/migrations/mysql/2025_12_15_revenue.sql
@@ -0,0 +1,5 @@
+-- Revenue / Payment provider integration fields for Project table
+ALTER TABLE `project` ADD COLUMN `paddleApiKeyEnc` text DEFAULT NULL;
+ALTER TABLE `project` ADD COLUMN `revenueCurrency` varchar(3) DEFAULT NULL;
+ALTER TABLE `project` ADD COLUMN `paddleApiKeyPermissions` text DEFAULT NULL;
+ALTER TABLE `project` ADD COLUMN `revenueLastSyncAt` datetime DEFAULT NULL;
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index e3b75542d..802248577 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -2431,3 +2431,96 @@ export const deleteAIChat = async (pid: string, chatId: string): Promise<{ succe
throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
})
}
+
+// Revenue API
+export interface RevenueStatus {
+ connected: boolean
+ provider?: string
+ currency?: string
+ lastSyncAt?: string
+}
+
+export interface RevenueStats {
+ totalRevenue: number
+ salesCount: number
+ refundsCount: number
+ refundsAmount: number
+ averageOrderValue: number
+ currency: string
+ mrr: number
+ revenueChange: number
+}
+
+export interface RevenueChart {
+ x: string[]
+ revenue: number[]
+ salesCount: number[]
+ refundsAmount: number[]
+}
+
+export const getRevenueStatus = async (pid: string): Promise<RevenueStatus> => {
+ return api
+ .get(`project/${pid}/revenue/status`)
+ .then((response): RevenueStatus => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
+ })
+}
+
+export const connectPaddleRevenue = async (
+ pid: string,
+ apiKey: string,
+ currency: string = 'USD',
+): Promise<{ success: boolean }> => {
+ return api
+ .post(`project/${pid}/revenue/connect`, { apiKey, currency })
+ .then((response): { success: boolean } => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
+ })
+}
+
+export const disconnectPaddleRevenue = async (pid: string): Promise<void> => {
+ return api
+ .delete(`project/${pid}/revenue/disconnect`)
+ .then((response) => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
+ })
+}
+
+export const syncRevenue = async (pid: string): Promise<{ success: boolean; transactionsSynced: number }> => {
+ return api
+ .post(`project/${pid}/revenue/sync`)
+ .then((response): { success: boolean; transactionsSynced: number } => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
+ })
+}
+
+export const updateRevenueCurrency = async (pid: string, currency: string): Promise<{ success: boolean }> => {
+ return api
+ .post(`project/${pid}/revenue/currency`, { currency })
+ .then((response): { success: boolean } => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
+ })
+}
+
+export const getRevenueData = async (
+ pid: string,
+ period: string,
+ from?: string,
+ to?: string,
+ timezone?: string,
+ timeBucket?: string,
+): Promise<{ stats: RevenueStats; chart: RevenueChart }> => {
+ return api
+ .get('log/revenue', {
+ params: { pid, period, from, to, timezone, timeBucket },
+ })
+ .then((response): { stats: RevenueStats; chart: RevenueChart } => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
+ })
+}
diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.ts
index 5bf6e6530..a15abbc9b 100644
--- a/web/app/lib/models/Project.ts
+++ b/web/app/lib/models/Project.ts
@@ -100,6 +100,8 @@ export interface Session {
pageviews: number
customEvents: number
errors: number
+ revenue?: number
+ refunds?: number
created: string
isLive: 1 | 0
sdur?: number
@@ -164,6 +166,8 @@ export interface ProfileDetails extends Profile {
errors: number[]
}
timeBucket?: string
+ totalRevenue?: number
+ revenueCurrency?: string
}
export interface AnalyticsFunnel {
diff --git a/web/app/pages/Project/Profiles/View/ProfilesView.tsx b/web/app/pages/Project/Profiles/View/ProfilesView.tsx
index 2e11f5f2c..323b5d0ee 100644
--- a/web/app/pages/Project/Profiles/View/ProfilesView.tsx
+++ b/web/app/pages/Project/Profiles/View/ProfilesView.tsx
@@ -337,6 +337,7 @@ const ProfilesView = ({ chartType }: ProfilesViewProps) => {
}
}}
canLoadMoreSessions={canLoadMoreProfileSessions}
+ currency={project?.revenueCurrency}
/>
)}
</>
diff --git a/web/app/pages/Project/Sessions/View/SessionsView.tsx b/web/app/pages/Project/Sessions/View/SessionsView.tsx
index f0880f9df..d80f5cab2 100644
--- a/web/app/pages/Project/Sessions/View/SessionsView.tsx
+++ b/web/app/pages/Project/Sessions/View/SessionsView.tsx
@@ -301,7 +301,7 @@ const SessionsView = ({ tnMapping, chartType, rotateXAxis }: SessionsViewProps)
{typeof sessionsLoading === 'boolean' && !sessionsLoading && _isEmpty(sessions) ? (
<NoEvents filters={filters} />
) : null}
- <Sessions sessions={sessions} timeFormat={timeFormat} />
+ <Sessions sessions={sessions} timeFormat={timeFormat} currency={project?.revenueCurrency} />
{canLoadMoreSessions ? (
<button
type='button'
diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsx
index 09d5c41d0..184141e92 100644
--- a/web/app/pages/Project/Settings/ProjectSettings.tsx
+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx
@@ -22,6 +22,7 @@ import {
PuzzleIcon,
StickyNoteIcon,
ShieldCheckIcon,
+ DollarSignIcon,
} from 'lucide-react'
import React, { useState, useEffect, useMemo, useCallback } from 'react'
import { Trans, useTranslation } from 'react-i18next'
@@ -73,6 +74,7 @@ import People from './People'
import AccessSettings from './tabs/AccessSettings'
import DangerZone from './tabs/DangerZone'
import General from './tabs/General'
+import Revenue from './tabs/Revenue'
import Shields from './tabs/Shields'
const MAX_NAME_LENGTH = 50
@@ -324,6 +326,7 @@ const ProjectSettings = () => {
| 'access'
| 'captcha'
| 'integrations'
+ | 'revenue'
| 'emails'
| 'people'
| 'annotations'
@@ -347,6 +350,12 @@ const ProjectSettings = () => {
icon: PuzzleIcon,
visible: !isSelfhosted,
},
+ {
+ id: 'revenue',
+ label: t('project.settings.tabs.revenue'),
+ icon: DollarSignIcon,
+ visible: !isSelfhosted,
+ },
{ id: 'emails', label: t('project.settings.tabs.emails'), icon: MailIcon, visible: !isSelfhosted },
{ id: 'people', label: t('project.settings.tabs.people'), icon: UserRoundIcon, visible: true },
{ id: 'annotations', label: t('project.settings.tabs.annotations'), icon: StickyNoteIcon, visible: true },
@@ -1093,6 +1102,8 @@ const ProjectSettings = () => {
</div>
) : null}
+ {activeTab === 'revenue' ? <Revenue projectId={id} /> : null}
+
{activeTab === 'danger' ? (
<DangerZone
setShowTransfer={setShowTransfer}
diff --git a/web/app/pages/Project/Settings/tabs/Revenue.tsx b/web/app/pages/Project/Settings/tabs/Revenue.tsx
new file mode 100644
index 000000000..8ad185e49
--- /dev/null
+++ b/web/app/pages/Project/Settings/tabs/Revenue.tsx
@@ -0,0 +1,253 @@
+import { useCallback, useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+
+import {
+ connectPaddleRevenue,
+ disconnectPaddleRevenue,
+ getRevenueStatus,
+ syncRevenue,
+ updateRevenueCurrency,
+} from '~/api'
+import Button from '~/ui/Button'
+import Input from '~/ui/Input'
+import Loader from '~/ui/Loader'
+import Select from '~/ui/Select'
+
+interface RevenueStatus {
+ connected: boolean
+ provider?: string
+ currency?: string
+ lastSyncAt?: string
+}
+
+const SUPPORTED_CURRENCIES = [
+ { code: 'USD', name: 'US Dollar' },
+ { code: 'EUR', name: 'Euro' },
+ { code: 'GBP', name: 'British Pound' },
+ { code: 'CAD', name: 'Canadian Dollar' },
+ { code: 'AUD', name: 'Australian Dollar' },
+]
+
+const PADDLE_DOCS_URL = 'https://developer.paddle.com/api-reference/about/authentication'
+
+interface Props {
+ projectId: string
+}
+
+const Revenue = ({ projectId }: Props) => {
+ const { t } = useTranslation('common')
+
+ const [status, setStatus] = useState<RevenueStatus | null>(null)
+ const [isLoading, setIsLoading] = useState(true)
+ const [apiKey, setApiKey] = useState('')
+ const [selectedCurrency, setSelectedCurrency] = useState('USD')
+ const [isConnecting, setIsConnecting] = useState(false)
+ const [isSyncing, setIsSyncing] = useState(false)
+
+ const loadStatus = useCallback(async () => {
+ try {
+ const result = await getRevenueStatus(projectId)
+ setStatus(result)
+ if (result.currency) {
+ setSelectedCurrency(result.currency)
+ }
+ } catch (error) {
+ console.error('Failed to load revenue status:', error)
+ } finally {
+ setIsLoading(false)
+ }
+ }, [projectId])
+
+ useEffect(() => {
+ loadStatus()
+ }, [loadStatus])
+
+ const handleConnect = async () => {
+ if (!apiKey.trim()) {
+ toast.error(t('project.settings.revenue.apiKeyRequired'))
+ return
+ }
+
+ setIsConnecting(true)
+ try {
+ await connectPaddleRevenue(projectId, apiKey, selectedCurrency)
+ toast.success(t('project.settings.revenue.connected'))
+ setApiKey('')
+ await loadStatus()
+ } catch (error: any) {
+ toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))
+ } finally {
+ setIsConnecting(false)
+ }
+ }
+
+ const handleDisconnect = async () => {
+ try {
+ await disconnectPaddleRevenue(projectId)
+ toast.success(t('project.settings.revenue.disconnected'))
+ setStatus({ connected: false })
+ } catch (error: any) {
+ toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))
+ }
+ }
+
+ const handleSync = async () => {
+ setIsSyncing(true)
+ try {
+ const result = await syncRevenue(projectId)
+ toast.success(t('project.settings.revenue.synced', { count: result.transactionsSynced }))
+ await loadStatus()
+ } catch (error: any) {
+ toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))
+ } finally {
+ setIsSyncing(false)
+ }
+ }
+
+ const handleCurrencyChange = async (currency: string) => {
+ setSelectedCurrency(currency)
+ if (status?.connected) {
+ try {
+ await updateRevenueCurrency(projectId, currency)
+ toast.success(t('project.settings.revenue.currencyUpdated'))
+ } catch (error: any) {
+ toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))
+ }
+ }
+ }
+
+ if (isLoading) {
+ return (
+ <div className='flex items-center justify-center py-8'>
+ <Loader />
+ </div>
+ )
+ }
+
+ return (
+ <div className='space-y-6'>
+ <div className='rounded-lg border border-gray-200 p-4 dark:border-slate-800'>
+ <h3 className='mb-2 text-lg font-medium text-gray-900 dark:text-gray-50'>
+ {t('project.settings.revenue.title')}
+ </h3>
+ <p className='mb-4 text-sm text-gray-600 dark:text-gray-300'>{t('project.settings.revenue.description')}</p>
+
+ {status?.connected ? (
+ <div className='space-y-4'>
+ <div className='flex items-center gap-2'>
+ <div className='h-2.5 w-2.5 rounded-full bg-green-500' />
+ <span className='text-sm font-medium text-gray-900 dark:text-gray-50'>
+ {t('project.settings.revenue.connectedTo', { provider: 'Paddle' })}
+ </span>
+ </div>
+
+ {status.lastSyncAt && (
+ <p className='text-sm text-gray-600 dark:text-gray-300'>
+ {t('project.settings.revenue.lastSync', {
+ date: new Date(status.lastSyncAt).toLocaleString(),
+ })}
+ </p>
+ )}
+
+ <div className='flex flex-wrap gap-2'>
+ <Button type='button' onClick={handleSync} loading={isSyncing} primary regular>
+ {t('project.settings.revenue.syncNow')}
+ </Button>
+ <Button type='button' onClick={handleDisconnect} semiDanger regular>
+ {t('common.disconnect')}
+ </Button>
+ </div>
+
+ <hr className='border-gray-200 dark:border-slate-700' />
+
+ <div>
+ <Select
+ label={t('project.settings.revenue.currency')}
+ hint={t('project.settings.revenue.currencyHint')}
+ className='max-w-xs'
+ items={SUPPORTED_CURRENCIES}
+ keyExtractor={(item) => item.code}
+ labelExtractor={(item) => `${item.code} - ${item.name}`}
+ selectedItem={SUPPORTED_CURRENCIES.find((c) => c.code === selectedCurrency)}
+ onSelect={(item: { code: string; name: string }) => handleCurrencyChange(item.code)}
+ title={selectedCurrency}
+ />
+ </div>
+ </div>
+ ) : (
+ <div className='space-y-4'>
+ <div>
+ <h4 className='mb-2 text-base font-medium text-gray-900 dark:text-gray-50'>
+ {t('project.settings.revenue.connectPaddle')}
+ </h4>
+ <p className='mb-3 text-sm text-gray-600 dark:text-gray-300'>
+ {t('project.settings.revenue.connectPaddleDesc')}
+ </p>
+ <a
+ href={PADDLE_DOCS_URL}
+ target='_blank'
+ rel='noopener noreferrer'
+ className='text-sm font-medium text-indigo-600 hover:underline dark:text-indigo-400'
+ >
+ {t('project.settings.revenue.paddleDocsLink')}
+ </a>
+ </div>
+
+ <Input
+ type='password'
+ label={t('project.settings.revenue.apiKey')}
+ hint={t('project.settings.revenue.apiKeyHint')}
+ placeholder='pdl_live_...'
+ value={apiKey}
+ onChange={(e) => setApiKey(e.target.value)}
+ className='max-w-md'
+ />
+
+ <Select
+ label={t('project.settings.revenue.currency')}
+ hint={t('project.settings.revenue.currencyHint')}
+ className='max-w-xs'
+ items={SUPPORTED_CURRENCIES}
+ keyExtractor={(item) => item.code}
+ labelExtractor={(item) => `${item.code} - ${item.name}`}
+ selectedItem={SUPPORTED_CURRENCIES.find((c) => c.code === selectedCurrency)}
+ onSelect={(item: { code: string; name: string }) => setSelectedCurrency(item.code)}
+ title={selectedCurrency}
+ />
+
+ <Button type='button' onClick={handleConnect} loading={isConnecting} primary regular>
+ {t('common.connect')}
+ </Button>
+ </div>
+ )}
+ </div>
+
+ <div className='rounded-lg border border-gray-200 p-4 dark:border-slate-800'>
+ <h3 className='mb-2 text-lg font-medium text-gray-900 dark:text-gray-50'>
+ {t('project.settings.revenue.attribution.title')}
+ </h3>
+ <p className='mb-4 text-sm text-gray-600 dark:text-gray-300'>
+ {t('project.settings.revenue.attribution.description')}
+ </p>
+
+ <div className='rounded-md bg-gray-100 p-4 dark:bg-slate-800'>
+ <p className='mb-2 text-sm font-medium text-gray-900 dark:text-gray-50'>
+ {t('project.settings.revenue.attribution.paddleExample')}
+ </p>
+ <pre className='overflow-x-auto text-xs text-gray-700 dark:text-gray-300'>
+ {`Paddle.Checkout.open({
+ items: [{ priceId: 'pri_...', quantity: 1 }],
+ customData: {
+ swetrix_profile_id: await swetrix.getProfileId(),
+ swetrix_session_id: await swetrix.getSessionId()
+ }
+})`}
+ </pre>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default Revenue
diff --git a/web/app/pages/Project/Traffic/View/TrafficView.tsx b/web/app/pages/Project/Traffic/View/TrafficView.tsx
index 5bcf574c3..c951e6c4d 100644
--- a/web/app/pages/Project/Traffic/View/TrafficView.tsx
+++ b/web/app/pages/Project/Traffic/View/TrafficView.tsx
@@ -21,6 +21,7 @@ import {
getCustomEventsMetadata,
getPropertyMetadata,
getGSCKeywords,
+ getRevenueData,
} from '~/api'
import { useAnnotations } from '~/hooks/useAnnotations'
import { TRAFFIC_PANELS_ORDER, chartTypes, PERIOD_PAIRS_COMPARE, isSelfhosted, type TimeBucket } from '~/lib/constants'
@@ -178,6 +179,7 @@ const TrafficView = ({
const [overallCompare, setOverallCompare] = useState<Partial<OverallObject>>({})
const [dataChartCompare, setDataChartCompare] = useState<any>({})
const [customEventsChartData, setCustomEventsChartData] = useState<any>({})
+ const [revenueChartData, setRevenueChartData] = useState<number[]>([])
// Chart metrics state
const [activeChartMetrics, setActiveChartMetrics] = useState({
@@ -189,6 +191,7 @@ const TrafficView = ({
[CHART_METRICS_MAPPING.trendlines]: false,
[CHART_METRICS_MAPPING.cumulativeMode]: false,
[CHART_METRICS_MAPPING.customEvents]: false,
+ [CHART_METRICS_MAPPING.revenue]: false,
})
const [activeChartMetricsCustomEvents, setActiveChartMetricsCustomEvents] = useState<string[]>([])
@@ -256,50 +259,59 @@ const TrafficView = ({
}, [panelsData.data?.brv, panelsData.data?.osv])
const chartMetrics = useMemo(
- () => [
- {
- id: CHART_METRICS_MAPPING.unique,
- label: t('dashboard.sessions'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.unique],
- },
- {
- id: CHART_METRICS_MAPPING.views,
- label: t('project.showAll'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.views],
- },
- {
- id: CHART_METRICS_MAPPING.sessionDuration,
- label: t('dashboard.sessionDuration'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.sessionDuration],
- conflicts: [CHART_METRICS_MAPPING.bounce],
- },
- {
- id: CHART_METRICS_MAPPING.bounce,
- label: t('dashboard.bounceRate'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.bounce],
- conflicts: [CHART_METRICS_MAPPING.sessionDuration],
- },
- {
- id: CHART_METRICS_MAPPING.viewsPerUnique,
- label: t('dashboard.viewsPerUnique'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.viewsPerUnique],
- },
- {
- id: CHART_METRICS_MAPPING.trendlines,
- label: t('dashboard.trendlines'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.trendlines],
- },
- {
- id: CHART_METRICS_MAPPING.cumulativeMode,
- label: t('dashboard.cumulativeMode'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.cumulativeMode],
- },
- {
- id: CHART_METRICS_MAPPING.customEvents,
- label: t('project.customEv'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.customEvents],
- },
- ],
+ () =>
+ [
+ {
+ id: CHART_METRICS_MAPPING.unique,
+ label: t('dashboard.sessions'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.unique],
+ },
+ {
+ id: CHART_METRICS_MAPPING.views,
+ label: t('project.showAll'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.views],
+ },
+ !isSelfhosted
+ ? {
+ id: CHART_METRICS_MAPPING.revenue,
+ label: t('dashboard.revenue'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.revenue],
+ conflicts: [CHART_METRICS_MAPPING.bounce, CHART_METRICS_MAPPING.sessionDuration],
+ }
+ : null,
+ {
+ id: CHART_METRICS_MAPPING.sessionDuration,
+ label: t('dashboard.sessionDuration'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.sessionDuration],
+ conflicts: [CHART_METRICS_MAPPING.bounce, CHART_METRICS_MAPPING.revenue],
+ },
+ {
+ id: CHART_METRICS_MAPPING.bounce,
+ label: t('dashboard.bounceRate'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.bounce],
+ conflicts: [CHART_METRICS_MAPPING.sessionDuration, CHART_METRICS_MAPPING.revenue],
+ },
+ {
+ id: CHART_METRICS_MAPPING.viewsPerUnique,
+ label: t('dashboard.viewsPerUnique'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.viewsPerUnique],
+ },
+ {
+ id: CHART_METRICS_MAPPING.trendlines,
+ label: t('dashboard.trendlines'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.trendlines],
+ },
+ {
+ id: CHART_METRICS_MAPPING.cumulativeMode,
+ label: t('dashboard.cumulativeMode'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.cumulativeMode],
+ },
+ {
+ id: CHART_METRICS_MAPPING.customEvents,
+ label: t('project.customEv'),
+ active: activeChartMetrics[CHART_METRICS_MAPPING.customEvents],
+ },
+ ].filter(Boolean),
[t, activeChartMetrics],
)
@@ -334,6 +346,8 @@ const TrafficView = ({
trendlineUnique: t('project.trendlineUnique'),
occurrences: t('project.occurrences'),
sessionDuration: t('dashboard.sessionDuration'),
+ revenue: t('dashboard.revenue'),
+ refundsAmount: t('dashboard.refunds'),
...dataNamesCustomEvents,
}),
[t, dataNamesCustomEvents],
@@ -567,7 +581,73 @@ const TrafficView = ({
if (_isEmpty(params)) {
setIsPanelsDataEmpty(true)
} else {
- setChartData(chart as any)
+ // Fetch revenue data if revenue metric is enabled and not selfhosted
+ let revenueData: number[] = []
+ let refundsData: number[] = []
+ if (activeChartMetrics.revenue && !isSelfhosted) {
+ try {
+ const revResult = await getRevenueData(
+ id,
+ period === 'custom' ? 'custom' : period,
+ period === 'custom' && dateRange ? getFormatDate(dateRange[0]) : undefined,
+ period === 'custom' && dateRange ? getFormatDate(dateRange[1]) : undefined,
+ timezone,
+ timeBucket,
+ )
+ const revChart = revResult?.chart
+ const revX = revChart?.x || []
+ const revY = revChart?.revenue || []
+ const revRefunds = revChart?.refundsAmount || []
+
+ // Align revenue series to the main traffic chart x-axis to avoid empty/invalid renders
+ if (Array.isArray(chart?.x) && chart.x.length > 0) {
+ if (
+ Array.isArray(revX) &&
+ revX.length === chart.x.length &&
+ revX[0] === chart.x[0] &&
+ revX[revX.length - 1] === chart.x[chart.x.length - 1]
+ ) {
+ revenueData = revY.map((v) => Number(v ?? 0))
+ refundsData = revRefunds.map((v) => Number(v ?? 0))
+ } else if (Array.isArray(revX) && revX.length > 0) {
+ const byX = new Map<string, number>()
+ const refundsByX = new Map<string, number>()
+ for (let i = 0; i < revX.length; i += 1) {
+ byX.set(revX[i], Number(revY[i] ?? 0))
+ refundsByX.set(revX[i], Number(revRefunds[i] ?? 0))
+ }
+ revenueData = chart.x.map((x: string) => Number(byX.get(x) ?? 0))
+ refundsData = chart.x.map((x: string) => Number(refundsByX.get(x) ?? 0))
+
+ // Fallback: if mapping produced all zeros but arrays match length, use index-based mapping
+ if (revenueData.every((v) => v === 0) && revY.length === chart.x.length) {
+ revenueData = revY.map((v) => Number(v ?? 0))
+ refundsData = revRefunds.map((v) => Number(v ?? 0))
+ }
+ } else {
+ revenueData = revY.map((v) => Number(v ?? 0))
+ refundsData = revRefunds.map((v) => Number(v ?? 0))
+ }
+ } else {
+ revenueData = revY.map((v) => Number(v ?? 0))
+ refundsData = revRefunds.map((v) => Number(v ?? 0))
+ }
+ } catch {
+ // Revenue data not available, continue without it
+ revenueData = []
+ refundsData = []
+ }
+ }
+ setRevenueChartData(revenueData)
+
+ // Merge revenue data with chart
+ const chartWithRevenue = {
+ ...chart,
+ revenue: revenueData,
+ refundsAmount: refundsData,
+ }
+
+ setChartData(chartWithRevenue as any)
setPanelsData({
types: _keys(params),
@@ -686,6 +766,7 @@ const TrafficView = ({
loadAnalytics()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
+ activeChartMetrics.revenue,
mode,
customMetrics,
filters,
diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsx
index d5dc1757d..b390f29a3 100644
--- a/web/app/pages/Project/View/ViewProject.helpers.tsx
+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx
@@ -18,6 +18,7 @@ import _replace from 'lodash/replace'
import _round from 'lodash/round'
import _size from 'lodash/size'
import _split from 'lodash/split'
+import _some from 'lodash/some'
import _startsWith from 'lodash/startsWith'
import _sum from 'lodash/sum'
import _toNumber from 'lodash/toNumber'
@@ -232,6 +233,7 @@ const CHART_METRICS_MAPPING = {
sessionDuration: 'sessionDuration',
customEvents: 'customEvents',
cumulativeMode: 'cumulativeMode',
+ revenue: 'revenue',
} as const
const CHART_METRICS_MAPPING_PERF = {
@@ -324,6 +326,18 @@ const getColumns = (
}
}
+ // Revenue data (if available) - revenue as bars with refunds stacked on top
+ if (activeChartMetrics.revenue && chart.revenue) {
+ columns.push(['revenue', ...chart.revenue])
+ // Add refundsAmount if available for stacked bar display
+ if (chart.refundsAmount) {
+ const hasAnyRefunds = _some(chart.refundsAmount, (v) => Number(v || 0) > 0)
+ if (hasAnyRefunds) {
+ columns.push(['refundsAmount', ...chart.refundsAmount])
+ }
+ }
+ }
+
return columns
}
@@ -617,6 +631,9 @@ const getSettings = (
trendlineTotal: spline(),
sessionDuration: chartType === chartTypes.line ? spline() : bar(),
sessionDurationCompare: chartType === chartTypes.line ? spline() : bar(),
+ // Revenue is always bars (stacked with refunds)
+ revenue: bar(),
+ refundsAmount: bar(),
},
colors: {
unique: '#2563EB',
@@ -630,13 +647,22 @@ const getSettings = (
trendlineTotal: '#eba14b',
sessionDuration: '#c945ed',
sessionDurationCompare: 'rgba(201, 69, 237, 0.4)',
+ revenue: '#ea580c', // orange-600 for net revenue
+ refundsAmount: 'rgba(234, 88, 12, 0.25)', // light orange fill for refunds overlay
...customEventsColors,
},
+ // Stack revenue and refundsAmount together
+ groups: activeChartMetrics.revenue ? [['revenue', 'refundsAmount']] : undefined,
+ // Prevent billboard/c3 from auto-reordering stacked series
+ // (we need refunds stacked on top of revenue consistently)
+ order: activeChartMetrics.revenue ? null : undefined,
// @ts-expect-error
regions,
axes: {
bounce: 'y2',
sessionDuration: 'y2',
+ revenue: 'y2',
+ refundsAmount: 'y2',
},
},
grid: {
@@ -679,12 +705,14 @@ const getSettings = (
inner: true,
},
y2: {
- show: activeChartMetrics.bounce || activeChartMetrics.sessionDuration,
+ show: activeChartMetrics.bounce || activeChartMetrics.sessionDuration || activeChartMetrics.revenue,
tick: {
// @ts-expect-error
format: activeChartMetrics.bounce
? (d: string) => `${d}%`
- : (d: string) => getStringFromTime(getTimeFromSeconds(d)),
+ : activeChartMetrics.revenue
+ ? (d: number) => `$${nFormatter(d, 1)}`
+ : (d: string) => getStringFromTime(getTimeFromSeconds(d)),
},
min: activeChartMetrics.bounce ? 10 : undefined,
max: activeChartMetrics.bounce ? 100 : undefined,
@@ -724,6 +752,31 @@ const getSettings = (
return ''
}
+ // Format revenue and refunds as currency
+ if (el.id === 'revenue') {
+ return `
+ <li class='flex justify-between'>
+ <div class='flex justify-items-start'>
+ <div class='w-3 h-3 rounded-xs mt-1.5 mr-2' style='background-color:${color(el.id)}'></div>
+ <span>${el.name}</span>
+ </div>
+ <span class='pl-4'>$${nFormatter(Number(el.value) || 0, 2)}</span>
+ </li>
+ `
+ }
+
+ if (el.id === 'refundsAmount') {
+ return `
+ <li class='flex justify-between'>
+ <div class='flex justify-items-start'>
+ <div class='w-3 h-3 rounded-xs mt-1.5 mr-2' style='background-color:rgba(234,88,12,0.25);border:1.5px dashed #ea580c'></div>
+ <span>${el.name}</span>
+ </div>
+ <span class='pl-4'>$${nFormatter(Number(el.value) || 0, 2)}</span>
+ </li>
+ `
+ }
+
return `
<li class='flex justify-between'>
<div class='flex justify-items-start'>
@@ -833,17 +886,42 @@ const getSettings = (
r: 3,
},
},
- hide: ['uniqueCompare', 'totalCompare', 'bounceCompare', 'sessionDurationCompare'],
+ hide: ['uniqueCompare', 'totalCompare', 'bounceCompare', 'sessionDurationCompare', 'refundsAmount'],
},
area: {
linearGradient: true,
},
bar: {
- linearGradient: true,
+ linearGradient: !activeChartMetrics.revenue, // Disable gradient when revenue is shown
radius: {
ratio: 0.15,
},
},
+ onrendered: activeChartMetrics.revenue
+ ? function () {
+ // Revenue chart styling:
+ // - revenue: solid orange stroke (handled by CSS)
+ // - refunds: dashed orange stroke + light fill
+ // - when refunds value is 0, remove stroke to avoid "cap" lines
+ // @ts-expect-error
+ const chart = this as any
+
+ if (chart?.$ && chart.$.bar?.bars) {
+ chart.$.bar.bars.each(function (this: SVGPathElement, d: any) {
+ if (d?.id === 'refundsAmount' && Number(d?.value || 0) > 0) {
+ this.style.stroke = '#ea580c'
+ this.style.strokeWidth = '1.5px'
+ this.style.strokeDasharray = '6,4'
+ } else if (d?.id === 'refundsAmount') {
+ // Avoid a dashed "cap" on top of revenue when refunds are 0.
+ this.style.strokeDasharray = ''
+ this.style.strokeWidth = '0'
+ this.style.stroke = 'none'
+ }
+ })
+ }
+ }
+ : undefined,
zoom:
onZoom && enableZoom !== false
? {
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 448d24b8f..87bc99045 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -75,6 +75,7 @@ import FunnelsView from '../Funnels/View'
import GoalsView from '../Goals/View'
import PerformanceView from '../Performance/View/PerformanceView'
import ProfilesView from '../Profiles/View'
+// Revenue dashboard removed - revenue data is displayed in TrafficView, Pageflow, and Profile details
import SessionsView from '../Sessions/View/SessionsView'
import TrafficView from '../Traffic/View/TrafficView'
diff --git a/web/app/pages/Project/View/components/Pageflow.tsx b/web/app/pages/Project/View/components/Pageflow.tsx
index fa4d1e3cc..0c393f0ec 100644
--- a/web/app/pages/Project/View/components/Pageflow.tsx
+++ b/web/app/pages/Project/View/components/Pageflow.tsx
@@ -4,7 +4,16 @@ import _map from 'lodash/map'
import _size from 'lodash/size'
import _toUpper from 'lodash/toUpper'
import _truncate from 'lodash/truncate'
-import { BugIcon, ChevronDownIcon, CircleIcon, FileTextIcon, MousePointerClickIcon, TagIcon } from 'lucide-react'
+import {
+ BugIcon,
+ ChevronDownIcon,
+ CircleIcon,
+ DollarSignIcon,
+ FileTextIcon,
+ MousePointerClickIcon,
+ RotateCcwIcon,
+ TagIcon,
+} from 'lucide-react'
import React, { useMemo, useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
@@ -17,10 +26,12 @@ interface Metadata {
interface PageflowProps {
pages: {
- type: 'pageview' | 'event' | 'error'
+ type: 'pageview' | 'event' | 'error' | 'sale' | 'refund'
value: string
created: string
metadata?: Metadata[]
+ amount?: number
+ currency?: string
}[]
timeFormat: '12-hour' | '24-hour'
zoomedTimeRange?: [Date, Date] | null
@@ -30,12 +41,14 @@ interface PageflowProps {
interface PageflowItemProps {
value: string
created: string
- type: 'pageview' | 'event' | 'error'
+ type: 'pageview' | 'event' | 'error' | 'sale' | 'refund'
metadata?: Metadata[]
displayCreated: string
timeDuration: number | null
isLastEvent: boolean
t: TFunction
+ amount?: number
+ currency?: string
}
const MetadataPanel = ({ metadata, t }: { metadata: Metadata[]; t: TFunction }) => {
@@ -115,6 +128,8 @@ const PageflowItem = ({
timeDuration,
isLastEvent,
t,
+ amount,
+ currency,
}: PageflowItemProps) => {
const [isExpanded, setIsExpanded] = useState(false)
const hasMetadata = metadata && metadata.length > 0
@@ -138,8 +153,10 @@ const PageflowItem = ({
<div>
<span
className={cn('flex h-8 w-8 items-center justify-center rounded-full', {
- 'bg-slate-400 dark:bg-slate-800': type !== 'error',
+ 'bg-slate-400 dark:bg-slate-800': type === 'pageview' || type === 'event',
'bg-red-400 dark:bg-red-800': type === 'error',
+ 'bg-green-500 dark:bg-green-700': type === 'sale',
+ 'bg-orange-500 dark:bg-orange-700': type === 'refund',
})}
>
{type === 'pageview' ? (
@@ -151,6 +168,12 @@ const PageflowItem = ({
{type === 'error' ? (
<BugIcon className='h-5 w-5 text-white' aria-hidden='true' strokeWidth={1.5} />
) : null}
+ {type === 'sale' ? (
+ <DollarSignIcon className='h-5 w-5 text-white' aria-hidden='true' strokeWidth={1.5} />
+ ) : null}
+ {type === 'refund' ? (
+ <RotateCcwIcon className='h-5 w-5 text-white' aria-hidden='true' strokeWidth={1.5} />
+ ) : null}
</span>
</div>
<div className='flex min-w-0 flex-1 flex-col pt-1.5'>
@@ -173,19 +196,37 @@ const PageflowItem = ({
: undefined
}
>
- <Trans
- t={t}
- i18nKey={
- type === 'pageview' ? 'project.pageviewX' : type === 'event' ? 'project.eventX' : 'project.errorX'
- }
- components={{
- value: <span className='ml-1 font-medium text-gray-900 dark:text-gray-50' />,
- span: <span />,
- }}
- values={{
- x: value || _toUpper(t('common.notSet')),
- }}
- />
+ {type === 'sale' || type === 'refund' ? (
+ <span className='flex items-center'>
+ <span
+ className={cn('font-semibold', {
+ 'text-green-600 dark:text-green-400': type === 'sale',
+ 'text-orange-600 dark:text-orange-400': type === 'refund',
+ })}
+ >
+ {type === 'refund' ? '-' : ''}
+ {new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: currency || 'USD',
+ }).format(Math.abs(amount || 0))}
+ </span>
+ {value ? <span className='ml-2 text-gray-500 dark:text-gray-400'>({value})</span> : null}
+ </span>
+ ) : (
+ <Trans
+ t={t}
+ i18nKey={
+ type === 'pageview' ? 'project.pageviewX' : type === 'event' ? 'project.eventX' : 'project.errorX'
+ }
+ components={{
+ value: <span className='ml-1 font-medium text-gray-900 dark:text-gray-50' />,
+ span: <span />,
+ }}
+ values={{
+ x: value || _toUpper(t('common.notSet')),
+ }}
+ />
+ )}
{hasMetadata ? (
<span className='ml-2 inline-flex shrink-0 items-center gap-0.5 rounded-full bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium text-slate-500 dark:bg-slate-700 dark:text-slate-400'>
<TagIcon className='h-2.5 w-2.5' />
@@ -295,7 +336,7 @@ export const Pageflow = ({ pages, timeFormat, zoomedTimeRange, sdur = 0 }: Pagef
return (
<div className='flow-root'>
<ul className='-mb-8'>
- {_map(filteredPages, ({ value, created, type, metadata }, index) => {
+ {_map(filteredPages, ({ value, created, type, metadata, amount, currency }, index) => {
const displayCreated = new Date(created).toLocaleDateString(language, {
day: 'numeric',
month: 'short',
@@ -319,6 +360,8 @@ export const Pageflow = ({ pages, timeFormat, zoomedTimeRange, sdur = 0 }: Pagef
timeDuration={timeDuration}
isLastEvent={isLastEvent}
t={t}
+ amount={amount}
+ currency={currency}
/>
)
})}
diff --git a/web/app/pages/Project/View/components/Sessions.tsx b/web/app/pages/Project/View/components/Sessions.tsx
index 7ac9f4450..2b39d2a3e 100644
--- a/web/app/pages/Project/View/components/Sessions.tsx
+++ b/web/app/pages/Project/View/components/Sessions.tsx
@@ -26,6 +26,19 @@ dayjs.extend(relativeTime)
const ONLINE_THRESHOLD_MINUTES = 5
const RECENTLY_ACTIVE_THRESHOLD_MINUTES = 30
+// Currency symbols
+const CURRENCY_SYMBOLS: Record<string, string> = {
+ USD: '$',
+ EUR: '€',
+ GBP: '£',
+ CAD: 'CA$',
+ AUD: 'A$',
+}
+
+const getCurrencySymbol = (currency?: string) => {
+ return CURRENCY_SYMBOLS[currency || 'USD'] || CURRENCY_SYMBOLS.USD
+}
+
type OnlineStatus = 'online' | 'recently_active' | 'offline'
const getOnlineStatus = (lastActivity: string): OnlineStatus => {
@@ -49,6 +62,7 @@ interface SessionsProps {
timeFormat: '12-hour' | '24-hour'
hideNewReturnBadge?: boolean
hideUserDetails?: boolean
+ currency?: string
}
interface SessionProps {
@@ -56,6 +70,7 @@ interface SessionProps {
timeFormat: '12-hour' | '24-hour'
hideNewReturnBadge?: boolean
hideUserDetails?: boolean
+ currency?: string
}
const Separator = () => (
@@ -64,7 +79,8 @@ const Separator = () => (
</svg>
)
-const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails }: SessionProps) => {
+const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails, currency }: SessionProps) => {
+ const currencySymbol = getCurrencySymbol(currency)
const {
t,
i18n: { language },
@@ -192,6 +208,19 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails }: S
<span className='mr-2 flex items-center' title={t('dashboard.pageviews')}>
<FileTextIcon className='mr-1 size-4' strokeWidth={1.5} /> {session.pageviews}
</span>
+ {session.revenue != null && session.revenue !== 0 ? (
+ <span
+ className={cx('mr-2 flex items-center', {
+ 'text-amber-600 dark:text-amber-500': session.revenue > 0,
+ 'text-orange-600 dark:text-orange-500': session.revenue < 0,
+ })}
+ title={t('dashboard.revenue')}
+ >
+ {session.revenue < 0 ? '-' : ''}
+ {currencySymbol}
+ {Math.abs(session.revenue).toFixed(2)}
+ </span>
+ ) : null}
{session.customEvents > 0 ? (
<span className='mr-2 flex items-center' title={t('dashboard.events')}>
<MousePointerClickIcon className='mr-1 size-4' strokeWidth={1.5} /> {session.customEvents}
@@ -211,6 +240,19 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails }: S
<span className='flex items-center' title={t('dashboard.xPageviews', { x: session.pageviews })}>
<FileTextIcon className='mr-1 size-5' strokeWidth={1.5} /> {session.pageviews}
</span>
+ {session.revenue != null && session.revenue !== 0 ? (
+ <span
+ className={cx('flex items-center', {
+ 'text-amber-600 dark:text-amber-500': session.revenue > 0,
+ 'text-orange-600 dark:text-orange-500': session.revenue < 0,
+ })}
+ title={`${session.revenue < 0 ? '-' : ''}${currencySymbol}${Math.abs(session.revenue).toFixed(2)}`}
+ >
+ {session.revenue < 0 ? '-' : ''}
+ {currencySymbol}
+ {Math.abs(session.revenue).toFixed(2)}
+ </span>
+ ) : null}
{session.customEvents > 0 ? (
<span className='flex items-center' title={t('dashboard.xCustomEvents', { x: session.customEvents })}>
<MousePointerClickIcon className='mr-1 size-5' strokeWidth={1.5} /> {session.customEvents}
@@ -234,7 +276,13 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails }: S
)
}
-export const Sessions: React.FC<SessionsProps> = ({ sessions, timeFormat, hideNewReturnBadge, hideUserDetails }) => {
+export const Sessions: React.FC<SessionsProps> = ({
+ sessions,
+ timeFormat,
+ hideNewReturnBadge,
+ hideUserDetails,
+ currency,
+}) => {
return (
<ClientOnly
fallback={
@@ -252,6 +300,7 @@ export const Sessions: React.FC<SessionsProps> = ({ sessions, timeFormat, hideNe
timeFormat={timeFormat}
hideNewReturnBadge={hideNewReturnBadge}
hideUserDetails={hideUserDetails}
+ currency={currency}
/>
))}
</ul>
diff --git a/web/app/pages/Project/View/components/UserDetails.tsx b/web/app/pages/Project/View/components/UserDetails.tsx
index f7311d1c7..9d638f0dc 100644
--- a/web/app/pages/Project/View/components/UserDetails.tsx
+++ b/web/app/pages/Project/View/components/UserDetails.tsx
@@ -11,6 +11,7 @@ import {
SmartphoneIcon,
TabletIcon,
GlobeIcon,
+ DollarSignIcon,
} from 'lucide-react'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
@@ -36,6 +37,7 @@ interface UserDetailsProps {
chartType: string
onLoadMoreSessions: () => void
canLoadMoreSessions: boolean
+ currency?: string
}
// Activity Calendar Component
@@ -200,6 +202,7 @@ export const UserDetails = ({
chartType,
onLoadMoreSessions,
canLoadMoreSessions,
+ currency,
}: UserDetailsProps) => {
const {
t,
@@ -278,6 +281,17 @@ export const UserDetails = ({
label={t('project.lastSeen')}
value={formatDate(details.lastSeen)}
/>
+ {details.totalRevenue !== undefined && details.totalRevenue > 0 ? (
+ <StatItem
+ icon={<DollarSignIcon className='h-3.5 w-3.5 text-green-500' />}
+ label={t('dashboard.revenue')}
+ value={new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: details.revenueCurrency || 'USD',
+ minimumFractionDigits: 2,
+ }).format(details.totalRevenue)}
+ />
+ ) : null}
</div>
</div>
@@ -379,7 +393,13 @@ export const UserDetails = ({
<p className='py-4 text-center text-sm text-gray-400'>{t('project.noSessions')}</p>
) : (
<>
- <Sessions sessions={sessions} timeFormat={timeFormat} hideNewReturnBadge hideUserDetails />
+ <Sessions
+ sessions={sessions}
+ timeFormat={timeFormat}
+ hideNewReturnBadge
+ hideUserDetails
+ currency={currency}
+ />
{canLoadMoreSessions ? (
<Button
onClick={onLoadMoreSessions}
diff --git a/web/app/styles/ProjectViewStyle.css b/web/app/styles/ProjectViewStyle.css
index bea1b1a40..2a1b63716 100644
--- a/web/app/styles/ProjectViewStyle.css
+++ b/web/app/styles/ProjectViewStyle.css
@@ -110,6 +110,17 @@ body.dark .bb-ygrid {
stroke: var(--color-red-400) !important;
}
+/* Revenue chart styling */
+.bb-target-revenue .bb-bar {
+ stroke: #ea580c !important;
+ fill-opacity: 0.85 !important;
+}
+
+.bb-target-refundsAmount .bb-bar {
+ stroke: #ea580c !important;
+ fill-opacity: 1 !important; /* keep rgba() fill visible (don't multiply by .bb-bar opacity) */
+}
+
.bb-target-dns .bb-bar {
stroke: #ec4319 !important;
}
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index ed39a7d64..a9c5efe79 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -887,6 +887,8 @@
"xPageviews": "{{x}} pageviews",
"xCustomEvents": "{{x}} custom events",
"xErrors": "{{x}} errors",
+ "sales": "Sales",
+ "xSales": "{{x}} sales",
"events": "Events",
"alerts": "Alerts",
"alertsDesc": "Automated alerts is a powerful tool that notifies you when some events occur on your website.\nWe can automatically monitor your project for traffic spikes and notify you via Telegram, Slack or Discord.",
@@ -909,6 +911,9 @@
"experimentsHint": "Run A/B tests to optimize your website.",
"featureFlagsHint": "Toggle features for specific user cohorts.",
"captchaHint": "Protect your forms with privacy-focused CAPTCHA.",
+ "revenue": "Revenue",
+ "refunds": "Refunds",
+ "revenueHint": "Track sales, refunds and revenue from your payment providers.",
"webAnalytics": "Web analytics",
"productAnalytics": "Product analytics",
"revenueAnalytics": "Revenue analytics",
@@ -1511,7 +1516,32 @@
"people": "People",
"annotations": "Annotations",
"danger": "Danger zone",
- "integrations": "Integrations"
+ "integrations": "Integrations",
+ "revenue": "Revenue"
+ },
+ "revenue": {
+ "title": "Revenue Tracking",
+ "description": "Connect your payment provider to track revenue and attribute sales to marketing channels.",
+ "connectPaddle": "Connect Paddle",
+ "connectPaddleDesc": "Enter your Paddle API key to start tracking revenue. We will automatically sync transactions from your Paddle account.",
+ "paddleDocsLink": "Learn how to get your Paddle API key",
+ "apiKey": "API Key",
+ "apiKeyHint": "Your Paddle API key for read-only access to transactions.",
+ "apiKeyRequired": "API key is required",
+ "currency": "Reporting Currency",
+ "currencyHint": "All revenue will be converted and displayed in this currency.",
+ "currencyUpdated": "Reporting currency updated",
+ "connected": "Revenue tracking connected",
+ "connectedTo": "Connected to {{provider}}",
+ "disconnected": "Revenue tracking disconnected",
+ "synced": "Synced {{count}} transactions",
+ "syncNow": "Sync now",
+ "lastSync": "Last synced: {{date}}",
+ "attribution": {
+ "title": "Revenue Attribution",
+ "description": "Pass visitor and session IDs to your payment provider to attribute revenue to marketing channels.",
+ "paddleExample": "Paddle Checkout Integration:"
+ }
},
"captcha": {
"title": "CAPTCHA Integration",
@@ -1665,6 +1695,28 @@
"conversionRateShort": "{{x}}% conversion rate",
"startShort": "Start",
"endShort": "End"
+ },
+ "revenue": {
+ "title": "Revenue Analytics",
+ "revenue": "Revenue",
+ "notConfigured": "Revenue tracking not configured",
+ "notConfiguredDesc": "Connect your payment provider in project settings to start tracking revenue.",
+ "configureRevenue": "Configure Revenue Tracking",
+ "sync": "Sync",
+ "synced": "Synced {{count}} transactions",
+ "lastSync": "Last sync: {{date}}",
+ "totalRevenue": "Total Revenue",
+ "salesCount": "Sales",
+ "averageOrderValue": "Avg Order",
+ "mrr": "MRR",
+ "refunds": "Refunds",
+ "refundsLabel": "refunds",
+ "revenueOverTime": "Revenue Over Time",
+ "recentTransactions": "Recent Transactions",
+ "noTransactions": "No transactions found for this period.",
+ "byProduct": "Revenue by Product",
+ "noProducts": "No product data available.",
+ "sales": "sales"
}
},
"billing": {