📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Display revenue for sessions
Blue Mouse084a4698ec39
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.tsindex 4d619065d..44abf7cd0 100644--- a/backend/apps/cloud/src/analytics/analytics.service.ts+++ b/backend/apps/cloud/src/analytics/analytics.service.ts@@ -6506,6 +6506,24 @@ export class AnalyticsService {)`+ const querySessionRevenue = `+ SELECT+ toFloat64(sum(CASE WHEN type = 'sale' THEN amount ELSE 0 END) - sum(CASE WHEN type = 'refund' THEN abs(amount) ELSE 0 END)) AS revenue,+ toFloat64(sum(CASE WHEN type = 'refund' THEN abs(amount) ELSE 0 END)) AS refunds+ FROM (+ SELECT+ argMax(type, synced_at) AS type,+ argMax(amount, synced_at) AS amount+ FROM revenue+ WHERE+ pid = {pid:FixedString(12)}+ AND session_id IS NOT NULL+ AND toString(session_id) = {psid:String}+ AND revenue.type IN ('sale', 'refund')+ GROUP BY pid, session_id, transaction_id+ )+ `+const paramsData = {params: {pid,@@ -6551,6 +6569,20 @@ export class AnalyticsService {duration = fromSessionsTable}+ const { data: revenueRows } = await clickhouse+ .query({+ query: querySessionRevenue,+ query_params: paramsData.params,+ })+ .then((resultSet) =>+ resultSet.json<{+ revenue: number+ refunds: number+ }>(),+ )++ const revenueTotals = revenueRows[0] || { revenue: 0, refunds: 0 }+// If sessions table exists but `firstSeen` was historically broken (e.g. firstSeen == lastSeen),// we can still approximate using the first recorded event time + the session's lastSeen (which// may include heartbeat updates and thus be later than the last pageflow event).@@ -6658,6 +6690,8 @@ export class AnalyticsService {...(details || {}),sdur: duration,isLive,+ revenue: revenueTotals.revenue || 0,+ refunds: revenueTotals.refunds || 0,},psid,chart: chartData,diff --git a/docs/content/docs/api/stats.mdx b/docs/content/docs/api/stats.mdxindex 4bd0d8bef..a5153952e 100644--- a/docs/content/docs/api/stats.mdx+++ b/docs/content/docs/api/stats.mdx@@ -803,7 +803,9 @@ curl 'https://api.swetrix.com/v1/log/sessions?pid=YOUR_PROJECT_ID&period=7d&take"sessionStart": "2025-05-11T16:09:06Z","lastActivity": "2025-05-11T17:22:02Z","isLive": 1,- "sdur": 520+ "sdur": 520,+ "revenue": 129.99,+ "refunds": 20},{"psid": "3653378394154006361",@@ -958,7 +960,9 @@ curl 'https://api.swetrix.com/v1/log/session?pid=YOUR_PROJECT_ID&psid=SESSION_ID"rg": "England","ct": "Liverpool","sdur": 242,- "isLive": 0+ "isLive": 0,+ "revenue": 129.99,+ "refunds": 20},"psid": "14287087333426119778","chart": {@@ -998,6 +1002,10 @@ The timezone to use for the time range. The default is `Etc/GMT`. You can use an<hr />+#### Revenue fields++When revenue tracking is enabled and transactions are attributed to the session, `details.revenue` contains the session's net revenue after refunds, and `details.refunds` contains the total refunded amount for the session. Values use the project's configured revenue currency.+### GET /v1/log/funnelReturns a funnel analysis for a specific set of pages or a saved funnel.diff --git a/web/app/components/pricing/MarketingPricing.tsx b/web/app/components/pricing/MarketingPricing.tsxindex 0bfb5fbd1..c23f3cee0 100644--- a/web/app/components/pricing/MarketingPricing.tsx+++ b/web/app/components/pricing/MarketingPricing.tsx@@ -642,7 +642,7 @@ export const PricingInternal = ({: (monthlyPrice ?? null)}currencySymbol={currency.symbol}- className='leading-none align-baseline'+ className='align-baseline leading-none'/></Text><Textdiff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.tsindex 56f203f2c..c2e2acf2d 100644--- a/web/app/lib/models/Project.ts+++ b/web/app/lib/models/Project.ts@@ -142,6 +142,8 @@ export interface SessionDetails {sdur?: numberisLive?: boolean+ revenue?: number+ refunds?: number}export interface Profile {diff --git a/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx b/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsxindex 57f77881a..22e6a03ce 100644--- a/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx+++ b/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx@@ -4,6 +4,8 @@ import _isEmpty from 'lodash/isEmpty'import _size from 'lodash/size'import _truncate from 'lodash/truncate'import {+ ArrowCounterClockwiseIcon,+ CurrencyDollarIcon,GlobeIcon,ClockIcon,LinkIcon,@@ -68,6 +70,7 @@ interface SessionDetailViewProps {timeFormat: '12-hour' | '24-hour'rotateXAxis: booleandataNames: Record<string, string>+ currency?: stringwebsiteUrl?: string | nullbackLink?: stringbackButtonLabel?: string@@ -142,6 +145,18 @@ const formatSessionId = (id: string | null | undefined) => {return `${id.slice(0, 6)}...${id.slice(-5)}`}+const formatCurrency = (value: number, currency: string, language: string) => {+ try {+ return new Intl.NumberFormat(language || 'en-US', {+ style: 'currency',+ currency,+ minimumFractionDigits: 2,+ }).format(value)+ } catch {+ return `${value.toFixed(2)} ${currency}`+ }+}+export const SessionDetailView = ({activeSession,sessionId,@@ -149,6 +164,7 @@ export const SessionDetailView = ({timeFormat,rotateXAxis,dataNames,+ currency,websiteUrl,backLink,backButtonLabel,@@ -341,6 +357,11 @@ export const SessionDetailView = ({: sessionDuration > 0? getStringFromTime(getTimeFromSeconds(sessionDuration)): 'N/A'+ const revenueCurrency = currency || 'USD'+ const sessionRevenue =+ typeof details.revenue === 'number' ? details.revenue : null+ const sessionRefunds =+ typeof details.refunds === 'number' ? details.refunds : nullconst durationTooltip = (<div className='grid min-w-48 gap-1.5'><div className='grid grid-cols-[auto_minmax(0,1fr)] gap-4'>@@ -630,6 +651,42 @@ export const SessionDetailView = ({label={t('dashboard.sessionDuration')}value={durationValue}/>+ {sessionRevenue !== null && sessionRevenue !== 0 ? (+ <InfoRow+ label={t('dashboard.revenue')}+ value={+ <>+ <CurrencyDollarIcon+ className={+ sessionRevenue > 0+ ? 'h-4 w-4 text-emerald-500'+ : 'h-4 w-4 text-amber-500'+ }+ />+ {formatCurrency(+ sessionRevenue,+ revenueCurrency,+ language,+ )}+ </>+ }+ />+ ) : null}+ {sessionRefunds !== null && sessionRefunds > 0 ? (+ <InfoRow+ label={t('dashboard.refunds')}+ value={+ <>+ <ArrowCounterClockwiseIcon className='h-4 w-4 text-amber-500' />+ {formatCurrency(+ sessionRefunds,+ revenueCurrency,+ language,+ )}+ </>+ }+ />+ ) : null}<InfoRowlabel={t('project.mapping.ref')}value={diff --git a/web/app/pages/Project/tabs/Sessions/SessionsView.tsx b/web/app/pages/Project/tabs/Sessions/SessionsView.tsxindex 9d0fbfc17..71968db7e 100644--- a/web/app/pages/Project/tabs/Sessions/SessionsView.tsx+++ b/web/app/pages/Project/tabs/Sessions/SessionsView.tsx@@ -212,6 +212,8 @@ const SessionsViewInner = ({isLive: matchingSession? matchingSession.isLive === 1: apiDetails.isLive,+ revenue: apiDetails.revenue ?? matchingSession?.revenue,+ refunds: apiDetails.refunds ?? matchingSession?.refunds,}return {details,@@ -426,6 +428,7 @@ const SessionsViewInner = ({timeFormat={timeFormat}rotateXAxis={rotateXAxis}dataNames={dataNames}+ currency={project?.revenueCurrency}websiteUrl={project?.websiteUrl}backLink={`?${pureSearchParams}`}backButtonLabel={t('project.backToSessions')}