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!

Fix metrics visualisation

Blue Mouse034e168b198d
diff --git a/backend/apps/cloud/src/admin/admin.service.ts b/backend/apps/cloud/src/admin/admin.service.ts
index 20387a97d..431035677 100644
--- a/backend/apps/cloud/src/admin/admin.service.ts
+++ b/backend/apps/cloud/src/admin/admin.service.ts
@@ -713,6 +713,13 @@ export class AdminService {
return payments
}
+ // A cold history crawl takes a while - concurrent requests that miss the
+ // cache share the one in flight instead of each starting their own
+ private paddleHistoryFetch: Promise<{
+ payments: HistoricPayment[]
+ fetchedAt: string
+ } | null> | null = null
+
private async getCachedPaddleHistory(): Promise<{
payments: HistoricPayment[]
fetchedAt: string
@@ -731,6 +738,21 @@ export class AdminService {
return null
}
+ if (!this.paddleHistoryFetch) {
+ this.paddleHistoryFetch = this.fetchAndCachePaddleHistory().finally(
+ () => {
+ this.paddleHistoryFetch = null
+ },
+ )
+ }
+
+ return this.paddleHistoryFetch
+ }
+
+ private async fetchAndCachePaddleHistory(): Promise<{
+ payments: HistoricPayment[]
+ fetchedAt: string
+ } | null> {
let result: { payments: HistoricPayment[]; fetchedAt: string }
try {
@@ -883,10 +905,12 @@ export class AdminService {
}
// The current month is deliberately left out: it is always mid-collection,
- // so it would render as a cliff on the chart
+ // so it would render as a cliff on the chart. The clamp keeps a caller
+ // from asking for months that have no bucket behind them.
+ const displayedMonths = Math.min(months, REVENUE_HISTORY_MONTHS - 1)
const displayedKeys: string[] = []
- for (let offset = months; offset >= 1; offset -= 1) {
+ for (let offset = displayedMonths; offset >= 1; offset -= 1) {
displayedKeys.push(shiftMonthKey(currentKey, -offset))
}
@@ -920,6 +944,16 @@ export class AdminService {
}
})
+ // Cash collected over the last twelve complete months, read off the full
+ // bucket map rather than the displayed window, so a 6-month view still
+ // reports a true trailing-twelve-month total
+ let ttmCashUsd = 0
+
+ for (let offset = MONTHS_IN_YEAR; offset >= 1; offset -= 1) {
+ ttmCashUsd +=
+ buckets.get(shiftMonthKey(currentKey, -offset))?.cashUsd ?? 0
+ }
+
const current = buckets.get(currentKey)
const dayOfMonth = now.getUTCDate()
const daysInMonth = new Date(
@@ -940,12 +974,12 @@ export class AdminService {
// of last month or just early in the cycle?"
projectedUsd: round2((current.cashUsd / dayOfMonth) * daysInMonth),
},
- summary: this.summariseTrends(rows),
+ summary: this.summariseTrends(rows, ttmCashUsd),
fetchedAt: history.fetchedAt,
}
}
- private summariseTrends(rows: TrendRow[]) {
+ private summariseTrends(rows: TrendRow[], ttmCashUsd: number) {
const last = rows[rows.length - 1]
const previous = rows[rows.length - 2]
@@ -1002,11 +1036,7 @@ export class AdminService {
recentChanges.length,
)
: null,
- ttmCashUsd: round2(
- rows
- .slice(-MONTHS_IN_YEAR)
- .reduce((total, row) => total + row.cashUsd, 0),
- ),
+ ttmCashUsd: round2(ttmCashUsd),
// Yearly plans are recognised monthly, so this is a run rate rather than
// a promise of next month's cash
runRateUsd: round2((last?.recognisedUsd ?? 0) * MONTHS_IN_YEAR),
@@ -1059,7 +1089,21 @@ export class AdminService {
}
if (user.cancellationEffectiveDate) {
- return 'cancelling'
+ // Cancelling during the trial ends the subscription on the trial end
+ // date itself; a converted account that cancels later ends on a bill
+ // date at least one billing period after that. The day of grace absorbs
+ // date-only columns and timezone truncation.
+ const cancellationAt = new Date(user.cancellationEffectiveDate).getTime()
+ const trialEnd = user.trialEndDate
+ ? new Date(user.trialEndDate).getTime()
+ : null
+
+ if (
+ trialEnd === null ||
+ cancellationAt <= trialEnd + 24 * 60 * 60 * 1000
+ ) {
+ return 'cancelling'
+ }
}
return isTrialing(user) ? 'trialing' : 'converted'
diff --git a/web/app/pages/Admin/RevenueTrends.tsx b/web/app/pages/Admin/RevenueTrends.tsx
index 1aeea3916..935f1a407 100644
--- a/web/app/pages/Admin/RevenueTrends.tsx
+++ b/web/app/pages/Admin/RevenueTrends.tsx
@@ -1,15 +1,16 @@
import dayjs from 'dayjs'
+import { useMemo } from 'react'
import { Badge } from '~/ui/Badge'
import Select from '~/ui/Select'
import { Text } from '~/ui/Text'
import { cn, nFormatter, nLocaleFormatter } from '~/utils/generic'
+import type { AdminChartSeries } from './AdminChart'
import { AdminChart, ADMIN_CHART_COLORS } from './AdminChart'
import { AdminTable, EmptyState, StatCard, Td } from './components'
import type { AdminRevenueTrends, AdminRevenueTrendMonth } from './types'
-
-const TREND_MONTHS_OPTIONS = [6, 12, 24]
+import { TREND_MONTHS_OPTIONS } from './types'
const usd = (amount: number): string =>
`$${nLocaleFormatter(Math.round(amount))}`
@@ -79,7 +80,40 @@ export const RevenueTrends = ({
months,
onMonthsChange,
}: RevenueTrendsProps) => {
- if (!trends?.available || !trends.months?.length || !trends.summary) {
+ const rows = trends?.months
+
+ // A stable series identity keeps unrelated parent re-renders from
+ // regenerating the billboard.js chart
+ const series = useMemo<AdminChartSeries[]>(
+ () =>
+ rows
+ ? [
+ {
+ id: 'cash',
+ name: 'Cash collected',
+ color: ADMIN_CHART_COLORS.blue,
+ type: 'bar',
+ data: rows.map((row) => ({
+ date: `${row.month}-01`,
+ count: row.cashUsd,
+ })),
+ },
+ {
+ id: 'recognised',
+ name: 'Recurring revenue',
+ color: ADMIN_CHART_COLORS.green,
+ type: 'line',
+ data: rows.map((row) => ({
+ date: `${row.month}-01`,
+ count: row.recognisedUsd,
+ })),
+ },
+ ]
+ : [],
+ [rows],
+ )
+
+ if (!trends?.available || !rows?.length || !trends.summary) {
return (
<section>
<Text as='h3' size='lg' weight='semibold'>
@@ -93,7 +127,6 @@ export const RevenueTrends = ({
}
const { summary, currentMonth } = trends
- const rows = trends.months
const rowsDesc = [...rows].reverse()
const paceVsLastMonth =
@@ -174,28 +207,7 @@ export const RevenueTrends = ({
<AdminChart
className='mt-4 h-72'
format={CHART_FORMAT}
- series={[
- {
- id: 'cash',
- name: 'Cash collected',
- color: ADMIN_CHART_COLORS.blue,
- type: 'bar',
- data: rows.map((row) => ({
- date: `${row.month}-01`,
- count: row.cashUsd,
- })),
- },
- {
- id: 'recognised',
- name: 'Recurring revenue',
- color: ADMIN_CHART_COLORS.green,
- type: 'line',
- data: rows.map((row) => ({
- date: `${row.month}-01`,
- count: row.recognisedUsd,
- })),
- },
- ]}
+ series={series}
/>
</div>
diff --git a/web/app/pages/Admin/types.ts b/web/app/pages/Admin/types.ts
index d8219d26e..9ff90d24a 100644
--- a/web/app/pages/Admin/types.ts
+++ b/web/app/pages/Admin/types.ts
@@ -94,6 +94,10 @@ export interface AdminBilling {
}
}
+// Window sizes the revenue-trends picker offers - the loader validates the
+// query param against the same list. Mirrors REVENUE_TREND_MONTHS on the API.
+export const TREND_MONTHS_OPTIONS = [6, 12, 24]
+
export interface AdminRevenueTrendMonth {
month: string
cashUsd: number
diff --git a/web/app/routes/admin.tsx b/web/app/routes/admin.tsx
index 3b606808e..d508cedbe 100644
--- a/web/app/routes/admin.tsx
+++ b/web/app/routes/admin.tsx
@@ -16,6 +16,7 @@ import NotFound from '~/pages/NotFound'
// lives in this stylesheet - without it the admin charts render with
// billboard defaults
import ProjectViewStyle from '~/styles/ProjectViewStyle.css?url'
+import { TREND_MONTHS_OPTIONS } from '~/pages/Admin/types'
import type {
AdminActionData,
AdminBilling,
@@ -75,7 +76,6 @@ const TABS: AdminTab[] = [
]
const CHART_DAYS = [30, 90, 180, 365]
-const TREND_MONTHS = [6, 12, 24]
const notFound = () => new Response('Not Found', { status: 404 })
@@ -148,7 +148,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
if (tab === 'billing') {
- const trendMonths = TREND_MONTHS.includes(
+ const trendMonths = TREND_MONTHS_OPTIONS.includes(
Number(searchParams.get('months')),
)
? Number(searchParams.get('months'))