📈 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
Admin - billing revenue trends
Blue Mouse97de1756e284
diff --git a/backend/apps/cloud/src/admin/admin.controller.ts b/backend/apps/cloud/src/admin/admin.controller.tsindex e128fc7a6..992711ea0 100644--- a/backend/apps/cloud/src/admin/admin.controller.ts+++ b/backend/apps/cloud/src/admin/admin.controller.ts@@ -14,6 +14,7 @@ import {AdminService,FeedbackType,ProjectsFilter,+ REVENUE_TREND_MONTHS,UsersFilter,} from './admin.service'import { AdminAuth } from './decorators/admin-auth.decorator'@@ -119,6 +120,13 @@ export class AdminController {return this.adminService.getBilling()}+ @Get('revenue-trends')+ async getRevenueTrends(@Query('months') months?: string) {+ return this.adminService.getRevenueTrends(+ parseDays(months, REVENUE_TREND_MONTHS, 12),+ )+ }+@Get('bot-blocks')async getBotBlocks(@Query('days') days?: string) {return this.adminService.getBotBlocks(parseDays(days, [7, 30, 90], 7))diff --git a/backend/apps/cloud/src/admin/admin.service.ts b/backend/apps/cloud/src/admin/admin.service.tsindex 14d98fdcc..20387a97d 100644--- a/backend/apps/cloud/src/admin/admin.service.ts+++ b/backend/apps/cloud/src/admin/admin.service.ts@@ -15,10 +15,12 @@ import { DeleteFeedback } from '../user/entities/delete-feedback.entity'import {ACCOUNT_PLANS,BillingFrequency,+ DashboardBlockReason,getEffectiveAccountLimits,getEffectivePlanType,PlanCode,PlanType,+ TRIAL_DURATION,User,} from '../user/entities/user.entity'import { UserFeedback } from '../user/entities/user-feedback.entity'@@ -40,6 +42,25 @@ const BILLABLE_COUNT_IF = `countIf(type IN ('pageview', 'custom_event', 'error')const FREE_PLAN_CODES = [PlanCode.none, PlanCode.free, PlanCode.trial]+// Plans a trial cannot be on. `PlanCode.trial` is deliberately absent: it is+// the legacy card-less trial, which is a trial too+const LAPSED_PLAN_CODES = [PlanCode.none, PlanCode.free]++// Since trials became card-first, `planCode` holds the real paid plan for the+// whole trial and `trialEndDate` is the only thing that says "not paying yet".+// Reading trial state off `planCode = PlanCode.trial` (the legacy card-less+// flow) silently matches nobody.+const isTrialing = (user: {+ planCode: PlanCode+ trialEndDate: Date | string | null+}): boolean =>+ Boolean(user.trialEndDate) &&+ new Date(user.trialEndDate).getTime() > Date.now() &&+ !LAPSED_PLAN_CODES.includes(user.planCode)++const TRIALING_CONDITION =+ 'user.trialEndDate IS NOT NULL AND user.trialEndDate > :now AND user.planCode NOT IN (:...lapsedPlans)'+const USERS_PAGE_SIZE = 25const PROJECTS_PAGE_SIZE = 25const ORGANISATIONS_PAGE_SIZE = 25@@ -181,6 +202,28 @@ const { PADDLE_VENDOR_ID, PADDLE_API_KEY } = process.envconst REVENUE_CACHE_KEY = 'admin:paddle-payments:v2'// Paddle's vendor API is rate limited; the numbers do not move fast anywayconst REVENUE_CACHE_TTL_SECONDS = 3600+const PADDLE_FETCH_TIMEOUT_MS = 15000++const REVENUE_HISTORY_CACHE_KEY = 'admin:paddle-payments-history:v1'+// History only changes when a new payment lands, and the trends are a+// month-level view - a stale-by-hours cache is fine+const REVENUE_HISTORY_CACHE_TTL_SECONDS = 6 * 60 * 60+// Longer than the longest chart window on purpose: a yearly payment made+// before the window still has to be recognised inside it+const REVENUE_HISTORY_MONTHS = 36+// Paddle returns the whole range in one response - keep each one small+const REVENUE_HISTORY_CHUNK_MONTHS = 3+const REVENUE_HISTORY_CONCURRENCY = 4+export const REVENUE_TREND_MONTHS = [6, 12, 24]+// A subscription billing this far apart is a yearly one, so its payment is+// spread over 12 months instead of landing in a single one+const YEARLY_PERIOD_MIN_GAP_DAYS = 300+const MONTHS_IN_YEAR = 12++const TRIAL_LOOKAHEAD_DAYS = TRIAL_DURATION+const TRIAL_LOOKBACK_DAYS = 30+const TRIAL_STATS_DAYS = 90+const TOP_ACCOUNTS_LIMIT = 5// Rough, static FX rates used only to produce a single comparable USD numberconst APPROX_USD_RATES: Record<string, number> = {@@ -200,6 +243,36 @@ interface PaddlePayment {receipt_url?: string}+// Trimmed-down payment - a few years of them are cached in redis+interface HistoricPayment {+ subscriptionId: number+ amount: number+ currency: string+ date: string+ isOneOff: boolean+}++interface MonthBucket {+ // Money that actually landed in the month+ cashUsd: number+ // Money the month is entitled to, with yearly payments spread across the+ // year they buy - the closest thing to an MRR series we can reconstruct+ recognisedUsd: number+ oneOffUsd: number+ byCurrency: Record<string, number>+ payments: number+ payers: Set<number>+ activeSubs: Set<number>+}++type TrendRow = Omit<MonthBucket, 'payers' | 'activeSubs'> & {+ month: string+ payers: number+ activeSubs: number+ newSubs: number+ churnedSubs: number+}+const CHURN_RISK_MIN_PREV_EVENTS = 100const CHURN_RISK_MIN_DROP = 0.5@@ -218,6 +291,13 @@ interface MrrSubscription {tierCurrency: string | null}+type TrialOutcome =+ | 'trialing'+ | 'converted'+ | 'cancelling'+ | 'expired'+ | 'payment_issue'+export type UsersFilter =| 'all'| 'active'@@ -240,6 +320,28 @@ export type ProjectsFilter =const dateToChDateTime = (date: Date): string =>date.toISOString().slice(0, 19).replace('T', ' ')+const toDateString = (date: Date): string => date.toISOString().slice(0, 10)++// Everything in the revenue trends is bucketed by UTC calendar month+const monthKey = (date: Date | string): string =>+ new Date(date).toISOString().slice(0, 7)++const shiftMonthKey = (key: string, offset: number): string => {+ const [year, month] = key.split('-').map(Number)++ return monthKey(new Date(Date.UTC(year, month - 1 + offset, 1)))+}++const round2 = (value: number): number => Math.round(value * 100) / 100++const percentChange = (current: number, previous: number): number | null =>+ previous > 0+ ? Math.round(((current - previous) / previous) * 1000) / 10+ : null++const daysBetween = (from: number, to: number): number =>+ (to - from) / (24 * 60 * 60 * 1000)+@Injectable()export class AdminService {constructor(@@ -303,6 +405,7 @@ export class AdminService {'planType','billingFrequency','tierCurrency',+ 'trialEndDate',],})@@ -313,6 +416,9 @@ export class AdminService {}let usdEquivalent = 0let unpricedSubscriptions = 0+ let payingUsers = 0+ let trialingUsers = 0+ let trialUsdEquivalent = 0for (const user of paidUsers) {const revenue = this.getMonthlyRevenue(user)@@ -322,6 +428,15 @@ export class AdminService {continue}+ // Card-first trials sit on a real plan code without having paid a penny+ // yet - counting them as MRR would inflate it by a whole trial cohort+ if (isTrialing(user)) {+ trialingUsers += 1+ trialUsdEquivalent += revenue.usdAmount+ continue+ }++ payingUsers += 1byCurrency[revenue.currency] += revenue.amountusdEquivalent += revenue.usdAmount}@@ -333,8 +448,10 @@ export class AdminService {GBP: Math.round(byCurrency.GBP * 100) / 100,},// Every subscription valued at its USD list price; an estimate, not accounting data- usdEquivalent: Math.round(usdEquivalent * 100) / 100,- payingUsers: paidUsers.length,+ usdEquivalent: round2(usdEquivalent),+ payingUsers,+ trialingUsers,+ trialUsdEquivalent: round2(trialUsdEquivalent),unpricedSubscriptions,}}@@ -359,6 +476,7 @@ export class AdminService {method: 'POST',headers: { 'Content-Type': 'application/x-www-form-urlencoded' },body,+ signal: AbortSignal.timeout(PADDLE_FETCH_TIMEOUT_MS),},)@@ -427,8 +545,6 @@ export class AdminService {return null}- const toDateString = (date: Date) => date.toISOString().slice(0, 10)-const now = new Date()const previousMonthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 1, 1),@@ -522,6 +638,384 @@ export class AdminService {}}+ // -------------------- Revenue trends --------------------++ // Several years of payments in one request would be a single huge response,+ // so the range is walked in chunks and stored in a compact shape+ private async fetchPaddleHistory(): Promise<HistoricPayment[]> {+ const now = new Date()+ const windowStart = new Date(+ Date.UTC(+ now.getUTCFullYear(),+ now.getUTCMonth() - (REVENUE_HISTORY_MONTHS - 1),+ 1,+ ),+ )++ const ranges: [string, string][] = []++ for (+ let cursor = windowStart;+ cursor <= now;+ cursor = new Date(+ Date.UTC(+ cursor.getUTCFullYear(),+ cursor.getUTCMonth() + REVENUE_HISTORY_CHUNK_MONTHS,+ 1,+ ),+ )+ ) {+ // Day 0 of the month after the chunk = last day of the chunk, so the+ // ranges never overlap+ const chunkEnd = new Date(+ Date.UTC(+ cursor.getUTCFullYear(),+ cursor.getUTCMonth() + REVENUE_HISTORY_CHUNK_MONTHS,+ 0,+ ),+ )++ ranges.push([toDateString(cursor), toDateString(chunkEnd)])+ }++ const seenIds = new Set<number>()+ const payments: HistoricPayment[] = []++ for (+ let index = 0;+ index < ranges.length;+ index += REVENUE_HISTORY_CONCURRENCY+ ) {+ const batch = await Promise.all(+ ranges+ .slice(index, index + REVENUE_HISTORY_CONCURRENCY)+ .map(([from, to]) => this.fetchPaddlePayments(from, to, 1)),+ )++ for (const chunk of batch) {+ for (const payment of chunk) {+ if (seenIds.has(payment.id)) {+ continue+ }++ seenIds.add(payment.id)+ payments.push({+ subscriptionId: Number(payment.subscription_id),+ amount: Number(payment.amount) || 0,+ currency: payment.currency || 'USD',+ date: String(payment.payout_date).slice(0, 10),+ isOneOff: Boolean(payment.is_one_off_charge),+ })+ }+ }+ }++ return payments+ }++ private async getCachedPaddleHistory(): Promise<{+ payments: HistoricPayment[]+ fetchedAt: string+ } | null> {+ const cached = await redis.get(REVENUE_HISTORY_CACHE_KEY).catch(() => null)++ if (cached) {+ try {+ return JSON.parse(cached)+ } catch {+ // fall through to a fresh fetch+ }+ }++ if (!PADDLE_VENDOR_ID || !PADDLE_API_KEY) {+ return null+ }++ let result: { payments: HistoricPayment[]; fetchedAt: string }++ try {+ result = {+ payments: await this.fetchPaddleHistory(),+ fetchedAt: new Date().toISOString(),+ }+ } catch (error) {+ console.error('[ERROR] (admin getCachedPaddleHistory):', error)+ return null+ }++ await redis+ .set(+ REVENUE_HISTORY_CACHE_KEY,+ JSON.stringify(result),+ 'EX',+ REVENUE_HISTORY_CACHE_TTL_SECONDS,+ )+ .catch(() => null)++ return result+ }++ // A yearly payment buys twelve months of service. Recognising all of it in+ // the month it landed would spike the trend line and flatline the rest of+ // the year, so each payment needs to know the period it covers.+ private buildBillingPeriods(+ payments: HistoricPayment[],+ yearlySubIds: Set<number>,+ ): Map<number, number> {+ const timestampsBySub = new Map<number, number[]>()++ for (const payment of payments) {+ if (payment.isOneOff) {+ continue+ }++ const timestamps = timestampsBySub.get(payment.subscriptionId) || []++ timestamps.push(new Date(payment.date).getTime())+ timestampsBySub.set(payment.subscriptionId, timestamps)+ }++ const periods = new Map<number, number>()++ for (const [subscriptionId, timestamps] of timestampsBySub) {+ timestamps.sort((a, b) => a - b)++ const gaps: number[] = []++ for (let index = 1; index < timestamps.length; index += 1) {+ gaps.push(daysBetween(timestamps[index - 1], timestamps[index]))+ }++ gaps.sort((a, b) => a - b)++ // How the account actually billed beats the current DB flag - it also+ // covers subscriptions that have since been cancelled or changed plan+ const isYearly =+ gaps.length > 0+ ? gaps[Math.floor(gaps.length / 2)] >= YEARLY_PERIOD_MIN_GAP_DAYS+ : yearlySubIds.has(subscriptionId)++ periods.set(subscriptionId, isYearly ? MONTHS_IN_YEAR : 1)+ }++ return periods+ }++ async getRevenueTrends(months: number) {+ const history = await this.getCachedPaddleHistory()++ if (!history) {+ return { available: false as const }+ }++ const subIds = Array.from(+ new Set(history.payments.map(({ subscriptionId }) => subscriptionId)),+ ).map(String)++ const yearlyUsers =+ subIds.length > 0+ ? await this.userRepository.find({+ where: {+ subID: In(subIds),+ billingFrequency: BillingFrequency.Yearly,+ },+ select: ['subID'],+ })+ : []++ const periods = this.buildBillingPeriods(+ history.payments,+ new Set(yearlyUsers.map(({ subID }) => Number(subID))),+ )++ const now = new Date()+ const currentKey = monthKey(now)+ const buckets = new Map<string, MonthBucket>()++ // Buckets span the whole fetched history, not just the displayed window,+ // so yearly payments made before it still get recognised inside it+ for (let offset = REVENUE_HISTORY_MONTHS - 1; offset >= 0; offset -= 1) {+ buckets.set(shiftMonthKey(currentKey, -offset), {+ cashUsd: 0,+ recognisedUsd: 0,+ oneOffUsd: 0,+ byCurrency: {},+ payments: 0,+ payers: new Set(),+ activeSubs: new Set(),+ })+ }++ for (const payment of history.payments) {+ const key = monthKey(payment.date)+ const bucket = buckets.get(key)++ if (!bucket) {+ continue+ }++ const usd = payment.amount * (APPROX_USD_RATES[payment.currency] ?? 1)++ bucket.cashUsd += usd+ bucket.byCurrency[payment.currency] =+ (bucket.byCurrency[payment.currency] || 0) + payment.amount+ bucket.payments += 1+ bucket.payers.add(payment.subscriptionId)++ if (payment.isOneOff) {+ bucket.oneOffUsd += usd+ continue+ }++ const period = periods.get(payment.subscriptionId) || 1+ const perMonth = usd / period++ for (let offset = 0; offset < period; offset += 1) {+ const covered = buckets.get(shiftMonthKey(key, offset))++ if (!covered) {+ break+ }++ covered.recognisedUsd += perMonth+ covered.activeSubs.add(payment.subscriptionId)+ }+ }++ // The current month is deliberately left out: it is always mid-collection,+ // so it would render as a cliff on the chart+ const displayedKeys: string[] = []++ for (let offset = months; offset >= 1; offset -= 1) {+ displayedKeys.push(shiftMonthKey(currentKey, -offset))+ }++ const rows = displayedKeys.map((key) => {+ const bucket = buckets.get(key)+ const previous = buckets.get(shiftMonthKey(key, -1))+ const activeSubs = Array.from(bucket.activeSubs)++ return {+ month: key,+ cashUsd: round2(bucket.cashUsd),+ recognisedUsd: round2(bucket.recognisedUsd),+ oneOffUsd: round2(bucket.oneOffUsd),+ byCurrency: Object.fromEntries(+ Object.entries(bucket.byCurrency).map(([currency, amount]) => [+ currency,+ round2(amount),+ ]),+ ),+ payments: bucket.payments,+ payers: bucket.payers.size,+ activeSubs: activeSubs.length,+ newSubs: previous+ ? activeSubs.filter((id) => !previous.activeSubs.has(id)).length+ : 0,+ churnedSubs: previous+ ? Array.from(previous.activeSubs).filter(+ (id) => !bucket.activeSubs.has(id),+ ).length+ : 0,+ }+ })++ const current = buckets.get(currentKey)+ const dayOfMonth = now.getUTCDate()+ const daysInMonth = new Date(+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0),+ ).getUTCDate()++ return {+ available: true as const,+ months: rows,+ currentMonth: {+ month: currentKey,+ cashUsd: round2(current.cashUsd),+ payments: current.payments,+ payers: current.payers.size,+ dayOfMonth,+ daysInMonth,+ // Straight-line pace, not a forecast - useful to answer "are we ahead+ // of last month or just early in the cycle?"+ projectedUsd: round2((current.cashUsd / dayOfMonth) * daysInMonth),+ },+ summary: this.summariseTrends(rows),+ fetchedAt: history.fetchedAt,+ }+ }++ private summariseTrends(rows: TrendRow[]) {+ const last = rows[rows.length - 1]+ const previous = rows[rows.length - 2]++ const changes: number[] = []++ for (let index = 1; index < rows.length; index += 1) {+ const change = percentChange(+ rows[index].recognisedUsd,+ rows[index - 1].recognisedUsd,+ )++ if (change !== null) {+ changes.push(change)+ }+ }++ const recentChanges = changes.slice(-3)++ // Signed run of consecutive months moving the same way, counted back from+ // the most recent one+ let streak = 0++ for (let index = rows.length - 1; index > 0; index -= 1) {+ const delta = rows[index].recognisedUsd - rows[index - 1].recognisedUsd+ const direction = Math.sign(delta)++ if (+ direction === 0 ||+ (streak !== 0 && Math.sign(streak) !== direction)+ ) {+ break+ }++ streak += direction+ }++ const best = rows.reduce<TrendRow | null>(+ (winner, row) => (!winner || row.cashUsd > winner.cashUsd ? row : winner),+ null,+ )++ return {+ lastCompleteMonth: last?.month || null,+ recognisedUsd: last?.recognisedUsd ?? 0,+ momPercent:+ last && previous+ ? percentChange(last.recognisedUsd, previous.recognisedUsd)+ : null,+ cashMomPercent:+ last && previous ? percentChange(last.cashUsd, previous.cashUsd) : null,+ avgMomPercent: recentChanges.length+ ? round2(+ recentChanges.reduce((total, value) => total + value, 0) /+ recentChanges.length,+ )+ : null,+ ttmCashUsd: round2(+ rows+ .slice(-MONTHS_IN_YEAR)+ .reduce((total, row) => total + row.cashUsd, 0),+ ),+ // 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),+ netNewSubs: (last?.newSubs ?? 0) - (last?.churnedSubs ?? 0),+ streak,+ bestMonth: best ? { month: best.month, cashUsd: best.cashUsd } : null,+ }+ }+// -------------------- Billing health --------------------private formatBillingUser(user: User) {@@ -546,43 +1040,103 @@ export class AdminService {}}+ // What happened to a trial, read off the columns the Paddle webhooks and the+ // trial crons write. A card-first trial that converts keeps its plan and+ // rolls its nextBillDate forward; one that does not falls back to `none`.+ private getTrialOutcome(user: User): TrialOutcome {+ if (+ LAPSED_PLAN_CODES.includes(user.planCode) ||+ user.dashboardBlockReason === DashboardBlockReason.trial_ended+ ) {+ return 'expired'+ }++ if (+ user.isAccountBillingSuspended ||+ user.dashboardBlockReason === DashboardBlockReason.payment_failed+ ) {+ return 'payment_issue'+ }++ if (user.cancellationEffectiveDate) {+ return 'cancelling'+ }++ return isTrialing(user) ? 'trialing' : 'converted'+ }+async getBilling() {const now = new Date()- const in14d = new Date(now.getTime() + 14 * 24 * 60 * 60 * 1000)- const monthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)+ const trialWindowEnd = new Date(+ now.getTime() + TRIAL_LOOKAHEAD_DAYS * 24 * 60 * 60 * 1000,+ )+ const trialWindowStart = new Date(+ now.getTime() - TRIAL_LOOKBACK_DAYS * 24 * 60 * 60 * 1000,+ )+ const trialStatsStart = new Date(+ now.getTime() - TRIAL_STATS_DAYS * 24 * 60 * 60 * 1000,+ )- const [trialUsers, cancellingUsers, suspendedUsers, payingUsers, paddle] =- await Promise.all([- // Recently-expired trials are as interesting as expiring ones - they- // are the ones worth a personal follow-up email- this.userRepository- .createQueryBuilder('user')- .loadRelationCountAndMap('user.projectCount', 'user.projects')- .where('user.planCode = :trial', { trial: PlanCode.trial })- .andWhere('user.trialEndDate IS NOT NULL')- .andWhere('user.trialEndDate <= :in14d', { in14d })- .andWhere('user.trialEndDate >= :monthAgo', { monthAgo })- .orderBy('user.trialEndDate', 'ASC')- .take(100)- .getMany(),- this.userRepository.find({- where: { cancellationEffectiveDate: Not(IsNull()) },- order: { cancellationEffectiveDate: 'ASC' },- take: 100,- }),- this.userRepository- .createQueryBuilder('user')- .where(- '(user.isAccountBillingSuspended = true OR user.dashboardBlockReason IS NOT NULL)',- )- .orderBy('user.created', 'DESC')- .take(100)- .getMany(),- this.userRepository.find({- where: { planCode: Not(In(FREE_PLAN_CODES)) },- }),- this.getCachedPaddlePayments(),- ])+ const [+ trialUsers,+ resolvedTrials,+ cancellingUsers,+ suspendedUsers,+ subscribedUsers,+ paddle,+ ] = await Promise.all([+ // Trial state lives in trialEndDate, not planCode - see `isTrialing`.+ // Recently-expired trials are as interesting as expiring ones: they are+ // the ones worth a personal follow-up email.+ this.userRepository+ .createQueryBuilder('user')+ .loadRelationCountAndMap('user.projectCount', 'user.projects')+ .where('user.trialEndDate IS NOT NULL')+ .andWhere('user.trialEndDate <= :trialWindowEnd', { trialWindowEnd })+ .andWhere('user.trialEndDate >= :trialWindowStart', {+ trialWindowStart,+ })+ .orderBy('user.trialEndDate', 'ASC')+ .take(100)+ .getMany(),+ // Every trial that has already run its course in the stats window, for+ // the conversion rate. Only the columns getTrialOutcome reads.+ this.userRepository+ .createQueryBuilder('user')+ .select([+ 'user.id',+ 'user.planCode',+ 'user.trialEndDate',+ 'user.cancellationEffectiveDate',+ 'user.dashboardBlockReason',+ 'user.isAccountBillingSuspended',+ ])+ .where('user.trialEndDate IS NOT NULL')+ .andWhere('user.trialEndDate <= :now', { now })+ .andWhere('user.trialEndDate >= :trialStatsStart', { trialStatsStart })+ .getMany(),+ this.userRepository.find({+ where: { cancellationEffectiveDate: Not(IsNull()) },+ order: { cancellationEffectiveDate: 'ASC' },+ take: 100,+ }),+ this.userRepository+ .createQueryBuilder('user')+ .where(+ '(user.isAccountBillingSuspended = true OR user.dashboardBlockReason IS NOT NULL)',+ )+ .orderBy('user.created', 'DESC')+ .take(100)+ .getMany(),+ this.userRepository.find({+ where: { planCode: Not(In(FREE_PLAN_CODES)) },+ }),+ this.getCachedPaddlePayments(),+ ])++ // Accounts still inside their trial have not paid anything yet - keeping+ // them out of the revenue maths is what makes these numbers real money+ const payingUsers = subscribedUsers.filter((user) => !isTrialing(user))const [trialUsage, churnRisk, payments] = await Promise.all([this.getMonthlyEventsForUsers(trialUsers.map((user) => user.id)),@@ -590,14 +1144,35 @@ export class AdminService {this.buildPaymentsFeed(paddle),])+ const outcomes = resolvedTrials.map((user) => this.getTrialOutcome(user))+ const converted = outcomes.filter(+ (outcome) => outcome === 'converted',+ ).length+return {trialsEndingSoon: trialUsers.map((user: User & { projectCount?: number }) => ({...this.formatBillingUser(user),projectCount: user.projectCount || 0,monthlyEvents: trialUsage[user.id] || 0,+ outcome: this.getTrialOutcome(user),}),),+ trialStats: {+ windowDays: TRIAL_STATS_DAYS,+ activeNow: subscribedUsers.filter((user) => isTrialing(user)).length,+ resolved: resolvedTrials.length,+ converted,+ conversionRate: resolvedTrials.length+ ? Math.round((converted / resolvedTrials.length) * 100)+ : null,+ cancelledDuringTrial: outcomes.filter(+ (outcome) => outcome === 'cancelling',+ ).length,+ paymentIssues: outcomes.filter((outcome) => outcome === 'payment_issue')+ .length,+ },+ mrr: this.summariseSubscriptionMrr(subscribedUsers),cancellationPipeline: cancellingUsers.map((user) =>this.formatBillingUser(user),),@@ -607,6 +1182,96 @@ export class AdminService {}}+ // Where the recurring revenue actually comes from: plan tier, billing+ // frequency, and how much of it rides on the largest few accounts+ private summariseSubscriptionMrr(subscribedUsers: User[]) {+ const byPlanType: Record<string, { accounts: number; usd: number }> = {}+ const byFrequency: Record<string, { accounts: number; usd: number }> = {}+ const accounts: {+ id: string+ email: string+ planCode: PlanCode+ usd: number+ }[] = []++ let usd = 0+ let trialUsd = 0+ let trialingAccounts = 0+ let unpriced = 0++ for (const user of subscribedUsers) {+ const revenue = this.getMonthlyRevenue(user)++ if (!revenue) {+ unpriced += 1+ continue+ }++ if (isTrialing(user)) {+ trialingAccounts += 1+ trialUsd += revenue.usdAmount+ continue+ }++ const planType = getEffectivePlanType(user) || PlanType.standard+ const frequency = user.billingFrequency || BillingFrequency.Monthly++ byPlanType[planType] = byPlanType[planType] || { accounts: 0, usd: 0 }+ byPlanType[planType].accounts += 1+ byPlanType[planType].usd += revenue.usdAmount++ byFrequency[frequency] = byFrequency[frequency] || { accounts: 0, usd: 0 }+ byFrequency[frequency].accounts += 1+ byFrequency[frequency].usd += revenue.usdAmount++ accounts.push({+ id: user.id,+ email: user.email,+ planCode: user.planCode,+ usd: revenue.usdAmount,+ })+ usd += revenue.usdAmount+ }++ const topAccounts = accounts+ .sort((a, b) => b.usd - a.usd)+ .slice(0, TOP_ACCOUNTS_LIMIT)++ const topUsd = topAccounts.reduce(+ (total, account) => total + account.usd,+ 0,+ )++ const toBreakdown = (+ grouped: Record<string, { accounts: number; usd: number }>,+ ) =>+ Object.entries(grouped)+ .map(([key, value]) => ({+ key,+ accounts: value.accounts,+ usd: round2(value.usd),+ }))+ .sort((a, b) => b.usd - a.usd)++ return {+ usd: round2(usd),+ payingAccounts: accounts.length,+ arpuUsd: accounts.length ? round2(usd / accounts.length) : 0,+ trialingAccounts,+ // What the trials currently running are worth if they all convert+ trialUsd: round2(trialUsd),+ unpricedSubscriptions: unpriced,+ byPlanType: toBreakdown(byPlanType),+ byFrequency: toBreakdown(byFrequency),+ topAccounts: topAccounts.map((account) => ({+ ...account,+ usd: round2(account.usd),+ })),+ // Concentration risk: how much of the MRR walks out with five customers+ topAccountsPercent: usd > 0 ? Math.round((topUsd / usd) * 100) : 0,+ }+ }+private async buildPaymentsFeed(paddle: {paid: PaddlePayment[]@@ -953,10 +1618,20 @@ export class AdminService {] = await Promise.all([this.userRepository.count(),this.userRepository.count({ where: { isActive: true } }),- this.userRepository.count({- where: { planCode: Not(In(FREE_PLAN_CODES)) },- }),- this.userRepository.count({ where: { planCode: PlanCode.trial } }),+ this.userRepository+ .createQueryBuilder('user')+ .where('user.planCode NOT IN (:...freePlans)', {+ freePlans: FREE_PLAN_CODES,+ })+ .andWhere(`NOT (${TRIALING_CONDITION})`, {+ now,+ lapsedPlans: LAPSED_PLAN_CODES,+ })+ .getCount(),+ this.userRepository+ .createQueryBuilder('user')+ .where(TRIALING_CONDITION, { now, lapsedPlans: LAPSED_PLAN_CODES })+ .getCount(),this.userRepository.count({where: { cancellationEffectiveDate: Not(IsNull()) },}),@@ -1301,12 +1976,18 @@ export class AdminService {} else if (filter === 'inactive') {query = query.andWhere('user.isActive = false')} else if (filter === 'paid') {- query = query.andWhere('user.planCode NOT IN (:...freePlans)', {- freePlans: FREE_PLAN_CODES,- })+ query = query+ .andWhere('user.planCode NOT IN (:...freePlans)', {+ freePlans: FREE_PLAN_CODES,+ })+ .andWhere(`NOT (${TRIALING_CONDITION})`, {+ now: new Date(),+ lapsedPlans: LAPSED_PLAN_CODES,+ })} else if (filter === 'trial') {- query = query.andWhere('user.planCode = :planCode', {- planCode: PlanCode.trial,+ query = query.andWhere(TRIALING_CONDITION, {+ now: new Date(),+ lapsedPlans: LAPSED_PLAN_CODES,})} else if (filter === 'free') {query = query.andWhere('user.planCode IN (:...freePlans)', {diff --git a/web/app/pages/Admin/AdminChart.tsx b/web/app/pages/Admin/AdminChart.tsxindex bf7e0cca0..267228ea0 100644--- a/web/app/pages/Admin/AdminChart.tsx+++ b/web/app/pages/Admin/AdminChart.tsx@@ -1,5 +1,5 @@import type { ChartOptions } from 'billboard.js'-import { area } from 'billboard.js'+import { area, bar, line } from 'billboard.js'import * as d3 from 'd3'import dayjs from 'dayjs'import { useMemo } from 'react'@@ -9,11 +9,27 @@ import { nFormatter } from '~/utils/generic'import type { SeriesPoint } from './types'+type AdminChartType = 'area' | 'bar' | 'line'++const CHART_TYPES = { area, bar, line }+export interface AdminChartSeries {id: stringname: stringcolor: stringdata: SeriesPoint[]+ type?: AdminChartType+}++interface AdminChartFormat {+ // Tick label under each point ('%b %d' for daily, '%b %Y' for monthly)+ xTick?: string+ // Heading of the tooltip+ xTooltip?: string+ // Exact value shown in the tooltip+ value?: (value: number) => string+ // Abbreviated value shown on the y axis+ axis?: (value: number) => string}// Same palette as the main analytics dashboard chart@@ -25,11 +41,14 @@ export const ADMIN_CHART_COLORS = {green: '#10B981',} as const-const tooltipDateFormat = d3.timeFormat('%a, %b %d, %Y')+const DEFAULT_TOOLTIP_FORMAT = '%a, %b %d, %Y'// Chart options mirroring the main dashboard's look (gradient areas, circle// legend, custom tooltip) instead of billboard.js defaults-const buildOptions = (series: AdminChartSeries[]): ChartOptions => {+const buildOptions = (+ series: AdminChartSeries[],+ format: AdminChartFormat,+): ChartOptions => {const dates = Array.from(new Set(series.flatMap(({ data }) => data.map(({ date }) => date))),).sort()@@ -43,17 +62,33 @@ const buildOptions = (series: AdminChartSeries[]): ChartOptions => {columns.push([id, ...dates.map((date) => countByDate.get(date) || 0)])}+ const tooltipDateFormat = d3.timeFormat(+ format.xTooltip || DEFAULT_TOOLTIP_FORMAT,+ )+ const formatValue =+ format.value || ((value: number) => value.toLocaleString('en-US'))+return {data: {x: 'x',columns,- types: Object.fromEntries(series.map(({ id }) => [id, area()])),+ types: Object.fromEntries(+ series.map(({ id, type }) => [id, CHART_TYPES[type || 'area']()]),+ ),colors: Object.fromEntries(series.map(({ id, color }) => [id, color])),names: Object.fromEntries(series.map(({ id, name }) => [id, name])),},area: {linearGradient: true,},+ bar: {+ width: {+ ratio: 0.6,+ },+ radius: {+ ratio: 0.15,+ },+ },grid: {y: {show: true,@@ -72,12 +107,14 @@ const buildOptions = (series: AdminChartSeries[]): ChartOptions => {clipPath: false,tick: {fit: false,- format: '%b %d',+ format: format.xTick || '%b %d',},},y: {tick: {- format: (d: number) => (Number.isInteger(d) ? nFormatter(d, 1) : ''),+ format:+ format.axis ||+ ((d: number) => (Number.isInteger(d) ? nFormatter(d, 1) : '')),},show: true,inner: true,@@ -110,7 +147,7 @@ const buildOptions = (series: AdminChartSeries[]): ChartOptions => {<div class='w-2.5 h-2.5 rounded-xs mr-1.5 shrink-0' style='background-color:${color(item.id)}'></div><span class='truncate'>${item.name || item.id}</span></div>- <span class='tabular-nums whitespace-nowrap'>${Number(item.value).toLocaleString('en-US')}</span>+ <span class='tabular-nums whitespace-nowrap'>${formatValue(Number(item.value))}</span></li>`,).join('')@@ -124,16 +161,26 @@ const buildOptions = (series: AdminChartSeries[]): ChartOptions => {}}+// Module-level so the default does not change identity between renders and+// re-generate the chart+const NO_FORMAT: AdminChartFormat = {}+export const AdminChart = ({series,className,+ format = NO_FORMAT,}: {series: AdminChartSeries[]className?: string+ format?: AdminChartFormat}) => {- const options = useMemo(() => buildOptions(series), [series])+ const options = useMemo(() => buildOptions(series, format), [series, format])return (- <BillboardChart options={options} className={className} deps={[series]} />+ <BillboardChart+ options={options}+ className={className}+ deps={[series, format]}+ />)}diff --git a/web/app/pages/Admin/BillingTab.tsx b/web/app/pages/Admin/BillingTab.tsxindex 6cc762487..d7cfcbfe0 100644--- a/web/app/pages/Admin/BillingTab.tsx+++ b/web/app/pages/Admin/BillingTab.tsx@@ -7,8 +7,16 @@ import { Text } from '~/ui/Text'import { nFormatter, nLocaleFormatter } from '~/utils/generic'import { AdminTable, EmptyState, formatDate, StatCard, Td } from './components'+import { RevenueTrends } from './RevenueTrends'import { adminLinkClassName } from './UsersTab'-import type { AdminBilling, AdminBillingUser, AdminPayment } from './types'+import type {+ AdminBilling,+ AdminBillingMrr,+ AdminBillingUser,+ AdminPayment,+ AdminRevenueTrends,+ AdminTrialOutcome,+} from './types'const CURRENCY_SYMBOLS: Record<string, string> = {USD: '$',@@ -84,6 +92,145 @@ const DeadlineBadge = ({ date }: { date: string | null }) => {)}+// What became of a trial. `trialing` is still in flight; everything else is a+// resolved outcome worth reading at a glance.+const TRIAL_OUTCOMES: Record<+ AdminTrialOutcome,+ { label: string; colour: 'green' | 'red' | 'yellow' | 'sky' | 'slate' }+> = {+ trialing: { label: 'trialing', colour: 'sky' },+ converted: { label: 'converted', colour: 'green' },+ cancelling: { label: 'cancelled', colour: 'yellow' },+ expired: { label: 'did not convert', colour: 'red' },+ payment_issue: { label: 'payment issue', colour: 'red' },+}++const OutcomeBadge = ({ outcome }: { outcome: AdminTrialOutcome }) => {+ const config = TRIAL_OUTCOMES[outcome] || TRIAL_OUTCOMES.trialing++ return <Badge colour={config.colour} label={config.label} size='sm' />+}++// Shared bar row for the MRR breakdowns+const MixRow = ({+ label,+ amount,+ accounts,+ share,+}: {+ label: string+ amount: number+ accounts: number+ share: number+}) => (+ <div className='flex items-center gap-3'>+ <Text as='span' size='sm' className='w-20 shrink-0' truncate>+ {label}+ </Text>+ <div className='h-4 flex-1 overflow-hidden rounded-sm bg-gray-200 dark:bg-slate-800'>+ <div+ className='h-full rounded-sm bg-indigo-500'+ style={{ width: `${share}%` }}+ />+ </div>+ <Text+ as='span'+ size='sm'+ colour='secondary'+ className='w-28 shrink-0 text-right tabular-nums'+ >+ ${nLocaleFormatter(Math.round(amount))}/mo · {accounts}+ </Text>+ </div>+)++const RevenueMix = ({ mrr }: { mrr: AdminBillingMrr }) => {+ const maxGroup = Math.max(+ ...mrr.byPlanType.map(({ usd }) => usd),+ ...mrr.byFrequency.map(({ usd }) => usd),+ 1,+ )++ return (+ <div className='grid grid-cols-1 gap-6 lg:grid-cols-2'>+ <div className='rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>+ <Text as='h3' size='lg' weight='semibold'>+ Where the MRR comes from+ </Text>+ <Text as='p' size='sm' colour='secondary' className='mt-0.5'>+ USD list price per account, trials excluded. Yearly plans counted at a+ twelfth of their price.+ </Text>+ {[+ { title: 'By plan', groups: mrr.byPlanType },+ { title: 'By billing', groups: mrr.byFrequency },+ ].map(({ title, groups }) => (+ <div key={title} className='mt-4 flex flex-col gap-2'>+ <Text as='p' size='xs' colour='secondary' className='uppercase'>+ {title}+ </Text>+ {groups.map(({ key, accounts, usd }) => (+ <MixRow+ key={key}+ label={key}+ amount={usd}+ accounts={accounts}+ share={(usd / maxGroup) * 100}+ />+ ))}+ </div>+ ))}+ {mrr.unpricedSubscriptions > 0 ? (+ <Text as='p' size='xs' colour='secondary' className='mt-3'>+ {mrr.unpricedSubscriptions} subscription+ {mrr.unpricedSubscriptions === 1 ? '' : 's'} on a plan with no list+ price (legacy or custom) are not counted.+ </Text>+ ) : null}+ </div>++ <div className='rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>+ <Text as='h3' size='lg' weight='semibold'>+ Biggest accounts+ </Text>+ <Text as='p' size='sm' colour='secondary' className='mt-0.5'>+ {mrr.topAccountsPercent}% of the MRR sits with these{' '}+ {mrr.topAccounts.length} accounts.+ </Text>+ <div className='mt-4 flex flex-col gap-2'>+ {mrr.topAccounts.length === 0 ? (+ <Text as='p' size='sm' colour='secondary'>+ No priced subscriptions yet.+ </Text>+ ) : (+ mrr.topAccounts.map((account) => (+ <div+ key={account.id}+ className='flex items-center justify-between gap-3'+ >+ <span className='min-w-0 truncate'>+ <UserLink user={account} />+ <span className='ml-2 text-xs text-gray-500 dark:text-gray-400'>+ {account.planCode}+ </span>+ </span>+ <Text+ as='span'+ size='sm'+ weight='medium'+ className='shrink-0 tabular-nums'+ >+ ${nLocaleFormatter(Math.round(account.usd))}/mo+ </Text>+ </div>+ ))+ )}+ </div>+ </div>+ </div>+ )+}+const Section = ({title,hint,@@ -167,11 +314,21 @@ const PaymentsTable = ({interface BillingTabProps {billing: AdminBilling+ revenueTrends: AdminRevenueTrends | null | undefined+ trendMonths: number+ onTrendMonthsChange: (months: number) => void}-export const BillingTab = ({ billing }: BillingTabProps) => {+export const BillingTab = ({+ billing,+ revenueTrends,+ trendMonths,+ onTrendMonthsChange,+}: BillingTabProps) => {const {trialsEndingSoon,+ trialStats,+ mrr,cancellationPipeline,suspended,churnRisk,@@ -190,40 +347,54 @@ export const BillingTab = ({ billing }: BillingTabProps) => {return (<div className='flex flex-col gap-8'>+ <RevenueTrends+ trends={revenueTrends}+ months={trendMonths}+ onMonthsChange={onTrendMonthsChange}+ />++ <RevenueMix mrr={mrr} />+<div className='grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4'><StatCard- label='Trials ending (±14d)'- value={trialsEndingSoon.length}- hint='Expiring within 14 days or expired within 30'+ label='Trials running'+ value={trialStats.activeNow}+ hint={`Worth $${nLocaleFormatter(Math.round(mrr.trialUsd))}/mo if they all convert`}+ />+ <StatCard+ label={`Trial conversion (${trialStats.windowDays}d)`}+ value={+ trialStats.conversionRate === null+ ? '—'+ : `${trialStats.conversionRate}%`+ }+ hint={`${trialStats.converted} of ${trialStats.resolved} finished trials converted`}/><StatCardlabel='Churn risk'value={churnRisk.atRisk.length}hint={`Usage dropped ≥50% · ${churnRisk.analyzed} paying accounts analyzed`}/>- <StatCard- label='Cancelling'- value={cancellationPipeline.length}- hint='Subscriptions with a cancellation date'- /><StatCardlabel='At-risk MRR (est.)'value={`$${nLocaleFormatter(Math.round(atRiskMrr))}`}- hint='Churn-risk + cancelling accounts, USD list price'+ hint={`Churn-risk + ${cancellationPipeline.length} cancelling account${cancellationPipeline.length === 1 ? '' : 's'}, USD list price`}/></div><Section- title='Trials ending soon'- hint='Sorted by trial end date. High usage + imminent expiry = worth a personal email.'+ title='Trials'+ hint={`Ending within 14 days or ended in the last 30. High usage + imminent expiry = worth a personal email.`}>{trialsEndingSoon.length === 0 ? (- <EmptyState message='No trials ending in the next 14 days' />+ <EmptyState message='No trials ending or recently ended' />) : (<AdminTablecolumns={[{ key: 'email', label: 'User' },+ { key: 'outcome', label: 'Status' },{ key: 'trialEnd', label: 'Trial ends' },+ { key: 'plan', label: 'Plan' },{ key: 'monthlyEvents', label: 'Events this month' },{ key: 'projects', label: 'Projects' },{ key: 'registered', label: 'Registered' },@@ -234,9 +405,15 @@ export const BillingTab = ({ billing }: BillingTabProps) => {<Td><UserLink user={user} /></Td>+ <Td>+ <OutcomeBadge outcome={user.outcome} />+ </Td><Td><DeadlineBadge date={user.trialEndDate} /></Td>+ <Td>+ <PlanCell user={user} />+ </Td><Td className='tabular-nums'><spanclassName={diff --git a/web/app/pages/Admin/RevenueTrends.tsx b/web/app/pages/Admin/RevenueTrends.tsxnew file mode 100644index 000000000..1aeea3916--- /dev/null+++ b/web/app/pages/Admin/RevenueTrends.tsx@@ -0,0 +1,270 @@+import dayjs from 'dayjs'++import { Badge } from '~/ui/Badge'+import Select from '~/ui/Select'+import { Text } from '~/ui/Text'+import { cn, nFormatter, nLocaleFormatter } from '~/utils/generic'++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]++const usd = (amount: number): string =>+ `$${nLocaleFormatter(Math.round(amount))}`++// One decimal keeps neighbouring axis ticks distinct ($1.2k, $1.4k) instead of+// rounding a whole cluster of them to the same "$1k"+const shortUsd = (amount: number): string =>+ amount < 1000 ? `$${Math.round(amount)}` : `$${nFormatter(amount, 1)}`++const monthLabel = (month: string): string =>+ dayjs(`${month}-01`).format('MMM YYYY')++const CHART_FORMAT = {+ xTick: '%b %Y',+ xTooltip: '%B %Y',+ value: usd,+ axis: shortUsd,+}++// Percentage moves are the point of this whole panel, so they get their own+// colour treatment rather than the generic ChangeBadge+const PercentBadge = ({+ percent,+ size = 'md',+}: {+ percent: number | null | undefined+ size?: 'sm' | 'md'+}) => {+ if (percent === null || percent === undefined || Number.isNaN(percent)) {+ return <span className='text-gray-400 dark:text-gray-500'>—</span>+ }++ if (percent === 0) {+ return <Badge colour='slate' label='±0%' size={size} />+ }++ return (+ <Badge+ colour={percent > 0 ? 'green' : 'red'}+ label={`${percent > 0 ? '+' : ''}${percent}%`}+ size={size}+ />+ )+}++const describeStreak = (streak: number): string => {+ if (streak === 0) {+ return 'flat vs the month before'+ }++ const months = Math.abs(streak)+ const noun = months === 1 ? 'month' : 'months'++ return streak > 0+ ? `${months} ${noun} of growth in a row`+ : `${months} ${noun} of decline in a row`+}++interface RevenueTrendsProps {+ trends: AdminRevenueTrends | null | undefined+ months: number+ onMonthsChange: (months: number) => void+}++export const RevenueTrends = ({+ trends,+ months,+ onMonthsChange,+}: RevenueTrendsProps) => {+ if (!trends?.available || !trends.months?.length || !trends.summary) {+ return (+ <section>+ <Text as='h3' size='lg' weight='semibold'>+ Revenue trend+ </Text>+ <div className='mt-3'>+ <EmptyState message='Paddle payment history unavailable' />+ </div>+ </section>+ )+ }++ const { summary, currentMonth } = trends+ const rows = trends.months+ const rowsDesc = [...rows].reverse()++ const paceVsLastMonth =+ currentMonth && rows.length > 0+ ? currentMonth.projectedUsd - rows[rows.length - 1].cashUsd+ : null++ return (+ <div className='flex flex-col gap-6'>+ <div className='grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4'>+ <StatCard+ label={`Recurring revenue (${summary.lastCompleteMonth ? monthLabel(summary.lastCompleteMonth) : '—'})`}+ value={usd(summary.recognisedUsd)}+ badge={<PercentBadge percent={summary.momPercent} />}+ hint={`${describeStreak(summary.streak)} · ${usd(summary.runRateUsd)} annual run rate`}+ />+ <StatCard+ label='Avg. MoM growth (3 mo)'+ value={+ summary.avgMomPercent === null+ ? '—'+ : `${summary.avgMomPercent > 0 ? '+' : ''}${summary.avgMomPercent}%`+ }+ hint={`Cash last month moved ${summary.cashMomPercent === null ? '—' : `${summary.cashMomPercent > 0 ? '+' : ''}${summary.cashMomPercent}%`}`}+ />+ <StatCard+ label='Cash collected (12 mo)'+ value={usd(summary.ttmCashUsd)}+ hint={+ summary.bestMonth+ ? `Best month: ${monthLabel(summary.bestMonth.month)} at ${usd(summary.bestMonth.cashUsd)}`+ : undefined+ }+ />+ <StatCard+ label={`This month so far (${currentMonth ? monthLabel(currentMonth.month) : '—'})`}+ value={currentMonth ? usd(currentMonth.cashUsd) : '—'}+ badge={+ paceVsLastMonth === null ? null : (+ <Badge+ colour={paceVsLastMonth >= 0 ? 'green' : 'yellow'}+ label={`on pace for ${usd(currentMonth!.projectedUsd)}`}+ />+ )+ }+ hint={+ currentMonth+ ? `Day ${currentMonth.dayOfMonth} of ${currentMonth.daysInMonth} · ${currentMonth.payments} payments from ${currentMonth.payers} accounts`+ : undefined+ }+ />+ </div>++ <div className='relative rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>+ <div className='mb-1 flex items-start justify-between gap-3'>+ <div>+ <Text as='h3' size='lg' weight='semibold'>+ Revenue trend+ </Text>+ <Text as='p' size='sm' colour='secondary' className='mt-0.5'>+ Complete months only. Yearly payments are spread across the twelve+ months they buy, so the recurring line is not distorted by renewal+ spikes.+ </Text>+ </div>+ <Select<number>+ label='Period'+ fieldLabelClassName='sr-only'+ title={`Last ${months} months`}+ items={TREND_MONTHS_OPTIONS}+ labelExtractor={(value) => `Last ${value} months`}+ keyExtractor={(value) => value.toString()}+ selectedItem={months}+ onSelect={onMonthsChange}+ menuClassName='right-0 w-max min-w-full'+ />+ </div>+ <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,+ })),+ },+ ]}+ />+ </div>++ <MonthTable rows={rowsDesc} />+ </div>+ )+}++const MonthTable = ({ rows }: { rows: AdminRevenueTrendMonth[] }) => (+ <AdminTable+ columns={[+ { key: 'month', label: 'Month' },+ { key: 'recognised', label: 'Recurring' },+ { key: 'mom', label: 'MoM' },+ { key: 'cash', label: 'Cash in' },+ { key: 'subs', label: 'Subscriptions' },+ { key: 'movement', label: 'New / churned' },+ { key: 'oneOff', label: 'One-off' },+ ]}+ >+ {rows.map((row, index) => {+ // `rows` is newest first, so the previous month is the next entry+ const previous = rows[index + 1]+ const momPercent =+ previous && previous.recognisedUsd > 0+ ? Math.round(+ ((row.recognisedUsd - previous.recognisedUsd) /+ previous.recognisedUsd) *+ 1000,+ ) / 10+ : null++ return (+ <tr key={row.month}>+ <Td className='font-medium'>{monthLabel(row.month)}</Td>+ <Td className='tabular-nums'>{usd(row.recognisedUsd)}</Td>+ <Td>+ <PercentBadge percent={momPercent} size='sm' />+ </Td>+ <Td className='tabular-nums'>{usd(row.cashUsd)}</Td>+ <Td className='tabular-nums'>{nLocaleFormatter(row.activeSubs)}</Td>+ <Td className='tabular-nums'>+ <span className='inline-flex items-center gap-1.5'>+ <span+ className={cn(+ row.newSubs > 0+ ? 'text-emerald-600 dark:text-emerald-400'+ : 'text-gray-400 dark:text-gray-500',+ )}+ >+ +{row.newSubs}+ </span>+ <span className='text-gray-300 dark:text-gray-600'>/</span>+ <span+ className={cn(+ row.churnedSubs > 0+ ? 'text-red-600 dark:text-red-400'+ : 'text-gray-400 dark:text-gray-500',+ )}+ >+ −{row.churnedSubs}+ </span>+ </span>+ </Td>+ <Td className='text-gray-500 tabular-nums dark:text-gray-400'>+ {row.oneOffUsd > 0 ? usd(row.oneOffUsd) : '—'}+ </Td>+ </tr>+ )+ })}+ </AdminTable>+)diff --git a/web/app/pages/Admin/index.tsx b/web/app/pages/Admin/index.tsxindex 7d5534cbe..0ecd50440 100644--- a/web/app/pages/Admin/index.tsx+++ b/web/app/pages/Admin/index.tsx@@ -267,7 +267,14 @@ const AdminPage = () => {) : null}{activeTab === 'billing' && data.billing ? (- <BillingTab billing={data.billing} />+ <BillingTab+ billing={data.billing}+ revenueTrends={data.revenueTrends}+ trendMonths={data.trendMonths || 12}+ onTrendMonthsChange={(months) =>+ updateParams({ months: months.toString() })+ }+ />) : null}{activeTab === 'bot-blocks' && data.botBlocks ? (diff --git a/web/app/pages/Admin/types.ts b/web/app/pages/Admin/types.tsindex 25039e927..d8219d26e 100644--- a/web/app/pages/Admin/types.ts+++ b/web/app/pages/Admin/types.ts@@ -34,11 +34,48 @@ export interface AdminPayment {user: { id: string; email: string; planCode: string } | null}+export type AdminTrialOutcome =+ | 'trialing'+ | 'converted'+ | 'cancelling'+ | 'expired'+ | 'payment_issue'++interface AdminMrrGroup {+ key: string+ accounts: number+ usd: number+}++export interface AdminBillingMrr {+ usd: number+ payingAccounts: number+ arpuUsd: number+ trialingAccounts: number+ trialUsd: number+ unpricedSubscriptions: number+ byPlanType: AdminMrrGroup[]+ byFrequency: AdminMrrGroup[]+ topAccounts: { id: string; email: string; planCode: string; usd: number }[]+ topAccountsPercent: number+}+export interface AdminBilling {trialsEndingSoon: (AdminBillingUser & {projectCount: numbermonthlyEvents: number+ outcome: AdminTrialOutcome})[]+ trialStats: {+ windowDays: number+ activeNow: number+ resolved: number+ converted: number+ conversionRate: number | null+ cancelledDuringTrial: number+ paymentIssues: number+ }+ mrr: AdminBillingMrrcancellationPipeline: AdminBillingUser[]suspended: AdminBillingUser[]churnRisk: {@@ -57,6 +94,46 @@ export interface AdminBilling {}}+export interface AdminRevenueTrendMonth {+ month: string+ cashUsd: number+ recognisedUsd: number+ oneOffUsd: number+ byCurrency: Record<string, number>+ payments: number+ payers: number+ activeSubs: number+ newSubs: number+ churnedSubs: number+}++export interface AdminRevenueTrends {+ available: boolean+ months?: AdminRevenueTrendMonth[]+ currentMonth?: {+ month: string+ cashUsd: number+ payments: number+ payers: number+ dayOfMonth: number+ daysInMonth: number+ projectedUsd: number+ }+ summary?: {+ lastCompleteMonth: string | null+ recognisedUsd: number+ momPercent: number | null+ cashMomPercent: number | null+ avgMomPercent: number | null+ ttmCashUsd: number+ runRateUsd: number+ netNewSubs: number+ streak: number+ bestMonth: { month: string; cashUsd: number } | null+ }+ fetchedAt?: string+}+export interface AdminBotBlocks {days: numbertotals: { total: number; last24h: number }@@ -138,6 +215,8 @@ export interface AdminOverview {byCurrency: { USD: number; EUR: number; GBP: number }usdEquivalent: numberpayingUsers: number+ trialingUsers: number+ trialUsdEquivalent: numberunpricedSubscriptions: number}planDistribution: { planCode: string; count: number }[]@@ -385,6 +464,8 @@ export interface AdminLoaderData {organisationDetails?: AdminOrganisationDetails | nullfeedback?: AdminFeedbackListbilling?: AdminBilling+ revenueTrends?: AdminRevenueTrends | null+ trendMonths?: numberbotBlocks?: AdminBotBlocksdatabase?: AdminDatabaseInfo}diff --git a/web/app/routes/admin.tsx b/web/app/routes/admin.tsxindex acdda5a71..3b606808e 100644--- a/web/app/routes/admin.tsx+++ b/web/app/routes/admin.tsx@@ -30,6 +30,7 @@ import type {AdminProjectDetails,AdminProjectsList,AdminRevenue,+ AdminRevenueTrends,AdminTab,AdminTopProjects,AdminUserDetails,@@ -74,6 +75,7 @@ const TABS: AdminTab[] = []const CHART_DAYS = [30, 90, 180, 365]+const TREND_MONTHS = [6, 12, 24]const notFound = () => new Response('Not Found', { status: 404 })@@ -146,9 +148,22 @@ export async function loader({ request }: LoaderFunctionArgs) {}if (tab === 'billing') {- const billing = await adminFetch<AdminBilling>('admin/billing')+ const trendMonths = TREND_MONTHS.includes(+ Number(searchParams.get('months')),+ )+ ? Number(searchParams.get('months'))+ : 12++ const [billing, revenueTrends] = await Promise.all([+ adminFetch<AdminBilling>('admin/billing'),+ // A cold Paddle history fetch is slow - the rest of the tab should not+ // wait on it, nor disappear if Paddle is down+ adminFetch<AdminRevenueTrends>(+ `admin/revenue-trends?months=${trendMonths}`,+ ).catch(() => null),+ ])- return { tab, billing }+ return { tab, billing, revenueTrends, trendMonths }}if (tab === 'bot-blocks') {