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!

Display user feedback in the admin panel & other minor improvements

Blue Mouse5c95971eca5f
diff --git a/backend/apps/cloud/src/admin/admin.controller.ts b/backend/apps/cloud/src/admin/admin.controller.ts
index c9a38dc0b..9ca7bffa5 100644
--- a/backend/apps/cloud/src/admin/admin.controller.ts
+++ b/backend/apps/cloud/src/admin/admin.controller.ts
@@ -10,7 +10,12 @@ import {
import { ApiExcludeController } from '@nestjs/swagger'
import { PlanType } from '../user/entities/user.entity'
-import { AdminService, ProjectsFilter, UsersFilter } from './admin.service'
+import {
+ AdminService,
+ FeedbackType,
+ ProjectsFilter,
+ UsersFilter,
+} from './admin.service'
import { AdminAuth } from './decorators/admin-auth.decorator'
const USERS_FILTERS: UsersFilter[] = [
@@ -102,6 +107,21 @@ export class AdminController {
return this.adminService.getOverview()
}
+ @Get('revenue')
+ async getRevenue() {
+ return this.adminService.getRevenue()
+ }
+
+ @Get('billing')
+ async getBilling() {
+ return this.adminService.getBilling()
+ }
+
+ @Get('bot-blocks')
+ async getBotBlocks(@Query('days') days?: string) {
+ return this.adminService.getBotBlocks(parseDays(days, [7, 30, 90], 7))
+ }
+
@Get('charts')
async getCharts(@Query('days') days?: string) {
return this.adminService.getCharts(parseDays(days, CHART_DAYS, 30))
@@ -197,14 +217,47 @@ export class AdminController {
)
}
+ @Get('projects/:id')
+ async getProjectDetails(@Param('id') id: string) {
+ return this.adminService.getProjectDetails(id)
+ }
+
@Get('organisations')
async getOrganisations(
@Query('page') page?: string,
@Query('search') search?: string,
+ @Query('sortBy') sortBy?: string,
+ @Query('order') order?: string,
) {
return this.adminService.getOrganisations(
parsePage(page),
parseSearch(search),
+ parseOneOf(sortBy, ['created', 'name'] as const, 'created'),
+ parseOneOf(order, ['ASC', 'DESC'] as const, 'DESC'),
+ )
+ }
+
+ @Get('organisations/:id')
+ async getOrganisationDetails(@Param('id') id: string) {
+ return this.adminService.getOrganisationDetails(id)
+ }
+
+ @Get('feedback')
+ async getFeedback(
+ @Query('type') type?: string,
+ @Query('page') page?: string,
+ @Query('search') search?: string,
+ @Query('order') order?: string,
+ ) {
+ return this.adminService.getFeedback(
+ parseOneOf(
+ type,
+ ['user', 'cancellation', 'deletion'] as FeedbackType[],
+ 'user',
+ ),
+ parsePage(page),
+ parseSearch(search),
+ parseOneOf(order, ['ASC', 'DESC'] as const, 'DESC'),
)
}
diff --git a/backend/apps/cloud/src/admin/admin.module.ts b/backend/apps/cloud/src/admin/admin.module.ts
index 62a249eb8..a80efaa6d 100644
--- a/backend/apps/cloud/src/admin/admin.module.ts
+++ b/backend/apps/cloud/src/admin/admin.module.ts
@@ -4,13 +4,24 @@ import { TypeOrmModule } from '@nestjs/typeorm'
import { Organisation } from '../organisation/entity/organisation.entity'
import { OrganisationMember } from '../organisation/entity/organisation-member.entity'
import { Project } from '../project/entity/project.entity'
+import { CancellationFeedback } from '../user/entities/cancellation-feedback.entity'
+import { DeleteFeedback } from '../user/entities/delete-feedback.entity'
import { User } from '../user/entities/user.entity'
+import { UserFeedback } from '../user/entities/user-feedback.entity'
import { AdminController } from './admin.controller'
import { AdminService } from './admin.service'
@Module({
imports: [
- TypeOrmModule.forFeature([User, Project, Organisation, OrganisationMember]),
+ TypeOrmModule.forFeature([
+ User,
+ Project,
+ Organisation,
+ OrganisationMember,
+ UserFeedback,
+ DeleteFeedback,
+ CancellationFeedback,
+ ]),
],
controllers: [AdminController],
providers: [AdminService],
diff --git a/backend/apps/cloud/src/admin/admin.service.ts b/backend/apps/cloud/src/admin/admin.service.ts
index 56045d383..ea03a44c7 100644
--- a/backend/apps/cloud/src/admin/admin.service.ts
+++ b/backend/apps/cloud/src/admin/admin.service.ts
@@ -1,7 +1,8 @@
import { Injectable, NotFoundException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
-import { In, IsNull, Not, Repository } from 'typeorm'
+import { In, IsNull, MoreThanOrEqual, Not, Repository } from 'typeorm'
+import { redis } from '../common/constants'
import { clickhouse } from '../common/integrations/clickhouse'
import { Organisation } from '../organisation/entity/organisation.entity'
import {
@@ -9,6 +10,8 @@ import {
OrganisationRole,
} from '../organisation/entity/organisation-member.entity'
import { Project } from '../project/entity/project.entity'
+import { CancellationFeedback } from '../user/entities/cancellation-feedback.entity'
+import { DeleteFeedback } from '../user/entities/delete-feedback.entity'
import {
ACCOUNT_PLANS,
BillingFrequency,
@@ -18,6 +21,7 @@ import {
PlanType,
User,
} from '../user/entities/user.entity'
+import { UserFeedback } from '../user/entities/user-feedback.entity'
// Event types that count towards project activity (parity with the analytics views)
const ACTIVITY_EVENT_TYPES = [
@@ -39,6 +43,9 @@ const FREE_PLAN_CODES = [PlanCode.none, PlanCode.free, PlanCode.trial]
const USERS_PAGE_SIZE = 25
const PROJECTS_PAGE_SIZE = 25
const ORGANISATIONS_PAGE_SIZE = 25
+const FEEDBACK_PAGE_SIZE = 20
+
+export type FeedbackType = 'user' | 'cancellation' | 'deletion'
interface CurrencyAmounts {
USD: number
@@ -168,6 +175,42 @@ const PLUS_PLAN_PRICES: Partial<Record<PlanCode, PlanPricing>> = {
type SupportedCurrency = keyof CurrencyAmounts
+const { PADDLE_VENDOR_ID, PADDLE_API_KEY } = process.env
+
+// v2: stores raw payments instead of derived summaries
+const REVENUE_CACHE_KEY = 'admin:paddle-payments:v2'
+// Paddle's vendor API is rate limited; the numbers do not move fast anyway
+const REVENUE_CACHE_TTL_SECONDS = 3600
+
+// Rough, static FX rates used only to produce a single comparable USD number
+const APPROX_USD_RATES: Record<string, number> = {
+ USD: 1,
+ EUR: 1.08,
+ GBP: 1.27,
+}
+
+interface PaddlePayment {
+ id: number
+ subscription_id: number
+ amount: number
+ currency: string
+ payout_date: string
+ is_paid: number
+ is_one_off_charge: boolean | number
+ receipt_url?: string
+}
+
+const CHURN_RISK_MIN_PREV_EVENTS = 100
+const CHURN_RISK_MIN_DROP = 0.5
+
+export interface RevenueBucket {
+ byCurrency: Record<string, number>
+ approxUsd: number
+ payments: number
+ oneOffPayments: number
+ payers: number
+}
+
interface MrrSubscription {
planCode: PlanCode
planType: PlanType | null
@@ -206,6 +249,12 @@ export class AdminService {
private readonly organisationRepository: Repository<Organisation>,
@InjectRepository(OrganisationMember)
private readonly organisationMemberRepository: Repository<OrganisationMember>,
+ @InjectRepository(UserFeedback)
+ private readonly userFeedbackRepository: Repository<UserFeedback>,
+ @InjectRepository(DeleteFeedback)
+ private readonly deleteFeedbackRepository: Repository<DeleteFeedback>,
+ @InjectRepository(CancellationFeedback)
+ private readonly cancellationFeedbackRepository: Repository<CancellationFeedback>,
) {}
// -------------------- MRR --------------------
@@ -288,6 +337,592 @@ export class AdminService {
}
}
+ // -------------------- Revenue (Paddle) --------------------
+
+ private async fetchPaddlePayments(
+ from: string,
+ to: string,
+ isPaid: 0 | 1,
+ ): Promise<PaddlePayment[]> {
+ const body = new URLSearchParams()
+ body.set('vendor_id', String(Number(PADDLE_VENDOR_ID)))
+ body.set('vendor_auth_code', PADDLE_API_KEY)
+ body.set('is_paid', String(isPaid))
+ body.set('from', from)
+ body.set('to', to)
+
+ const res = await fetch(
+ 'https://vendors.paddle.com/api/2.0/subscription/payments',
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body,
+ },
+ )
+
+ const data = await res.json()
+
+ if (!res.ok || !data?.success) {
+ throw new Error(
+ `Paddle payments request failed: ${JSON.stringify(data?.error || data)}`,
+ )
+ }
+
+ return data.response || []
+ }
+
+ private summariseRevenue(payments: PaddlePayment[]): RevenueBucket {
+ const byCurrency: Record<string, number> = {}
+ const payerIds = new Set<number>()
+ let approxUsd = 0
+ let oneOffPayments = 0
+
+ for (const payment of payments) {
+ const amount = Number(payment.amount) || 0
+ const currency = payment.currency || 'USD'
+
+ byCurrency[currency] = (byCurrency[currency] || 0) + amount
+ approxUsd += amount * (APPROX_USD_RATES[currency] ?? 1)
+ payerIds.add(payment.subscription_id)
+
+ if (payment.is_one_off_charge) {
+ oneOffPayments += 1
+ }
+ }
+
+ for (const currency of Object.keys(byCurrency)) {
+ byCurrency[currency] = Math.round(byCurrency[currency] * 100) / 100
+ }
+
+ return {
+ byCurrency,
+ approxUsd: Math.round(approxUsd * 100) / 100,
+ payments: payments.length,
+ oneOffPayments,
+ payers: payerIds.size,
+ }
+ }
+
+ // Raw payments shared by the revenue summary and the billing payments feed.
+ // Cached in redis because the vendor API is slow and rate limited; the
+ // summaries are derived from this cache instead of being cached themselves.
+ private async getCachedPaddlePayments(): Promise<{
+ paid: PaddlePayment[]
+ upcoming: PaddlePayment[]
+ fetchedAt: string
+ } | null> {
+ const cached = await redis.get(REVENUE_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
+ }
+
+ 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),
+ )
+ const upcomingUntil = new Date(now.getTime() + 45 * 24 * 60 * 60 * 1000)
+
+ let result
+
+ try {
+ const [paid, upcoming] = await Promise.all([
+ this.fetchPaddlePayments(
+ toDateString(previousMonthStart),
+ toDateString(now),
+ 1,
+ ),
+ this.fetchPaddlePayments(
+ toDateString(now),
+ toDateString(upcomingUntil),
+ 0,
+ ),
+ ])
+
+ result = { paid, upcoming, fetchedAt: now.toISOString() }
+ } catch (error) {
+ console.error('[ERROR] (admin getCachedPaddlePayments):', error)
+ return null
+ }
+
+ await redis
+ .set(
+ REVENUE_CACHE_KEY,
+ JSON.stringify(result),
+ 'EX',
+ REVENUE_CACHE_TTL_SECONDS,
+ )
+ .catch(() => null)
+
+ return result
+ }
+
+ // Real cash-in numbers from Paddle (includes one-off charges), unlike the
+ // list-price MRR estimate
+ async getRevenue() {
+ const payments = await this.getCachedPaddlePayments()
+
+ if (!payments) {
+ return { available: false as const }
+ }
+
+ const now = new Date()
+ const dayOfMonth = now.getUTCDate()
+ const currentMonthStart = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1),
+ )
+ const currentMonthEnd = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0, 23, 59, 59),
+ )
+
+ const currentMonthPayments: PaddlePayment[] = []
+ const previousMonthPayments: PaddlePayment[] = []
+ const previousMonthToDatePayments: PaddlePayment[] = []
+
+ for (const payment of payments.paid) {
+ const payoutDate = new Date(payment.payout_date)
+
+ if (payoutDate >= currentMonthStart) {
+ currentMonthPayments.push(payment)
+ } else {
+ previousMonthPayments.push(payment)
+
+ // Same day-of-month window as the current month, so the MoM badge
+ // compares like for like instead of MTD vs a full month
+ if (payoutDate.getUTCDate() <= dayOfMonth) {
+ previousMonthToDatePayments.push(payment)
+ }
+ }
+ }
+
+ // "Scheduled" on the revenue card means the rest of this month only
+ const upcomingThisMonth = payments.upcoming.filter(
+ (payment) => new Date(payment.payout_date) <= currentMonthEnd,
+ )
+
+ return {
+ available: true as const,
+ currentMonth: this.summariseRevenue(currentMonthPayments),
+ previousMonth: this.summariseRevenue(previousMonthPayments),
+ previousMonthToDate: this.summariseRevenue(previousMonthToDatePayments),
+ upcoming: this.summariseRevenue(upcomingThisMonth),
+ fetchedAt: payments.fetchedAt,
+ }
+ }
+
+ // -------------------- Billing health --------------------
+
+ private formatBillingUser(user: User) {
+ const revenue = this.getMonthlyRevenue(user)
+
+ return {
+ id: user.id,
+ email: user.email,
+ planCode: user.planCode,
+ planType: getEffectivePlanType(user),
+ billingFrequency: user.billingFrequency,
+ created: user.created,
+ trialEndDate: user.trialEndDate,
+ nextBillDate: user.nextBillDate,
+ cancellationEffectiveDate: user.cancellationEffectiveDate,
+ dashboardBlockReason: user.dashboardBlockReason,
+ isAccountBillingSuspended: user.isAccountBillingSuspended,
+ // USD list-price estimate of what this account is worth per month
+ monthlyRevenueUsd: revenue
+ ? Math.round(revenue.usdAmount * 100) / 100
+ : null,
+ }
+ }
+
+ 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 [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 [trialUsage, churnRisk, payments] = await Promise.all([
+ this.getMonthlyEventsForUsers(trialUsers.map((user) => user.id)),
+ this.getChurnRisk(payingUsers),
+ this.buildPaymentsFeed(paddle),
+ ])
+
+ return {
+ trialsEndingSoon: trialUsers.map(
+ (user: User & { projectCount?: number }) => ({
+ ...this.formatBillingUser(user),
+ projectCount: user.projectCount || 0,
+ monthlyEvents: trialUsage[user.id] || 0,
+ }),
+ ),
+ cancellationPipeline: cancellingUsers.map((user) =>
+ this.formatBillingUser(user),
+ ),
+ suspended: suspendedUsers.map((user) => this.formatBillingUser(user)),
+ churnRisk,
+ payments,
+ }
+ }
+
+ private async buildPaymentsFeed(
+ paddle: {
+ paid: PaddlePayment[]
+ upcoming: PaddlePayment[]
+ fetchedAt: string
+ } | null,
+ ) {
+ if (!paddle) {
+ return { available: false as const, recent: [], upcoming: [] }
+ }
+
+ const recent = [...paddle.paid]
+ .sort(
+ (a, b) =>
+ new Date(b.payout_date).getTime() - new Date(a.payout_date).getTime(),
+ )
+ .slice(0, 50)
+ const upcoming = [...paddle.upcoming]
+ .sort(
+ (a, b) =>
+ new Date(a.payout_date).getTime() - new Date(b.payout_date).getTime(),
+ )
+ .slice(0, 50)
+
+ // Paddle only knows subscription ids - map them back to accounts
+ const subIds = Array.from(
+ new Set(
+ [...recent, ...upcoming].map(({ subscription_id }) =>
+ String(subscription_id),
+ ),
+ ),
+ )
+ const users =
+ subIds.length > 0
+ ? await this.userRepository.find({
+ where: { subID: In(subIds) },
+ select: ['id', 'email', 'subID', 'planCode'],
+ })
+ : []
+ const usersBySubId = Object.fromEntries(
+ users.map((user) => [user.subID, user]),
+ )
+
+ const mapPayment = (payment: PaddlePayment) => {
+ const user = usersBySubId[String(payment.subscription_id)]
+
+ return {
+ id: payment.id,
+ date: payment.payout_date,
+ amount: Number(payment.amount) || 0,
+ currency: payment.currency,
+ isOneOff: Boolean(payment.is_one_off_charge),
+ receiptUrl: payment.receipt_url || null,
+ subscriptionId: payment.subscription_id,
+ user: user
+ ? { id: user.id, email: user.email, planCode: user.planCode }
+ : null,
+ }
+ }
+
+ return {
+ available: true as const,
+ recent: recent.map(mapPayment),
+ upcoming: upcoming.map(mapPayment),
+ fetchedAt: paddle.fetchedAt,
+ }
+ }
+
+ // Paying users whose usage collapsed vs the previous month - the churn
+ // early-warning list
+ private async getChurnRisk(payingUsers: User[]) {
+ if (payingUsers.length === 0) {
+ return { atRisk: [], analyzed: 0 }
+ }
+
+ const projects: { pid: string; userId: string }[] =
+ await this.projectRepository
+ .createQueryBuilder('project')
+ .select('project.id', 'pid')
+ .addSelect('admin.id', 'userId')
+ .leftJoin('project.admin', 'admin')
+ .where('admin.id IN (:...userIds)', {
+ userIds: payingUsers.map((user) => user.id),
+ })
+ .getRawMany()
+
+ if (projects.length === 0) {
+ return { atRisk: [], analyzed: payingUsers.length }
+ }
+
+ const query = `
+ SELECT
+ pid,
+ countIf(created >= now() - INTERVAL 30 DAY) AS current,
+ countIf(
+ created >= now() - INTERVAL 60 DAY
+ AND created < now() - INTERVAL 30 DAY
+ ) AS previous
+ FROM events
+ WHERE pid IN ({pids:Array(FixedString(12))})
+ AND type IN ({types:Array(String)})
+ GROUP BY pid
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: {
+ pids: projects.map(({ pid }) => pid),
+ types: ACTIVITY_EVENT_TYPES,
+ },
+ })
+ .then((resultSet) =>
+ resultSet.json<{ pid: string; current: number; previous: number }>(),
+ )
+
+ const byPid: Record<string, { current: number; previous: number }> = {}
+
+ for (const { pid, current, previous } of data) {
+ byPid[pid] = { current: Number(current), previous: Number(previous) }
+ }
+
+ const byUser: Record<string, { current: number; previous: number }> = {}
+
+ for (const { pid, userId } of projects) {
+ const counts = byPid[pid]
+
+ if (!counts) {
+ continue
+ }
+
+ byUser[userId] = byUser[userId] || { current: 0, previous: 0 }
+ byUser[userId].current += counts.current
+ byUser[userId].previous += counts.previous
+ }
+
+ const atRisk = payingUsers
+ .map((user) => {
+ const usage = byUser[user.id] || { current: 0, previous: 0 }
+ const drop =
+ usage.previous > 0
+ ? (usage.previous - usage.current) / usage.previous
+ : 0
+
+ return { user, usage, drop }
+ })
+ .filter(
+ ({ usage, drop }) =>
+ usage.previous >= CHURN_RISK_MIN_PREV_EVENTS &&
+ drop >= CHURN_RISK_MIN_DROP,
+ )
+ .sort((a, b) => b.drop - a.drop)
+ .map(({ user, usage, drop }) => ({
+ ...this.formatBillingUser(user),
+ events30d: usage.current,
+ eventsPrev30d: usage.previous,
+ dropPercent: Math.round(drop * 100),
+ }))
+
+ return { atRisk, analyzed: payingUsers.length }
+ }
+
+ // -------------------- Bot blocks --------------------
+
+ async getBotBlocks(days: number) {
+ const [seriesRaw, byProjectRaw, totalsRaw] = await Promise.all([
+ clickhouse
+ .query({
+ query: `
+ SELECT toString(toDate(created)) AS date, reason, count() AS count
+ FROM bot_blocks
+ WHERE created >= now() - INTERVAL {days:UInt16} DAY
+ GROUP BY date, reason
+ ORDER BY date ASC
+ `,
+ query_params: { days },
+ })
+ .then((resultSet) =>
+ resultSet.json<{ date: string; reason: string; count: number }>(),
+ )
+ .then(({ data }) => data),
+ clickhouse
+ .query({
+ query: `
+ SELECT pid, reason, count() AS count
+ FROM bot_blocks
+ WHERE created >= now() - INTERVAL {days:UInt16} DAY
+ GROUP BY pid, reason
+ `,
+ query_params: { days },
+ })
+ .then((resultSet) =>
+ resultSet.json<{ pid: string; reason: string; count: number }>(),
+ )
+ .then(({ data }) => data),
+ clickhouse
+ .query({
+ query: `
+ SELECT
+ count() AS total,
+ countIf(created >= now() - INTERVAL 1 DAY) AS last24h
+ FROM bot_blocks
+ WHERE created >= now() - INTERVAL {days:UInt16} DAY
+ `,
+ query_params: { days },
+ })
+ .then((resultSet) =>
+ resultSet.json<{ total: number; last24h: number }>(),
+ )
+ .then(({ data }) => data[0]),
+ ])
+
+ // Aggregate per project and per reason
+ const byPid: Record<
+ string,
+ { total: number; reasons: Record<string, number> }
+ > = {}
+ const byReason: Record<string, number> = {}
+
+ for (const { pid, reason, count } of byProjectRaw) {
+ const numeric = Number(count)
+
+ byPid[pid] = byPid[pid] || { total: 0, reasons: {} }
+ byPid[pid].total += numeric
+ byPid[pid].reasons[reason] = (byPid[pid].reasons[reason] || 0) + numeric
+ byReason[reason] = (byReason[reason] || 0) + numeric
+ }
+
+ const topPids = Object.entries(byPid)
+ .sort(([, a], [, b]) => b.total - a.total)
+ .slice(0, 30)
+ .map(([pid]) => pid)
+
+ const [acceptedByPid, projects] = await Promise.all([
+ this.getAcceptedEventCounts(topPids, days),
+ topPids.length > 0
+ ? this.projectRepository.find({
+ where: { id: In(topPids) },
+ relations: ['admin'],
+ })
+ : Promise.resolve([]),
+ ])
+
+ const projectsByPid: Record<string, Project> = {}
+
+ for (const project of projects) {
+ projectsByPid[project.id] = project
+ }
+
+ const topProjects = topPids.map((pid) => {
+ const blocked = byPid[pid].total
+ const accepted = acceptedByPid[pid] || 0
+ const project = projectsByPid[pid]
+ const topReason = Object.entries(byPid[pid].reasons).sort(
+ ([, a], [, b]) => b - a,
+ )[0]
+
+ return {
+ id: pid,
+ name: project?.name || null,
+ botsProtectionLevel: project?.botsProtectionLevel || null,
+ admin: project?.admin
+ ? { id: project.admin.id, email: project.admin.email }
+ : null,
+ blocked,
+ accepted,
+ // blocked / all incoming traffic; ~100% means the shield is eating
+ // everything the customer sends
+ blockRatio: Math.round((blocked / (blocked + accepted)) * 100),
+ topReason: topReason ? topReason[0] : null,
+ }
+ })
+
+ return {
+ days,
+ totals: {
+ total: Number(totalsRaw?.total) || 0,
+ last24h: Number(totalsRaw?.last24h) || 0,
+ },
+ byReason: Object.entries(byReason)
+ .map(([reason, count]) => ({ reason, count }))
+ .sort((a, b) => b.count - a.count),
+ series: seriesRaw.map(({ date, reason, count }) => ({
+ date,
+ reason,
+ count: Number(count),
+ })),
+ topProjects,
+ }
+ }
+
+ private async getAcceptedEventCounts(
+ pids: string[],
+ days: number,
+ ): Promise<Record<string, number>> {
+ if (pids.length === 0) {
+ return {}
+ }
+
+ const { data } = await clickhouse
+ .query({
+ query: `
+ SELECT pid, count() AS count
+ FROM events
+ WHERE pid IN ({pids:Array(FixedString(12))})
+ AND created >= now() - INTERVAL {days:UInt16} DAY
+ AND type IN ({types:Array(String)})
+ GROUP BY pid
+ `,
+ query_params: { pids, days, types: ACTIVITY_EVENT_TYPES },
+ })
+ .then((resultSet) => resultSet.json<{ pid: string; count: number }>())
+
+ return Object.fromEntries(
+ data.map(({ pid, count }) => [pid, Number(count)]),
+ )
+ }
+
// -------------------- Overview --------------------
async getOverview() {
@@ -295,6 +930,7 @@ export class AdminService {
const dayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000)
const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
const monthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)
+ const twoMonthsAgo = new Date(now.getTime() - 60 * 24 * 60 * 60 * 1000)
const [
totalUsers,
@@ -310,6 +946,7 @@ export class AdminService {
signups24h,
signups7d,
signups30d,
+ signupsPrev30d,
mrr,
] = await Promise.all([
this.userRepository.count(),
@@ -338,6 +975,7 @@ export class AdminService {
this.countUsersCreatedSince(dayAgo),
this.countUsersCreatedSince(weekAgo),
this.countUsersCreatedSince(monthAgo),
+ this.countUsersCreatedBetween(twoMonthsAgo, monthAgo),
this.calculateMrr(),
])
@@ -358,6 +996,7 @@ export class AdminService {
signups24h,
signups7d,
signups30d,
+ signupsPrev30d,
},
projects: {
total: totalProjects,
@@ -379,13 +1018,27 @@ export class AdminService {
.getCount()
}
+ private async countUsersCreatedBetween(
+ from: Date,
+ to: Date,
+ ): Promise<number> {
+ return this.userRepository
+ .createQueryBuilder('user')
+ .where('user.created >= :from AND user.created < :to', { from, to })
+ .getCount()
+ }
+
private async getEventTotals() {
const query = `
SELECT
count() AS total,
countIf(created >= now() - INTERVAL 1 DAY) AS last24h,
countIf(created >= now() - INTERVAL 7 DAY) AS last7d,
- countIf(created >= now() - INTERVAL 30 DAY) AS last30d
+ countIf(created >= now() - INTERVAL 30 DAY) AS last30d,
+ countIf(
+ created >= now() - INTERVAL 60 DAY
+ AND created < now() - INTERVAL 30 DAY
+ ) AS prev30d
FROM events
WHERE type IN ({types:Array(String)})
`
@@ -398,6 +1051,7 @@ export class AdminService {
last24h: number
last7d: number
last30d: number
+ prev30d: number
}>(),
)
@@ -407,6 +1061,7 @@ export class AdminService {
last24h: 0,
last7d: 0,
last30d: 0,
+ prev30d: 0,
}
)
}
@@ -415,15 +1070,168 @@ export class AdminService {
async getCharts(days: number) {
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000)
+ const prevSince = new Date(Date.now() - 2 * days * 24 * 60 * 60 * 1000)
- const [signups, projects, organisations, events] = await Promise.all([
+ const [
+ signups,
+ projects,
+ organisations,
+ events,
+ signupsTotals,
+ projectsTotals,
+ organisationsTotals,
+ eventsTotals,
+ funnel,
+ ] = await Promise.all([
this.getMysqlCreationSeries('user', since),
this.getMysqlCreationSeries('project', since),
this.getMysqlCreationSeries('organisation', since),
this.getEventsSeries(days),
+ this.getMysqlCreationTotals('user', since, prevSince),
+ this.getMysqlCreationTotals('project', since, prevSince),
+ this.getMysqlCreationTotals('organisation', since, prevSince),
+ this.getEventsTotalsForWindow(days),
+ this.getActivationFunnel(since),
])
- return { signups, projects, organisations, events }
+ return {
+ signups,
+ projects,
+ organisations,
+ events,
+ // Current window vs the same-length window immediately before it, for
+ // the change badges above the charts
+ totals: {
+ signups: signupsTotals,
+ projects: projectsTotals,
+ organisations: organisationsTotals,
+ events: eventsTotals,
+ },
+ funnel,
+ }
+ }
+
+ // Cohort funnel over users who signed up in the window: how far did they
+ // get towards becoming paying customers (state as of now, not as of signup)
+ private async getActivationFunnel(since: Date) {
+ const cohort = await this.userRepository.find({
+ where: { created: MoreThanOrEqual(since) },
+ select: ['id', 'isActive', 'planCode'],
+ })
+
+ if (cohort.length === 0) {
+ return {
+ signups: 0,
+ verified: 0,
+ createdProject: 0,
+ sentData: 0,
+ paid: 0,
+ }
+ }
+
+ const projects: { pid: string; userId: string }[] =
+ await this.projectRepository
+ .createQueryBuilder('project')
+ .select('project.id', 'pid')
+ .addSelect('admin.id', 'userId')
+ .leftJoin('project.admin', 'admin')
+ .where('admin.id IN (:...userIds)', {
+ userIds: cohort.map((user) => user.id),
+ })
+ .getRawMany()
+
+ const usersWithProject = new Set(projects.map(({ userId }) => userId))
+
+ let usersWithData = new Set<string>()
+
+ if (projects.length > 0) {
+ const { data } = await clickhouse
+ .query({
+ query: `
+ SELECT DISTINCT pid
+ FROM events
+ WHERE pid IN ({pids:Array(FixedString(12))})
+ AND type IN ({types:Array(String)})
+ `,
+ query_params: {
+ pids: projects.map(({ pid }) => pid),
+ types: ACTIVITY_EVENT_TYPES,
+ },
+ })
+ .then((resultSet) => resultSet.json<{ pid: string }>())
+
+ const pidsWithData = new Set(data.map(({ pid }) => pid))
+
+ usersWithData = new Set(
+ projects
+ .filter(({ pid }) => pidsWithData.has(pid))
+ .map(({ userId }) => userId),
+ )
+ }
+
+ return {
+ signups: cohort.length,
+ verified: cohort.filter((user) => user.isActive).length,
+ createdProject: usersWithProject.size,
+ sentData: usersWithData.size,
+ paid: cohort.filter((user) => !FREE_PLAN_CODES.includes(user.planCode))
+ .length,
+ }
+ }
+
+ private async getMysqlCreationTotals(
+ table: 'user' | 'project' | 'organisation',
+ since: Date,
+ prevSince: Date,
+ ): Promise<{ current: number; previous: number }> {
+ // table name comes from a hardcoded whitelist, never from user input
+ const rows: { current: string; previous: string }[] =
+ await this.userRepository.query(
+ `
+ SELECT
+ COALESCE(SUM(created >= ?), 0) AS current,
+ COALESCE(SUM(created < ?), 0) AS previous
+ FROM \`${table}\`
+ WHERE created >= ?
+ `,
+ [since, since, prevSince],
+ )
+
+ return {
+ current: Number(rows[0]?.current) || 0,
+ previous: Number(rows[0]?.previous) || 0,
+ }
+ }
+
+ private async getEventsTotalsForWindow(
+ days: number,
+ ): Promise<{ current: number; previous: number }> {
+ const query = `
+ SELECT
+ countIf(created >= now() - INTERVAL {days:UInt16} DAY) AS current,
+ countIf(created < now() - INTERVAL {days:UInt16} DAY) AS previous
+ FROM events
+ WHERE created >= now() - INTERVAL {doubleDays:UInt16} DAY
+ AND type IN ({types:Array(String)})
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: {
+ days,
+ doubleDays: days * 2,
+ types: ACTIVITY_EVENT_TYPES,
+ },
+ })
+ .then((resultSet) =>
+ resultSet.json<{ current: number; previous: number }>(),
+ )
+
+ return {
+ current: Number(data[0]?.current) || 0,
+ previous: Number(data[0]?.previous) || 0,
+ }
}
private async getMysqlCreationSeries(
@@ -952,14 +1760,109 @@ export class AdminService {
}
}
+ async getProjectDetails(id: string) {
+ const project = await this.projectRepository.findOne({
+ where: { id },
+ relations: ['admin', 'organisation', 'share', 'share.user'],
+ })
+
+ if (!project) {
+ throw new NotFoundException()
+ }
+
+ const [eventCounts, series, typeBreakdown] = await Promise.all([
+ this.getEventCountsForProjects([id]),
+ this.getProjectEventsSeries(id, 30),
+ this.getProjectEventTypeBreakdown(id),
+ ])
+
+ return {
+ project: {
+ ...this.formatProject(project, eventCounts),
+ origins: project.origins,
+ ipBlacklist: project.ipBlacklist,
+ },
+ series,
+ typeBreakdown,
+ shares: (project.share || []).map((share) => ({
+ id: share.id,
+ role: share.role,
+ confirmed: share.confirmed,
+ created: share.created,
+ user: share.user
+ ? { id: share.user.id, email: share.user.email }
+ : null,
+ })),
+ }
+ }
+
+ private async getProjectEventsSeries(
+ pid: string,
+ days: number,
+ ): Promise<{ date: string; count: number }[]> {
+ const query = `
+ SELECT
+ toString(toDate(created)) AS date,
+ count() AS count
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND created >= now() - INTERVAL {days:UInt16} DAY
+ AND type IN ({types:Array(String)})
+ GROUP BY date
+ ORDER BY date ASC
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { pid, days, types: ACTIVITY_EVENT_TYPES },
+ })
+ .then((resultSet) => resultSet.json<{ date: string; count: number }>())
+
+ return data.map(({ date, count }) => ({ date, count: Number(count) }))
+ }
+
+ private async getProjectEventTypeBreakdown(
+ pid: string,
+ ): Promise<{ type: string; last30d: number; total: number }[]> {
+ const query = `
+ SELECT
+ type,
+ countIf(created >= now() - INTERVAL 30 DAY) AS last30d,
+ count() AS total
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type IN ({types:Array(String)})
+ GROUP BY type
+ ORDER BY total DESC
+ `
+
+ const { data } = await clickhouse
+ .query({ query, query_params: { pid, types: ACTIVITY_EVENT_TYPES } })
+ .then((resultSet) =>
+ resultSet.json<{ type: string; last30d: number; total: number }>(),
+ )
+
+ return data.map(({ type, last30d, total }) => ({
+ type,
+ last30d: Number(last30d),
+ total: Number(total),
+ }))
+ }
+
// -------------------- Organisations --------------------
- async getOrganisations(page: number, search: string) {
+ async getOrganisations(
+ page: number,
+ search: string,
+ sortBy: 'created' | 'name',
+ order: 'ASC' | 'DESC',
+ ) {
let query = this.organisationRepository
.createQueryBuilder('org')
.loadRelationCountAndMap('org.memberCount', 'org.members')
.loadRelationCountAndMap('org.projectCount', 'org.projects')
- .orderBy('org.created', 'DESC')
+ .orderBy(`org.${sortBy}`, order)
.skip(page * ORGANISATIONS_PAGE_SIZE)
.take(ORGANISATIONS_PAGE_SIZE)
@@ -1014,6 +1917,245 @@ export class AdminService {
}
}
+ async getOrganisationDetails(id: string) {
+ const organisation = await this.organisationRepository.findOne({
+ where: { id },
+ relations: ['members', 'members.user', 'projects', 'projects.admin'],
+ })
+
+ if (!organisation) {
+ throw new NotFoundException()
+ }
+
+ const eventCounts = await this.getEventCountsForProjects(
+ organisation.projects.map((project) => project.id),
+ )
+
+ return {
+ organisation: {
+ id: organisation.id,
+ name: organisation.name,
+ created: organisation.created,
+ memberCount: organisation.members.length,
+ projectCount: organisation.projects.length,
+ },
+ members: organisation.members.map((member) => ({
+ id: member.id,
+ role: member.role,
+ confirmed: member.confirmed,
+ created: member.created,
+ user: member.user
+ ? { id: member.user.id, email: member.user.email }
+ : null,
+ })),
+ projects: organisation.projects.map((project) => ({
+ id: project.id,
+ name: project.name,
+ active: project.active,
+ isArchived: project.isArchived,
+ created: project.created,
+ admin: project.admin
+ ? { id: project.admin.id, email: project.admin.email }
+ : null,
+ ...(eventCounts[project.id] || {
+ events24h: 0,
+ events30d: 0,
+ totalEvents: 0,
+ }),
+ })),
+ }
+ }
+
+ // -------------------- Feedback --------------------
+
+ async getFeedback(
+ type: FeedbackType,
+ page: number,
+ search: string,
+ order: 'ASC' | 'DESC',
+ ) {
+ const [counts, list] = await Promise.all([
+ this.getFeedbackCounts(),
+ type === 'user'
+ ? this.getUserFeedbackList(page, search, order)
+ : type === 'cancellation'
+ ? this.getCancellationFeedbackList(page, search, order)
+ : this.getDeleteFeedbackList(page, search, order),
+ ])
+
+ return { ...list, counts }
+ }
+
+ private async getFeedbackCounts() {
+ const [user, cancellation, deletion] = await Promise.all([
+ this.userFeedbackRepository.count(),
+ this.cancellationFeedbackRepository.count(),
+ this.deleteFeedbackRepository.count(),
+ ])
+
+ return { user, cancellation, deletion }
+ }
+
+ private async getUsersByIds(
+ ids: string[],
+ ): Promise<Record<string, { id: string; email: string; planCode: string }>> {
+ if (ids.length === 0) {
+ return {}
+ }
+
+ const users = await this.userRepository.find({
+ where: { id: In(ids) },
+ select: ['id', 'email', 'planCode'],
+ })
+
+ return Object.fromEntries(
+ users.map((user) => [
+ user.id,
+ { id: user.id, email: user.email, planCode: user.planCode },
+ ]),
+ )
+ }
+
+ private async getUserFeedbackList(
+ page: number,
+ search: string,
+ order: 'ASC' | 'DESC',
+ ) {
+ let query = this.userFeedbackRepository
+ .createQueryBuilder('fb')
+ .orderBy('fb.createdAt', order)
+ .skip(page * FEEDBACK_PAGE_SIZE)
+ .take(FEEDBACK_PAGE_SIZE)
+
+ if (search) {
+ // Emails live on the user table, so resolve matching authors first to
+ // make "who left it" searchable
+ const matchingUsers: { id: string }[] = await this.userRepository
+ .createQueryBuilder('user')
+ .select('user.id', 'id')
+ .where('LOWER(user.email) LIKE :search', {
+ search: `%${search.toLowerCase()}%`,
+ })
+ .getRawMany()
+
+ const ids = matchingUsers.map(({ id }) => id)
+
+ query = query.andWhere(
+ ids.length > 0
+ ? '(LOWER(fb.message) LIKE :search OR fb.userId IN (:...ids))'
+ : 'LOWER(fb.message) LIKE :search',
+ { search: `%${search.toLowerCase()}%`, ids },
+ )
+ }
+
+ const [items, total] = await query.getManyAndCount()
+
+ const usersById = await this.getUsersByIds(
+ Array.from(new Set(items.map((item) => item.userId))),
+ )
+
+ return {
+ total,
+ pageSize: FEEDBACK_PAGE_SIZE,
+ items: items.map((item) => ({
+ id: item.id,
+ message: item.message,
+ attachmentUrls: item.attachmentUrls || [],
+ createdAt: item.createdAt,
+ // null = the account was deleted since
+ user: usersById[item.userId] || null,
+ userId: item.userId,
+ })),
+ }
+ }
+
+ private async getCancellationFeedbackList(
+ page: number,
+ search: string,
+ order: 'ASC' | 'DESC',
+ ) {
+ let query = this.cancellationFeedbackRepository
+ .createQueryBuilder('fb')
+ .orderBy('fb.createdAt', order)
+ .skip(page * FEEDBACK_PAGE_SIZE)
+ .take(FEEDBACK_PAGE_SIZE)
+
+ if (search) {
+ query = query.andWhere(
+ '(LOWER(fb.feedback) LIKE :search OR LOWER(fb.email) LIKE :search OR LOWER(fb.planCode) LIKE :search)',
+ { search: `%${search.toLowerCase()}%` },
+ )
+ }
+
+ const [items, total] = await query.getManyAndCount()
+
+ // Link back to the account when it still exists
+ const emails = Array.from(
+ new Set(items.map((item) => item.email).filter(Boolean)),
+ )
+ const users =
+ emails.length > 0
+ ? await this.userRepository.find({
+ where: { email: In(emails) },
+ select: ['id', 'email', 'planCode'],
+ })
+ : []
+ const usersByEmail = Object.fromEntries(
+ users.map((user) => [user.email, user]),
+ )
+
+ return {
+ total,
+ pageSize: FEEDBACK_PAGE_SIZE,
+ items: items.map((item) => ({
+ id: item.id,
+ message: item.feedback,
+ email: item.email,
+ planCode: item.planCode,
+ createdAt: item.createdAt,
+ user: item.email
+ ? usersByEmail[item.email]
+ ? {
+ id: usersByEmail[item.email].id,
+ email: usersByEmail[item.email].email,
+ planCode: usersByEmail[item.email].planCode,
+ }
+ : null
+ : null,
+ })),
+ }
+ }
+
+ private async getDeleteFeedbackList(
+ page: number,
+ search: string,
+ order: 'ASC' | 'DESC',
+ ) {
+ let query = this.deleteFeedbackRepository
+ .createQueryBuilder('fb')
+ .orderBy('fb.createdAt', order)
+ .skip(page * FEEDBACK_PAGE_SIZE)
+ .take(FEEDBACK_PAGE_SIZE)
+
+ if (search) {
+ query = query.andWhere('LOWER(fb.feedback) LIKE :search', {
+ search: `%${search.toLowerCase()}%`,
+ })
+ }
+
+ const [items, total] = await query.getManyAndCount()
+
+ return {
+ total,
+ pageSize: FEEDBACK_PAGE_SIZE,
+ items: items.map((item) => ({
+ id: item.id,
+ message: item.feedback,
+ createdAt: item.createdAt,
+ })),
+ }
+ }
+
// -------------------- Database --------------------
async getDatabaseInfo() {
diff --git a/web/app/pages/Admin/AdminChart.tsx b/web/app/pages/Admin/AdminChart.tsx
new file mode 100644
index 000000000..bf7e0cca0
--- /dev/null
+++ b/web/app/pages/Admin/AdminChart.tsx
@@ -0,0 +1,139 @@
+import type { ChartOptions } from 'billboard.js'
+import { area } from 'billboard.js'
+import * as d3 from 'd3'
+import dayjs from 'dayjs'
+import { useMemo } from 'react'
+
+import BillboardChart from '~/ui/BillboardChart'
+import { nFormatter } from '~/utils/generic'
+
+import type { SeriesPoint } from './types'
+
+export interface AdminChartSeries {
+ id: string
+ name: string
+ color: string
+ data: SeriesPoint[]
+}
+
+// Same palette as the main analytics dashboard chart
+export const ADMIN_CHART_COLORS = {
+ blue: '#2563EB',
+ amber: '#D97706',
+ purple: '#c945ed',
+ teal: '#2AC4B3',
+ green: '#10B981',
+} as const
+
+const tooltipDateFormat = d3.timeFormat('%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 dates = Array.from(
+ new Set(series.flatMap(({ data }) => data.map(({ date }) => date))),
+ ).sort()
+
+ const columns: [string, ...(Date | number)[]][] = [
+ ['x', ...dates.map((date) => dayjs(date).toDate())],
+ ]
+
+ for (const { id, data } of series) {
+ const countByDate = new Map(data.map(({ date, count }) => [date, count]))
+ columns.push([id, ...dates.map((date) => countByDate.get(date) || 0)])
+ }
+
+ return {
+ data: {
+ x: 'x',
+ columns,
+ types: Object.fromEntries(series.map(({ id }) => [id, area()])),
+ colors: Object.fromEntries(series.map(({ id, color }) => [id, color])),
+ names: Object.fromEntries(series.map(({ id, name }) => [id, name])),
+ },
+ area: {
+ linearGradient: true,
+ },
+ grid: {
+ y: {
+ show: true,
+ },
+ },
+ transition: {
+ duration: 200,
+ },
+ resize: {
+ auto: true,
+ timer: true,
+ },
+ axis: {
+ x: {
+ type: 'timeseries',
+ clipPath: false,
+ tick: {
+ fit: false,
+ format: '%b %d',
+ },
+ },
+ y: {
+ tick: {
+ format: (d: number) => (Number.isInteger(d) ? nFormatter(d, 1) : ''),
+ },
+ show: true,
+ inner: true,
+ },
+ },
+ point: {
+ focus: {
+ only: dates.length > 1,
+ },
+ pattern: ['circle'],
+ r: 4,
+ },
+ legend: {
+ show: series.length > 1,
+ item: {
+ tile: {
+ type: 'circle',
+ width: 10,
+ r: 3,
+ },
+ },
+ },
+ tooltip: {
+ contents: (items, _, __, color) => {
+ const rows = items
+ .map(
+ (item) => `
+ <li class='flex justify-between items-center py-px leading-snug'>
+ <div class='flex items-center min-w-0 mr-4'>
+ <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>
+ </li>`,
+ )
+ .join('')
+
+ return `<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-900 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm shadow-md z-50'>
+ <li class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-slate-800'>${tooltipDateFormat(items[0].x as unknown as Date)}</li>
+ ${rows}
+ </ul>`
+ },
+ },
+ }
+}
+
+export const AdminChart = ({
+ series,
+ className,
+}: {
+ series: AdminChartSeries[]
+ className?: string
+}) => {
+ const options = useMemo(() => buildOptions(series), [series])
+
+ return (
+ <BillboardChart options={options} className={className} deps={[series]} />
+ )
+}
diff --git a/web/app/pages/Admin/BillingTab.tsx b/web/app/pages/Admin/BillingTab.tsx
new file mode 100644
index 000000000..6cc762487
--- /dev/null
+++ b/web/app/pages/Admin/BillingTab.tsx
@@ -0,0 +1,412 @@
+import { ArrowSquareOutIcon } from '@phosphor-icons/react'
+import dayjs from 'dayjs'
+import { Link } from 'react-router'
+
+import { Badge } from '~/ui/Badge'
+import { Text } from '~/ui/Text'
+import { nFormatter, nLocaleFormatter } from '~/utils/generic'
+
+import { AdminTable, EmptyState, formatDate, StatCard, Td } from './components'
+import { adminLinkClassName } from './UsersTab'
+import type { AdminBilling, AdminBillingUser, AdminPayment } from './types'
+
+const CURRENCY_SYMBOLS: Record<string, string> = {
+ USD: '$',
+ EUR: '€',
+ GBP: 'Β£',
+}
+
+const formatAmount = (amount: number, currency: string): string =>
+ `${CURRENCY_SYMBOLS[currency] || `${currency} `}${amount.toLocaleString(
+ 'en-US',
+ { minimumFractionDigits: 2, maximumFractionDigits: 2 },
+ )}`
+
+const UserLink = ({ user }: { user: { id: string; email: string } | null }) => {
+ if (!user) {
+ return (
+ <span className='text-gray-500 italic dark:text-gray-400'>
+ Unknown account
+ </span>
+ )
+ }
+
+ return (
+ <Link
+ to={`/admin?tab=users&user=${user.id}`}
+ className={adminLinkClassName}
+ >
+ {user.email}
+ </Link>
+ )
+}
+
+const PlanCell = ({ user }: { user: AdminBillingUser }) => (
+ <span className='inline-flex items-center gap-1.5'>
+ {user.planCode}
+ {user.billingFrequency === 'yearly' ? (
+ <Badge colour='slate' label='yearly' size='sm' />
+ ) : null}
+ </span>
+)
+
+const RevenueCell = ({ user }: { user: AdminBillingUser }) => (
+ <span className='tabular-nums'>
+ {user.monthlyRevenueUsd !== null
+ ? `$${nLocaleFormatter(Math.round(user.monthlyRevenueUsd))}/mo`
+ : 'β€”'}
+ </span>
+)
+
+// "in 3 days" / "2 days ago" with colour coding for urgency
+const DeadlineBadge = ({ date }: { date: string | null }) => {
+ if (!date) {
+ return <>β€”</>
+ }
+
+ const daysLeft = dayjs(date).diff(dayjs(), 'day')
+
+ return (
+ <span className='inline-flex items-center gap-2'>
+ <span>{formatDate(date)}</span>
+ <Badge
+ colour={daysLeft < 0 ? 'red' : daysLeft <= 3 ? 'yellow' : 'slate'}
+ label={
+ daysLeft < 0
+ ? `${Math.abs(daysLeft)}d ago`
+ : daysLeft === 0
+ ? 'today'
+ : `in ${daysLeft}d`
+ }
+ size='sm'
+ />
+ </span>
+ )
+}
+
+const Section = ({
+ title,
+ hint,
+ children,
+}: {
+ title: string
+ hint?: string
+ children: React.ReactNode
+}) => (
+ <section>
+ <Text as='h3' size='lg' weight='semibold'>
+ {title}
+ </Text>
+ {hint ? (
+ <Text as='p' size='sm' colour='secondary' className='mt-0.5'>
+ {hint}
+ </Text>
+ ) : null}
+ <div className='mt-3'>{children}</div>
+ </section>
+)
+
+const PaymentsTable = ({
+ payments,
+ emptyMessage,
+}: {
+ payments: AdminPayment[]
+ emptyMessage: string
+}) => {
+ if (payments.length === 0) {
+ return <EmptyState message={emptyMessage} />
+ }
+
+ return (
+ <AdminTable
+ columns={[
+ { key: 'date', label: 'Date' },
+ { key: 'user', label: 'Customer' },
+ { key: 'amount', label: 'Amount' },
+ { key: 'kind', label: '' },
+ { key: 'receipt', label: '' },
+ ]}
+ >
+ {payments.map((payment) => (
+ <tr key={payment.id}>
+ <Td>{formatDate(payment.date)}</Td>
+ <Td>
+ <UserLink user={payment.user} />
+ {payment.user?.planCode ? (
+ <span className='ml-2 text-xs text-gray-500 dark:text-gray-400'>
+ {payment.user.planCode}
+ </span>
+ ) : null}
+ </Td>
+ <Td className='font-medium tabular-nums'>
+ {formatAmount(payment.amount, payment.currency)}
+ </Td>
+ <Td>
+ {payment.isOneOff ? (
+ <Badge colour='indigo' label='one-off charge' size='sm' />
+ ) : null}
+ </Td>
+ <Td>
+ {payment.receiptUrl ? (
+ <a
+ href={payment.receiptUrl}
+ target='_blank'
+ rel='noopener noreferrer'
+ className='inline-flex items-center gap-1 text-xs font-medium text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100'
+ >
+ Receipt
+ <ArrowSquareOutIcon className='size-3.5' />
+ </a>
+ ) : null}
+ </Td>
+ </tr>
+ ))}
+ </AdminTable>
+ )
+}
+
+interface BillingTabProps {
+ billing: AdminBilling
+}
+
+export const BillingTab = ({ billing }: BillingTabProps) => {
+ const {
+ trialsEndingSoon,
+ cancellationPipeline,
+ suspended,
+ churnRisk,
+ payments,
+ } = billing
+
+ const atRiskMrr =
+ churnRisk.atRisk.reduce(
+ (acc, user) => acc + (user.monthlyRevenueUsd || 0),
+ 0,
+ ) +
+ cancellationPipeline.reduce(
+ (acc, user) => acc + (user.monthlyRevenueUsd || 0),
+ 0,
+ )
+
+ return (
+ <div className='flex flex-col gap-8'>
+ <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'
+ />
+ <StatCard
+ label='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'
+ />
+ <StatCard
+ label='At-risk MRR (est.)'
+ value={`$${nLocaleFormatter(Math.round(atRiskMrr))}`}
+ hint='Churn-risk + cancelling accounts, USD list price'
+ />
+ </div>
+
+ <Section
+ title='Trials ending soon'
+ hint='Sorted by trial end date. High usage + imminent expiry = worth a personal email.'
+ >
+ {trialsEndingSoon.length === 0 ? (
+ <EmptyState message='No trials ending in the next 14 days' />
+ ) : (
+ <AdminTable
+ columns={[
+ { key: 'email', label: 'User' },
+ { key: 'trialEnd', label: 'Trial ends' },
+ { key: 'monthlyEvents', label: 'Events this month' },
+ { key: 'projects', label: 'Projects' },
+ { key: 'registered', label: 'Registered' },
+ ]}
+ >
+ {trialsEndingSoon.map((user) => (
+ <tr key={user.id}>
+ <Td>
+ <UserLink user={user} />
+ </Td>
+ <Td>
+ <DeadlineBadge date={user.trialEndDate} />
+ </Td>
+ <Td className='tabular-nums'>
+ <span
+ className={
+ user.monthlyEvents > 0
+ ? 'font-medium text-emerald-600 dark:text-emerald-400'
+ : 'text-gray-500 dark:text-gray-400'
+ }
+ >
+ {nFormatter(user.monthlyEvents, 1)}
+ </span>
+ </Td>
+ <Td className='tabular-nums'>{user.projectCount}</Td>
+ <Td>{formatDate(user.created)}</Td>
+ </tr>
+ ))}
+ </AdminTable>
+ )}
+ </Section>
+
+ <Section
+ title='Churn risk'
+ hint={`Paying accounts whose events dropped β‰₯50% vs the previous 30 days (min ${nLocaleFormatter(100)} events).`}
+ >
+ {churnRisk.atRisk.length === 0 ? (
+ <EmptyState message='No paying accounts with collapsing usage β€” nice' />
+ ) : (
+ <AdminTable
+ columns={[
+ { key: 'email', label: 'User' },
+ { key: 'plan', label: 'Plan' },
+ { key: 'revenue', label: 'Est. revenue' },
+ { key: 'events30d', label: 'Events (30d)' },
+ { key: 'eventsPrev30d', label: 'Previous 30d' },
+ { key: 'drop', label: 'Drop' },
+ ]}
+ >
+ {churnRisk.atRisk.map((user) => (
+ <tr key={user.id}>
+ <Td>
+ <UserLink user={user} />
+ </Td>
+ <Td>
+ <PlanCell user={user} />
+ </Td>
+ <Td>
+ <RevenueCell user={user} />
+ </Td>
+ <Td className='tabular-nums'>
+ {nLocaleFormatter(user.events30d)}
+ </Td>
+ <Td className='tabular-nums'>
+ {nLocaleFormatter(user.eventsPrev30d)}
+ </Td>
+ <Td>
+ <Badge colour='red' label={`-${user.dropPercent}%`} />
+ </Td>
+ </tr>
+ ))}
+ </AdminTable>
+ )}
+ </Section>
+
+ <Section
+ title='Cancellation pipeline'
+ hint='Active subscriptions that will end on their effective date.'
+ >
+ {cancellationPipeline.length === 0 ? (
+ <EmptyState message='Nobody is cancelling right now' />
+ ) : (
+ <AdminTable
+ columns={[
+ { key: 'email', label: 'User' },
+ { key: 'plan', label: 'Plan' },
+ { key: 'revenue', label: 'Est. revenue' },
+ { key: 'effective', label: 'Cancellation effective' },
+ { key: 'nextBill', label: 'Next bill' },
+ ]}
+ >
+ {cancellationPipeline.map((user) => (
+ <tr key={user.id}>
+ <Td>
+ <UserLink user={user} />
+ </Td>
+ <Td>
+ <PlanCell user={user} />
+ </Td>
+ <Td>
+ <RevenueCell user={user} />
+ </Td>
+ <Td>
+ <DeadlineBadge date={user.cancellationEffectiveDate} />
+ </Td>
+ <Td>{formatDate(user.nextBillDate)}</Td>
+ </tr>
+ ))}
+ </AdminTable>
+ )}
+ </Section>
+
+ <Section
+ title='Suspended & blocked'
+ hint='Accounts whose dashboards are blocked or billing is suspended.'
+ >
+ {suspended.length === 0 ? (
+ <EmptyState message='No suspended or blocked accounts' />
+ ) : (
+ <AdminTable
+ columns={[
+ { key: 'email', label: 'User' },
+ { key: 'plan', label: 'Plan' },
+ { key: 'status', label: 'Status' },
+ { key: 'registered', label: 'Registered' },
+ ]}
+ >
+ {suspended.map((user) => (
+ <tr key={user.id}>
+ <Td>
+ <UserLink user={user} />
+ </Td>
+ <Td>
+ <PlanCell user={user} />
+ </Td>
+ <Td>
+ <span className='inline-flex items-center gap-1.5'>
+ {user.isAccountBillingSuspended ? (
+ <Badge colour='red' label='billing suspended' size='sm' />
+ ) : null}
+ {user.dashboardBlockReason ? (
+ <Badge
+ colour='yellow'
+ label={user.dashboardBlockReason}
+ size='sm'
+ />
+ ) : null}
+ </span>
+ </Td>
+ <Td>{formatDate(user.created)}</Td>
+ </tr>
+ ))}
+ </AdminTable>
+ )}
+ </Section>
+
+ {payments.available ? (
+ <>
+ <Section
+ title='Recent payments'
+ hint='Straight from Paddle (cached for an hour). One-off charges included.'
+ >
+ <PaymentsTable
+ payments={payments.recent}
+ emptyMessage='No payments in the last two months'
+ />
+ </Section>
+
+ <Section
+ title='Upcoming payments'
+ hint='Scheduled renewals for the next 45 days.'
+ >
+ <PaymentsTable
+ payments={payments.upcoming}
+ emptyMessage='No scheduled payments'
+ />
+ </Section>
+ </>
+ ) : (
+ <Section title='Payments'>
+ <EmptyState message='Paddle data unavailable' />
+ </Section>
+ )}
+ </div>
+ )
+}
diff --git a/web/app/pages/Admin/BotBlocksTab.tsx b/web/app/pages/Admin/BotBlocksTab.tsx
new file mode 100644
index 000000000..f35551209
--- /dev/null
+++ b/web/app/pages/Admin/BotBlocksTab.tsx
@@ -0,0 +1,213 @@
+import { Link } from 'react-router'
+
+import { Badge } from '~/ui/Badge'
+import Select from '~/ui/Select'
+import { Text } from '~/ui/Text'
+import { nFormatter, nLocaleFormatter } from '~/utils/generic'
+
+import { AdminChart, ADMIN_CHART_COLORS } from './AdminChart'
+import { AdminTable, EmptyState, StatCard, Td } from './components'
+import { adminLinkClassName } from './UsersTab'
+import type { AdminBotBlocks } from './types'
+
+const PERIODS = [
+ { key: 7, label: 'Last 7 days' },
+ { key: 30, label: 'Last 30 days' },
+ { key: 90, label: 'Last 90 days' },
+]
+
+const REASON_COLORS = [
+ ADMIN_CHART_COLORS.blue,
+ ADMIN_CHART_COLORS.amber,
+ ADMIN_CHART_COLORS.purple,
+ ADMIN_CHART_COLORS.teal,
+ ADMIN_CHART_COLORS.green,
+ '#f43f5e',
+ '#64748b',
+]
+
+const humanizeReason = (reason: string): string =>
+ reason.replaceAll('_', ' ').replace(/^./, (c) => c.toUpperCase())
+
+interface BotBlocksTabProps {
+ botBlocks: AdminBotBlocks
+ onDaysChange: (days: number) => void
+}
+
+export const BotBlocksTab = ({
+ botBlocks,
+ onDaysChange,
+}: BotBlocksTabProps) => {
+ const { days, totals, byReason, series, topProjects } = botBlocks
+
+ const selectedPeriod = PERIODS.find(({ key }) => key === days) || PERIODS[0]
+
+ // Pivot {date, reason, count} rows into one chart series per reason,
+ // ordered by volume so colours stay stable across period switches
+ const chartSeries = byReason.map(({ reason }, index) => ({
+ id: reason,
+ name: humanizeReason(reason),
+ color: REASON_COLORS[index % REASON_COLORS.length],
+ data: series
+ .filter((point) => point.reason === reason)
+ .map(({ date, count }) => ({ date, count })),
+ }))
+
+ const topReason = byReason[0]
+
+ return (
+ <div className='flex flex-col gap-6'>
+ <div className='flex items-start justify-between gap-3'>
+ <div>
+ <Text as='h3' size='lg' weight='semibold'>
+ Bot blocks
+ </Text>
+ <Text as='p' size='sm' colour='secondary' className='mt-0.5'>
+ Events dropped by bot protection. A project blocking most of its
+ traffic usually means a misconfigured proxy, not bots.
+ </Text>
+ </div>
+ <Select
+ label='Period'
+ fieldLabelClassName='sr-only'
+ title={selectedPeriod.label}
+ items={PERIODS}
+ labelExtractor={(item) => item.label}
+ keyExtractor={(item) => item.key.toString()}
+ selectedItem={selectedPeriod}
+ onSelect={(item) => onDaysChange(item.key)}
+ menuClassName='right-0 w-max min-w-full'
+ />
+ </div>
+
+ <div className='grid grid-cols-1 gap-4 sm:grid-cols-3'>
+ <StatCard
+ label={`Blocked (${days}d)`}
+ value={nFormatter(totals.total, 1)}
+ hint={nLocaleFormatter(totals.total)}
+ />
+ <StatCard label='Blocked (24h)' value={nFormatter(totals.last24h, 1)} />
+ <StatCard
+ label='Top reason'
+ value={topReason ? humanizeReason(topReason.reason) : 'β€”'}
+ hint={
+ topReason
+ ? `${nLocaleFormatter(topReason.count)} blocks`
+ : undefined
+ }
+ />
+ </div>
+
+ <div className='rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>
+ <Text as='h4' size='lg' weight='semibold' className='mb-4'>
+ Blocks by reason
+ </Text>
+ {series.length === 0 ? (
+ <EmptyState message='No blocks recorded in this period' />
+ ) : (
+ <AdminChart className='h-72' series={chartSeries} />
+ )}
+ </div>
+
+ <section>
+ <Text as='h4' size='lg' weight='semibold'>
+ Most blocked projects
+ </Text>
+ <Text as='p' size='sm' colour='secondary' className='mt-0.5'>
+ Block ratio = blocked / (blocked + accepted). Near 100% on an active
+ project is the datacenter-IP-wipeout signature β€” check their proxy
+ setup.
+ </Text>
+ <div className='mt-3'>
+ {topProjects.length === 0 ? (
+ <EmptyState message='No blocks recorded in this period' />
+ ) : (
+ <AdminTable
+ columns={[
+ { key: 'project', label: 'Project' },
+ { key: 'owner', label: 'Owner' },
+ { key: 'shield', label: 'Protection' },
+ { key: 'blocked', label: 'Blocked' },
+ { key: 'accepted', label: 'Accepted' },
+ { key: 'ratio', label: 'Block ratio' },
+ { key: 'reason', label: 'Top reason' },
+ ]}
+ >
+ {topProjects.map((project) => (
+ <tr key={project.id}>
+ <Td>
+ {project.name ? (
+ <Link
+ to={`/admin?tab=projects&project=${project.id}`}
+ className={adminLinkClassName}
+ >
+ {project.name}
+ </Link>
+ ) : (
+ <span className='text-gray-500 italic dark:text-gray-400'>
+ Deleted project
+ </span>
+ )}
+ <span className='ml-2 text-xs text-gray-500 dark:text-gray-400'>
+ {project.id}
+ </span>
+ </Td>
+ <Td>
+ {project.admin ? (
+ <Link
+ to={`/admin?tab=users&user=${project.admin.id}`}
+ className={adminLinkClassName}
+ >
+ {project.admin.email}
+ </Link>
+ ) : (
+ 'β€”'
+ )}
+ </Td>
+ <Td>
+ {project.botsProtectionLevel ? (
+ <Badge
+ colour={
+ project.botsProtectionLevel === 'strict'
+ ? 'yellow'
+ : 'slate'
+ }
+ label={project.botsProtectionLevel}
+ size='sm'
+ />
+ ) : (
+ 'β€”'
+ )}
+ </Td>
+ <Td className='tabular-nums'>
+ {nLocaleFormatter(project.blocked)}
+ </Td>
+ <Td className='tabular-nums'>
+ {nLocaleFormatter(project.accepted)}
+ </Td>
+ <Td>
+ <Badge
+ colour={
+ project.blockRatio >= 80
+ ? 'red'
+ : project.blockRatio >= 40
+ ? 'yellow'
+ : 'slate'
+ }
+ label={`${project.blockRatio}%`}
+ />
+ </Td>
+ <Td>
+ {project.topReason
+ ? humanizeReason(project.topReason)
+ : 'β€”'}
+ </Td>
+ </tr>
+ ))}
+ </AdminTable>
+ )}
+ </div>
+ </section>
+ </div>
+ )
+}
diff --git a/web/app/pages/Admin/DatabaseTab.tsx b/web/app/pages/Admin/DatabaseTab.tsx
index 0f07171a4..62910a9ef 100644
--- a/web/app/pages/Admin/DatabaseTab.tsx
+++ b/web/app/pages/Admin/DatabaseTab.tsx
@@ -1,7 +1,14 @@
import { Text } from '~/ui/Text'
import { nFormatter, nLocaleFormatter } from '~/utils/generic'
-import { AdminTable, formatBytes, StatCard, Td, UsageBar } from './components'
+import {
+ AdminTable,
+ formatBytes,
+ StatCard,
+ Td,
+ UsageBar,
+ useAdminSort,
+} from './components'
import type { AdminDatabaseInfo } from './types'
interface DatabaseTabProps {
@@ -11,6 +18,32 @@ interface DatabaseTabProps {
export const DatabaseTab = ({ database }: DatabaseTabProps) => {
const { clickhouse, mysql } = database
+ const clickhouseSort = useAdminSort<
+ AdminDatabaseInfo['clickhouse']['tables'][number]
+ >([], { by: 'compressedBytes', order: 'DESC' }, () => {}, {
+ table: (table) => table.table,
+ rows: (table) => table.rows,
+ compressedBytes: (table) => table.compressedBytes,
+ uncompressedBytes: (table) => table.uncompressedBytes,
+ ratio: (table) =>
+ table.compressedBytes > 0
+ ? table.uncompressedBytes / table.compressedBytes
+ : 0,
+ parts: (table) => table.parts,
+ })
+
+ const mysqlSort = useAdminSort<AdminDatabaseInfo['mysql']['tables'][number]>(
+ [],
+ { by: 'dataBytes', order: 'DESC' },
+ () => {},
+ {
+ tableName: (table) => table.tableName,
+ estimatedRows: (table) => table.estimatedRows,
+ dataBytes: (table) => table.dataBytes,
+ indexBytes: (table) => table.indexBytes,
+ },
+ )
+
const compressionRatio =
clickhouse.totalCompressedBytes > 0
? (
@@ -68,18 +101,20 @@ export const DatabaseTab = ({ database }: DatabaseTabProps) => {
</div>
<AdminTable
- headers={[
- 'Table',
- 'Rows',
- 'Compressed',
- 'Uncompressed',
- 'Ratio',
- 'Parts',
+ columns={[
+ { key: 'table', label: 'Table', sortable: true },
+ { key: 'rows', label: 'Rows', sortable: true },
+ { key: 'compressedBytes', label: 'Compressed', sortable: true },
+ { key: 'uncompressedBytes', label: 'Uncompressed', sortable: true },
+ { key: 'ratio', label: 'Ratio', sortable: true },
+ { key: 'parts', label: 'Parts', sortable: true },
]}
+ sort={clickhouseSort.sort}
+ onSort={clickhouseSort.onSort}
>
- {clickhouse.tables.map((table) => (
+ {clickhouseSort.sortRows(clickhouse.tables).map((table) => (
<tr key={table.table}>
- <Td className='font-mono'>{table.table}</Td>
+ <Td>{table.table}</Td>
<Td className='tabular-nums'>{nLocaleFormatter(table.rows)}</Td>
<Td className='tabular-nums'>
{formatBytes(table.compressedBytes)}
@@ -113,10 +148,19 @@ export const DatabaseTab = ({ database }: DatabaseTabProps) => {
</Text>
</div>
- <AdminTable headers={['Table', 'Est. rows', 'Data', 'Indexes']}>
- {mysql.tables.map((table) => (
+ <AdminTable
+ columns={[
+ { key: 'tableName', label: 'Table', sortable: true },
+ { key: 'estimatedRows', label: 'Est. rows', sortable: true },
+ { key: 'dataBytes', label: 'Data', sortable: true },
+ { key: 'indexBytes', label: 'Indexes', sortable: true },
+ ]}
+ sort={mysqlSort.sort}
+ onSort={mysqlSort.onSort}
+ >
+ {mysqlSort.sortRows(mysql.tables).map((table) => (
<tr key={table.tableName}>
- <Td className='font-mono'>{table.tableName}</Td>
+ <Td>{table.tableName}</Td>
<Td className='tabular-nums'>
{nLocaleFormatter(table.estimatedRows)}
</Td>
diff --git a/web/app/pages/Admin/FeedbackTab.tsx b/web/app/pages/Admin/FeedbackTab.tsx
new file mode 100644
index 000000000..1ab8dd8e4
--- /dev/null
+++ b/web/app/pages/Admin/FeedbackTab.tsx
@@ -0,0 +1,326 @@
+import {
+ ArrowSquareOutIcon,
+ FileIcon,
+ MagnifyingGlassIcon,
+} from '@phosphor-icons/react'
+import dayjs from 'dayjs'
+import relativeTime from 'dayjs/plugin/relativeTime'
+import { Link } from 'react-router'
+
+import { Badge } from '~/ui/Badge'
+import Input from '~/ui/Input'
+import Pagination from '~/ui/Pagination'
+import Select from '~/ui/Select'
+import { Text } from '~/ui/Text'
+import Tooltip from '~/ui/Tooltip'
+import { cn, nLocaleFormatter } from '~/utils/generic'
+
+import { EmptyState } from './components'
+import { adminLinkClassName } from './UsersTab'
+import type {
+ AdminFeedbackItem,
+ AdminFeedbackList,
+ AdminFeedbackType,
+} from './types'
+
+dayjs.extend(relativeTime)
+
+const FEEDBACK_TYPES: {
+ key: AdminFeedbackType
+ label: string
+ countKey: keyof AdminFeedbackList['counts']
+}[] = [
+ { key: 'user', label: 'User feedback', countKey: 'user' },
+ { key: 'cancellation', label: 'Cancellations', countKey: 'cancellation' },
+ { key: 'deletion', label: 'Account deletions', countKey: 'deletion' },
+]
+
+const SORT_OPTIONS = [
+ { key: 'DESC', label: 'Newest first' },
+ { key: 'ASC', label: 'Oldest first' },
+] as const
+
+const IMAGE_EXTENSIONS = /\.(png|jpe?g|gif|webp|avif|svg)(\?.*)?$/i
+
+const attachmentName = (url: string): string => {
+ try {
+ const pathname = new URL(url).pathname
+ return decodeURIComponent(pathname.split('/').pop() || url)
+ } catch {
+ return url
+ }
+}
+
+const Attachments = ({ urls }: { urls: string[] }) => {
+ if (urls.length === 0) {
+ return null
+ }
+
+ return (
+ <div className='mt-3 flex flex-wrap gap-2'>
+ {urls.map((url) =>
+ IMAGE_EXTENSIONS.test(url) ? (
+ <a
+ key={url}
+ href={url}
+ target='_blank'
+ rel='noopener noreferrer'
+ className='group relative block overflow-hidden rounded-md ring-1 ring-gray-200 transition-shadow hover:ring-2 hover:ring-indigo-400 dark:ring-slate-700/80'
+ >
+ <img
+ src={url}
+ alt={attachmentName(url)}
+ loading='lazy'
+ className='h-24 w-auto max-w-48 object-cover'
+ />
+ <span className='absolute inset-0 hidden items-center justify-center bg-black/40 group-hover:flex'>
+ <ArrowSquareOutIcon className='size-5 text-white' />
+ </span>
+ </a>
+ ) : (
+ <a
+ key={url}
+ href={url}
+ target='_blank'
+ rel='noopener noreferrer'
+ className='inline-flex items-center gap-1.5 rounded-md bg-gray-100 px-2.5 py-1.5 text-xs font-medium text-gray-700 transition-colors hover:bg-gray-200 dark:bg-slate-800 dark:text-gray-200 dark:hover:bg-slate-700'
+ >
+ <FileIcon className='size-4 shrink-0' />
+ <span className='max-w-48 truncate'>{attachmentName(url)}</span>
+ </a>
+ ),
+ )}
+ </div>
+ )
+}
+
+const authorInitial = (item: AdminFeedbackItem): string => {
+ const source = item.user?.email || item.email
+ return source ? source[0].toUpperCase() : '?'
+}
+
+const FeedbackAuthor = ({
+ item,
+ type,
+}: {
+ item: AdminFeedbackItem
+ type: AdminFeedbackType
+}) => {
+ if (item.user) {
+ return (
+ <span className='inline-flex items-center gap-2'>
+ <Link
+ to={`/admin?tab=users&user=${item.user.id}`}
+ className={adminLinkClassName}
+ >
+ {item.user.email}
+ </Link>
+ {item.user.planCode && item.user.planCode !== 'none' ? (
+ <Badge colour='indigo' label={item.user.planCode} size='sm' />
+ ) : null}
+ </span>
+ )
+ }
+
+ // Cancellation rows keep the email even after the account is gone
+ if (item.email) {
+ return (
+ <span className='inline-flex items-center gap-2'>
+ <span className='text-sm font-medium text-gray-900 dark:text-gray-100'>
+ {item.email}
+ </span>
+ <Badge colour='slate' label='account deleted' size='sm' />
+ </span>
+ )
+ }
+
+ if (type === 'deletion') {
+ return (
+ <span className='text-sm font-medium text-gray-500 italic dark:text-gray-400'>
+ Deleted account
+ </span>
+ )
+ }
+
+ return (
+ <span className='inline-flex items-center gap-2'>
+ <span className='text-sm font-medium text-gray-500 italic dark:text-gray-400'>
+ Unknown user
+ </span>
+ <Badge colour='slate' label='account deleted' size='sm' />
+ </span>
+ )
+}
+
+const FeedbackCard = ({
+ item,
+ type,
+}: {
+ item: AdminFeedbackItem
+ type: AdminFeedbackType
+}) => (
+ <div className='rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>
+ <div className='flex flex-wrap items-center justify-between gap-x-4 gap-y-1'>
+ <div className='flex min-w-0 items-center gap-3'>
+ <span
+ aria-hidden='true'
+ className='flex size-8 shrink-0 items-center justify-center rounded-full bg-indigo-100 text-sm font-semibold text-indigo-700 dark:bg-indigo-500/20 dark:text-indigo-300'
+ >
+ {authorInitial(item)}
+ </span>
+ <div className='min-w-0'>
+ <FeedbackAuthor item={item} type={type} />
+ {type === 'cancellation' && item.planCode ? (
+ <Text as='p' size='xs' colour='secondary'>
+ was on {item.planCode}
+ </Text>
+ ) : null}
+ </div>
+ </div>
+ <Tooltip
+ text={dayjs(item.createdAt).format('MMM D, YYYY HH:mm')}
+ tooltipNode={
+ <Text
+ as='span'
+ size='xs'
+ colour='secondary'
+ className='whitespace-nowrap'
+ >
+ {dayjs(item.createdAt).fromNow()}
+ </Text>
+ }
+ />
+ </div>
+
+ <div className='mt-3'>
+ {item.message ? (
+ <Text
+ as='p'
+ size='sm'
+ className='leading-relaxed break-words whitespace-pre-wrap'
+ >
+ {item.message}
+ </Text>
+ ) : (
+ <Text as='p' size='sm' colour='secondary' className='italic'>
+ No message left
+ </Text>
+ )}
+ </div>
+
+ <Attachments urls={item.attachmentUrls || []} />
+ </div>
+)
+
+interface FeedbackTabProps {
+ feedback: AdminFeedbackList
+ type: AdminFeedbackType
+ page: number
+ search: string
+ order: 'ASC' | 'DESC'
+ onTypeChange: (type: AdminFeedbackType) => void
+ onPageChange: (page: number) => void
+ onSearchChange: (search: string) => void
+ onOrderChange: (order: 'ASC' | 'DESC') => void
+}
+
+export const FeedbackTab = ({
+ feedback,
+ type,
+ page,
+ search,
+ order,
+ onTypeChange,
+ onPageChange,
+ onSearchChange,
+ onOrderChange,
+}: FeedbackTabProps) => {
+ const selectedSort =
+ SORT_OPTIONS.find(({ key }) => key === order) || SORT_OPTIONS[0]
+
+ const searchPlaceholder =
+ type === 'user'
+ ? 'Search by message or author email'
+ : type === 'cancellation'
+ ? 'Search by message, email or plan'
+ : 'Search by message'
+
+ return (
+ <div className='flex flex-col gap-4'>
+ <div className='flex w-fit max-w-full overflow-x-auto rounded-md border border-gray-200 p-0.5 dark:border-slate-800/60'>
+ {FEEDBACK_TYPES.map(({ key, label, countKey }) => (
+ <button
+ key={key}
+ type='button'
+ onClick={() => onTypeChange(key)}
+ className={cn(
+ 'flex cursor-pointer items-center gap-1.5 rounded px-3 py-1.5 text-sm font-medium whitespace-nowrap transition-colors',
+ type === key
+ ? 'bg-gray-100 text-gray-900 dark:bg-slate-800 dark:text-gray-50'
+ : 'text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-50',
+ )}
+ >
+ {label}
+ <span
+ className={cn(
+ 'rounded-full px-1.5 text-xs tabular-nums',
+ type === key
+ ? 'bg-gray-200 text-gray-700 dark:bg-slate-700 dark:text-gray-200'
+ : 'bg-gray-100 text-gray-500 dark:bg-slate-800/80 dark:text-gray-400',
+ )}
+ >
+ {nLocaleFormatter(feedback.counts[countKey])}
+ </span>
+ </button>
+ ))}
+ </div>
+
+ <div className='flex flex-col gap-3 sm:flex-row sm:items-end'>
+ <Input
+ label='Search feedback'
+ className='sm:max-w-xs sm:flex-1'
+ leadingIcon={<MagnifyingGlassIcon className='size-4 text-gray-400' />}
+ placeholder={searchPlaceholder}
+ defaultValue={search}
+ onChange={(event) => onSearchChange(event.target.value)}
+ />
+ <Select
+ label='Sort'
+ fieldLabelClassName='sr-only'
+ title={selectedSort.label}
+ items={SORT_OPTIONS}
+ labelExtractor={(item) => item.label}
+ keyExtractor={(item) => item.key}
+ selectedItem={selectedSort}
+ onSelect={(item) => onOrderChange(item.key)}
+ menuClassName='w-max min-w-full'
+ />
+ </div>
+
+ {feedback.items.length === 0 ? (
+ <EmptyState
+ message={
+ search ? 'No feedback matches your search' : 'No feedback here yet'
+ }
+ />
+ ) : (
+ <>
+ <div className='flex flex-col gap-3'>
+ {feedback.items.map((item) => (
+ <FeedbackCard key={item.id} item={item} type={type} />
+ ))}
+ </div>
+ {feedback.total > feedback.pageSize ? (
+ <Pagination
+ page={page + 1}
+ setPage={(newPage) => onPageChange(newPage - 1)}
+ pageAmount={Math.ceil(feedback.total / feedback.pageSize)}
+ total={feedback.total}
+ pageSize={feedback.pageSize}
+ />
+ ) : null}
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/web/app/pages/Admin/OrganisationsTab.tsx b/web/app/pages/Admin/OrganisationsTab.tsx
index 84a4f3ca8..97393324b 100644
--- a/web/app/pages/Admin/OrganisationsTab.tsx
+++ b/web/app/pages/Admin/OrganisationsTab.tsx
@@ -1,68 +1,299 @@
-import { MagnifyingGlassIcon } from '@phosphor-icons/react'
+import { ArrowLeftIcon, MagnifyingGlassIcon } from '@phosphor-icons/react'
+import { Link } from 'react-router'
+import { Badge } from '~/ui/Badge'
import Input from '~/ui/Input'
import Pagination from '~/ui/Pagination'
+import { Text } from '~/ui/Text'
+import { nLocaleFormatter } from '~/utils/generic'
-import { AdminTable, EmptyState, formatDate, Td } from './components'
-import type { AdminOrganisationsList } from './types'
+import {
+ AdminTable,
+ EmptyState,
+ formatDate,
+ formatDateTime,
+ StatCard,
+ Td,
+ useAdminSort,
+} from './components'
+import { adminLinkClassName } from './UsersTab'
+import type {
+ AdminOrganisationDetails,
+ AdminOrganisationsList,
+ SortState,
+} from './types'
+
+const OrganisationDetails = ({
+ details,
+ onBack,
+}: {
+ details: AdminOrganisationDetails
+ onBack: () => void
+}) => {
+ const { organisation, members, projects } = details
+
+ return (
+ <div className='flex flex-col gap-6'>
+ <div>
+ <button
+ type='button'
+ onClick={onBack}
+ className='inline-flex cursor-pointer items-center gap-1.5 text-sm font-medium text-gray-700 hover:text-gray-900 dark:text-gray-300 dark:hover:text-gray-50'
+ >
+ <ArrowLeftIcon className='size-4' />
+ Back to organisations
+ </button>
+ <div className='mt-3 flex items-baseline gap-3'>
+ <Text as='h3' size='xl' weight='semibold'>
+ {organisation.name}
+ </Text>
+ <Text as='span' size='sm' colour='secondary'>
+ {organisation.id}
+ </Text>
+ </div>
+ </div>
+
+ <div className='grid grid-cols-1 gap-4 sm:grid-cols-3'>
+ <StatCard label='Members' value={organisation.memberCount} />
+ <StatCard label='Projects' value={organisation.projectCount} />
+ <StatCard
+ label='Created'
+ value={formatDateTime(organisation.created)}
+ />
+ </div>
+
+ <div>
+ <Text as='h4' size='lg' weight='semibold' className='mb-3'>
+ Members ({members.length})
+ </Text>
+ {members.length === 0 ? (
+ <EmptyState message='No members' />
+ ) : (
+ <AdminTable
+ columns={[
+ { key: 'user', label: 'User' },
+ { key: 'role', label: 'Role' },
+ { key: 'confirmed', label: 'Confirmed' },
+ { key: 'created', label: 'Joined' },
+ ]}
+ >
+ {members.map((member) => (
+ <tr key={member.id}>
+ <Td>
+ {member.user ? (
+ <Link
+ to={`/admin?tab=users&user=${member.user.id}`}
+ className={adminLinkClassName}
+ >
+ {member.user.email}
+ </Link>
+ ) : (
+ 'β€”'
+ )}
+ </Td>
+ <Td>
+ <Badge colour='indigo' label={member.role} size='sm' />
+ </Td>
+ <Td>{member.confirmed ? 'Yes' : 'No'}</Td>
+ <Td>{formatDate(member.created)}</Td>
+ </tr>
+ ))}
+ </AdminTable>
+ )}
+ </div>
+
+ <div>
+ <Text as='h4' size='lg' weight='semibold' className='mb-3'>
+ Projects ({projects.length})
+ </Text>
+ {projects.length === 0 ? (
+ <EmptyState message='No projects' />
+ ) : (
+ <AdminTable
+ columns={[
+ { key: 'name', label: 'Project' },
+ { key: 'owner', label: 'Owner' },
+ { key: 'events24h', label: '24h events' },
+ { key: 'events30d', label: '30d events' },
+ { key: 'totalEvents', label: 'Total events' },
+ { key: 'created', label: 'Created' },
+ { key: 'badges', label: '' },
+ ]}
+ >
+ {projects.map((project) => (
+ <tr key={project.id}>
+ <Td>
+ <Link
+ to={`/admin?tab=projects&project=${project.id}`}
+ className={adminLinkClassName}
+ >
+ {project.name}
+ </Link>
+ <span className='ml-2 text-xs text-gray-500 dark:text-gray-400'>
+ {project.id}
+ </span>
+ </Td>
+ <Td>
+ {project.admin ? (
+ <Link
+ to={`/admin?tab=users&user=${project.admin.id}`}
+ className={adminLinkClassName}
+ >
+ {project.admin.email}
+ </Link>
+ ) : (
+ 'β€”'
+ )}
+ </Td>
+ <Td className='tabular-nums'>
+ {nLocaleFormatter(project.events24h)}
+ </Td>
+ <Td className='tabular-nums'>
+ {nLocaleFormatter(project.events30d)}
+ </Td>
+ <Td className='tabular-nums'>
+ {nLocaleFormatter(project.totalEvents)}
+ </Td>
+ <Td>{formatDate(project.created)}</Td>
+ <Td>
+ {project.isArchived ? (
+ <Badge colour='slate' label='archived' size='sm' />
+ ) : null}
+ </Td>
+ </tr>
+ ))}
+ </AdminTable>
+ )}
+ </div>
+ </div>
+ )
+}
interface OrganisationsTabProps {
organisations: AdminOrganisationsList
+ organisationDetails?: AdminOrganisationDetails | null
page: number
search: string
+ sort: SortState
onPageChange: (page: number) => void
onSearchChange: (search: string) => void
+ onSortChange: (by: string, order: 'ASC' | 'DESC') => void
+ onOrganisationSelect: (id: string | null) => void
}
export const OrganisationsTab = ({
organisations,
+ organisationDetails,
page,
search,
+ sort,
onPageChange,
onSearchChange,
-}: OrganisationsTabProps) => (
- <div className='flex flex-col gap-4'>
- <Input
- label='Search organisations'
- className='sm:max-w-xs'
- leadingIcon={<MagnifyingGlassIcon className='size-4 text-gray-400' />}
- placeholder='Search by name or ID'
- defaultValue={search}
- onChange={(event) => onSearchChange(event.target.value)}
- />
+ onSortChange,
+ onOrganisationSelect,
+}: OrganisationsTabProps) => {
+ const {
+ sort: activeSort,
+ onSort,
+ sortRows,
+ } = useAdminSort<AdminOrganisationsList['organisations'][number]>(
+ ['name', 'created'],
+ sort,
+ onSortChange,
+ {
+ memberCount: (org) => org.memberCount,
+ projectCount: (org) => org.projectCount,
+ owner: (org) => org.owner?.email || null,
+ },
+ )
- {organisations.organisations.length === 0 ? (
- <EmptyState message='No organisations found' />
- ) : (
- <>
- <AdminTable
- headers={['Organisation', 'Owner', 'Members', 'Projects', 'Created']}
- >
- {organisations.organisations.map((organisation) => (
- <tr key={organisation.id}>
- <Td>
- <span className='font-medium'>{organisation.name}</span>
- <div className='font-mono text-xs text-gray-500 dark:text-gray-400'>
- {organisation.id}
- </div>
- </Td>
- <Td>{organisation.owner?.email || 'β€”'}</Td>
- <Td className='tabular-nums'>{organisation.memberCount}</Td>
- <Td className='tabular-nums'>{organisation.projectCount}</Td>
- <Td>{formatDate(organisation.created)}</Td>
- </tr>
- ))}
- </AdminTable>
- {organisations.total > organisations.pageSize ? (
- <Pagination
- page={page + 1}
- setPage={(newPage) => onPageChange(newPage - 1)}
- pageAmount={Math.ceil(organisations.total / organisations.pageSize)}
- total={organisations.total}
- pageSize={organisations.pageSize}
- />
- ) : null}
- </>
- )}
- </div>
-)
+ if (organisationDetails) {
+ return (
+ <OrganisationDetails
+ details={organisationDetails}
+ onBack={() => onOrganisationSelect(null)}
+ />
+ )
+ }
+
+ return (
+ <div className='flex flex-col gap-4'>
+ <Input
+ label='Search organisations'
+ className='sm:max-w-xs'
+ leadingIcon={<MagnifyingGlassIcon className='size-4 text-gray-400' />}
+ placeholder='Search by name or ID'
+ defaultValue={search}
+ onChange={(event) => onSearchChange(event.target.value)}
+ />
+
+ {organisations.organisations.length === 0 ? (
+ <EmptyState message='No organisations found' />
+ ) : (
+ <>
+ <AdminTable
+ columns={[
+ { key: 'name', label: 'Organisation', sortable: true },
+ { key: 'owner', label: 'Owner', sortable: true },
+ { key: 'memberCount', label: 'Members', sortable: true },
+ { key: 'projectCount', label: 'Projects', sortable: true },
+ { key: 'created', label: 'Created', sortable: true },
+ ]}
+ sort={activeSort}
+ onSort={onSort}
+ >
+ {sortRows(organisations.organisations).map((organisation) => (
+ <tr
+ key={organisation.id}
+ onClick={() => onOrganisationSelect(organisation.id)}
+ onKeyDown={(e) => {
+ if (e.target !== e.currentTarget) return
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault()
+ onOrganisationSelect(organisation.id)
+ }
+ }}
+ tabIndex={0}
+ className='cursor-pointer transition-colors hover:bg-gray-50 focus-visible:bg-gray-50 focus-visible:-outline-offset-2 dark:hover:bg-slate-900/60 dark:focus-visible:bg-slate-900/60'
+ >
+ <Td>
+ <span className='font-medium'>{organisation.name}</span>
+ <div className='text-xs text-gray-500 dark:text-gray-400'>
+ {organisation.id}
+ </div>
+ </Td>
+ <Td>
+ {organisation.owner ? (
+ <Link
+ to={`/admin?tab=users&user=${organisation.owner.id}`}
+ onClick={(e) => e.stopPropagation()}
+ className={adminLinkClassName}
+ >
+ {organisation.owner.email}
+ </Link>
+ ) : (
+ 'β€”'
+ )}
+ </Td>
+ <Td className='tabular-nums'>{organisation.memberCount}</Td>
+ <Td className='tabular-nums'>{organisation.projectCount}</Td>
+ <Td>{formatDate(organisation.created)}</Td>
+ </tr>
+ ))}
+ </AdminTable>
+ {organisations.total > organisations.pageSize ? (
+ <Pagination
+ page={page + 1}
+ setPage={(newPage) => onPageChange(newPage - 1)}
+ pageAmount={Math.ceil(
+ organisations.total / organisations.pageSize,
+ )}
+ total={organisations.total}
+ pageSize={organisations.pageSize}
+ />
+ ) : null}
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/web/app/pages/Admin/OverviewTab.tsx b/web/app/pages/Admin/OverviewTab.tsx
index 8f58338ab..6b8588a8c 100644
--- a/web/app/pages/Admin/OverviewTab.tsx
+++ b/web/app/pages/Admin/OverviewTab.tsx
@@ -1,91 +1,188 @@
-import type { ChartOptions } from 'billboard.js'
-import { area } from 'billboard.js'
import dayjs from 'dayjs'
-import { useMemo } from 'react'
+import { motion } from 'motion/react'
-import BillboardChart from '~/ui/BillboardChart'
+import {
+ MetricCard,
+ metricCardsContainerVariants,
+} from '~/pages/Project/tabs/Traffic/MetricCards'
import { Badge } from '~/ui/Badge'
import Select from '~/ui/Select'
import { Text } from '~/ui/Text'
import { nFormatter, nLocaleFormatter } from '~/utils/generic'
-import { StatCard } from './components'
-import type { AdminCharts, AdminOverview, SeriesPoint } from './types'
+import { AdminChart, ADMIN_CHART_COLORS } from './AdminChart'
+import { ChangeBadge, StatCard } from './components'
+import type { AdminCharts, AdminOverview, AdminRevenue } from './types'
const CHART_DAYS_OPTIONS = [30, 90, 180, 365]
-const buildTimeseriesOptions = (
- series: { id: string; name: string; color: string; data: SeriesPoint[] }[],
-): ChartOptions => {
- const dates = Array.from(
- new Set(series.flatMap(({ data }) => data.map(({ date }) => date))),
- ).sort()
+const MRR_CURRENCY_SYMBOLS: Record<string, string> = {
+ USD: '$',
+ EUR: '€',
+ GBP: 'Β£',
+}
+
+const formatCurrencyBreakdown = (byCurrency: Record<string, number>): string =>
+ Object.entries(byCurrency)
+ .filter(([, amount]) => amount > 0)
+ .sort(([, a], [, b]) => b - a)
+ .map(
+ ([currency, amount]) =>
+ `${MRR_CURRENCY_SYMBOLS[currency] || `${currency} `}${nLocaleFormatter(Math.round(amount))}`,
+ )
+ .join(' + ')
- const columns: [string, ...(Date | number)[]][] = [
- ['x', ...dates.map((date) => dayjs(date).toDate())],
- ]
+const countMetricMapper = (value: number, type: 'main' | 'badge') =>
+ type === 'badge'
+ ? `${value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ : nLocaleFormatter(value)
- for (const { id, data } of series) {
- const countByDate = new Map(data.map(({ date, count }) => [date, count]))
- columns.push([id, ...dates.map((date) => countByDate.get(date) || 0)])
+const RevenueCard = ({
+ overview,
+ revenue,
+}: {
+ overview: AdminOverview
+ revenue: AdminRevenue | null | undefined
+}) => {
+ if (!revenue?.available || !revenue.currentMonth) {
+ const mrrBreakdown = formatCurrencyBreakdown(overview.mrr.byCurrency)
+
+ return (
+ <StatCard
+ label='MRR (est., USD list price)'
+ value={`$${nLocaleFormatter(Math.round(overview.mrr.usdEquivalent))}`}
+ hint={
+ overview.mrr.unpricedSubscriptions > 0
+ ? `${mrrBreakdown} Β· ${overview.mrr.unpricedSubscriptions} unpriced Β· Paddle data unavailable`
+ : `${mrrBreakdown} Β· Paddle data unavailable`
+ }
+ />
+ )
}
- return {
- data: {
- x: 'x',
- columns,
- types: Object.fromEntries(series.map(({ id }) => [id, area()])),
- colors: Object.fromEntries(series.map(({ id, color }) => [id, color])),
- names: Object.fromEntries(series.map(({ id, name }) => [id, name])),
- },
- grid: {
- y: {
- show: true,
- },
- },
- transition: {
- duration: 200,
- },
- resize: {
- auto: true,
- timer: true,
- },
- axis: {
- x: {
- type: 'timeseries',
- tick: {
- fit: false,
- format: '%b %d',
- },
- },
- y: {
- tick: {
- // Counts are integers - hide the fractional gridline labels
- format: (d: number) => (Number.isInteger(d) ? nFormatter(d, 1) : ''),
- },
- show: true,
- inner: true,
- },
- },
- point: {
- focus: {
- only: true,
- },
- pattern: ['circle'],
- r: 2,
- },
- legend: {
- show: true,
- },
+ const { currentMonth, previousMonth, previousMonthToDate, upcoming } = revenue
+
+ const change = previousMonthToDate
+ ? Math.round(currentMonth.approxUsd - previousMonthToDate.approxUsd)
+ : null
+
+ const hints = [formatCurrencyBreakdown(currentMonth.byCurrency)].filter(
+ Boolean,
+ )
+
+ if (previousMonth) {
+ hints.push(
+ `$${nLocaleFormatter(Math.round(previousMonth.approxUsd))} last month`,
+ )
+ }
+
+ if (upcoming && upcoming.approxUsd > 0) {
+ hints.push(`$${nLocaleFormatter(Math.round(upcoming.approxUsd))} scheduled`)
}
+
+ return (
+ <StatCard
+ label={`Revenue (${dayjs().format('MMMM')}, Paddle)`}
+ value={`$${nLocaleFormatter(Math.round(currentMonth.approxUsd))}`}
+ badge={
+ <ChangeBadge
+ change={change}
+ formatter={(value) => `$${nFormatter(Math.abs(value), 1)}`}
+ />
+ }
+ hint={hints.join(' Β· ')}
+ />
+ )
}
-const MRR_CURRENCY_SYMBOLS = { USD: '$', EUR: '€', GBP: 'Β£' } as const
+const FUNNEL_STAGES: {
+ key: keyof AdminCharts['funnel']
+ label: string
+}[] = [
+ { key: 'signups', label: 'Signed up' },
+ { key: 'verified', label: 'Verified email' },
+ { key: 'createdProject', label: 'Created a project' },
+ { key: 'sentData', label: 'Sent data' },
+ { key: 'paid', label: 'Paying now' },
+]
+
+// Cohort funnel: everyone who signed up in the selected window and how far
+// they got (current state)
+const ActivationFunnel = ({
+ funnel,
+ chartDays,
+}: {
+ funnel: AdminCharts['funnel']
+ chartDays: number
+}) => (
+ <div className='rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>
+ <Text as='h3' size='lg' weight='semibold'>
+ Activation funnel
+ </Text>
+ <Text as='p' size='sm' colour='secondary' className='mt-0.5'>
+ Users who signed up in the last {chartDays} days, by how far they got
+ </Text>
+ <div className='mt-4 flex flex-col gap-2.5'>
+ {FUNNEL_STAGES.map(({ key, label }, index) => {
+ const count = funnel[key]
+ const pctOfSignups =
+ funnel.signups > 0 ? (count / funnel.signups) * 100 : 0
+ const prevCount =
+ index === 0 ? null : funnel[FUNNEL_STAGES[index - 1].key]
+ const stepPct =
+ prevCount === null
+ ? null
+ : prevCount > 0
+ ? Math.round((count / prevCount) * 100)
+ : 0
+
+ return (
+ <div key={key} className='flex items-center gap-3'>
+ <Text as='span' size='sm' className='w-36 shrink-0' truncate>
+ {label}
+ </Text>
+ <div className='h-5 flex-1 overflow-hidden rounded-sm bg-gray-100 dark:bg-slate-800/60'>
+ <div
+ className='h-full rounded-sm bg-indigo-500 transition-[width] duration-300'
+ style={{ width: `${pctOfSignups}%` }}
+ />
+ </div>
+ <Text
+ as='span'
+ size='sm'
+ weight='semibold'
+ className='w-14 shrink-0 text-right tabular-nums'
+ >
+ {nLocaleFormatter(count)}
+ </Text>
+ <Text
+ as='span'
+ size='xs'
+ colour='secondary'
+ className='w-24 shrink-0 text-right tabular-nums'
+ >
+ {Math.round(pctOfSignups)}% of signups
+ </Text>
+ <Text
+ as='span'
+ size='xs'
+ colour='secondary'
+ className='hidden w-20 shrink-0 text-right tabular-nums sm:block'
+ >
+ {stepPct === null ? '' : `${stepPct}% of prev`}
+ </Text>
+ </div>
+ )
+ })}
+ </div>
+ </div>
+)
interface OverviewTabProps {
overview: AdminOverview
charts: AdminCharts
chartDays: number
+ revenue?: AdminRevenue | null
onChartDaysChange: (days: number) => void
}
@@ -93,95 +190,55 @@ export const OverviewTab = ({
overview,
charts,
chartDays,
+ revenue,
onChartDaysChange,
}: OverviewTabProps) => {
- const growthOptions = useMemo(
- () =>
- buildTimeseriesOptions([
- {
- id: 'signups',
- name: 'Signups',
- color: '#2563eb',
- data: charts.signups,
- },
- {
- id: 'projects',
- name: 'Projects created',
- color: '#16a34a',
- data: charts.projects,
- },
- {
- id: 'organisations',
- name: 'Organisations created',
- color: '#9333ea',
- data: charts.organisations,
- },
- ]),
- [charts],
- )
-
- const eventsOptions = useMemo(
- () =>
- buildTimeseriesOptions([
- {
- id: 'events',
- name: 'Events',
- color: '#f59e0b',
- data: charts.events,
- },
- ]),
- [charts],
- )
-
- const mrrBreakdown = (
- Object.entries(overview.mrr.byCurrency) as [
- keyof typeof MRR_CURRENCY_SYMBOLS,
- number,
- ][]
- )
- .filter(([, amount]) => amount > 0)
- .map(
- ([currency, amount]) =>
- `${MRR_CURRENCY_SYMBOLS[currency]}${nLocaleFormatter(Math.round(amount))}`,
- )
- .join(' + ')
-
const maxPlanCount = Math.max(
...overview.planDistribution.map(({ count }) => count),
1,
)
+ const payersChange =
+ revenue?.available && revenue.currentMonth && revenue.previousMonthToDate
+ ? revenue.currentMonth.payers - revenue.previousMonthToDate.payers
+ : null
+
+ const { totals } = charts
+
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='MRR (est., USD list price)'
- value={`$${nLocaleFormatter(Math.round(overview.mrr.usdEquivalent))}`}
- hint={
- overview.mrr.unpricedSubscriptions > 0
- ? `${mrrBreakdown} Β· ${overview.mrr.unpricedSubscriptions} unpriced`
- : mrrBreakdown
- }
- />
+ <RevenueCard overview={overview} revenue={revenue} />
<StatCard
label='Paying users'
value={nLocaleFormatter(overview.mrr.payingUsers)}
+ badge={<ChangeBadge change={payersChange} />}
hint={`${nLocaleFormatter(overview.users.trial)} on trial Β· ${nLocaleFormatter(overview.users.cancelling)} cancelling`}
/>
<StatCard
label='Users'
value={nLocaleFormatter(overview.users.total)}
+ badge={
+ <ChangeBadge
+ change={overview.users.signups30d - overview.users.signupsPrev30d}
+ />
+ }
hint={`+${overview.users.signups24h} today Β· +${overview.users.signups7d} this week Β· +${overview.users.signups30d} this month`}
/>
<StatCard
label='Events (30d)'
value={nFormatter(overview.events.last30d, 1)}
+ badge={
+ <ChangeBadge
+ change={overview.events.last30d - overview.events.prev30d}
+ />
+ }
hint={`${nFormatter(overview.events.last24h, 1)} in 24h Β· ${nFormatter(overview.events.total, 1)} all-time`}
/>
</div>
- <div className='rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>
- <div className='mb-4 flex items-center justify-between'>
+ <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-4 flex items-center justify-between gap-3'>
<Text as='h3' size='lg' weight='semibold'>
Growth
</Text>
@@ -194,26 +251,97 @@ export const OverviewTab = ({
keyExtractor={(days) => days.toString()}
selectedItem={chartDays}
onSelect={onChartDaysChange}
+ menuClassName='right-0 w-max min-w-full'
/>
</div>
- <BillboardChart
- options={growthOptions}
+ <motion.div
+ initial='hidden'
+ animate='visible'
+ variants={metricCardsContainerVariants}
+ className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'
+ >
+ <MetricCard
+ label='Signups'
+ value={totals.signups.current}
+ change={totals.signups.current - totals.signups.previous}
+ goodChangeDirection='down'
+ valueMapper={countMetricMapper}
+ />
+ <MetricCard
+ label='Projects created'
+ value={totals.projects.current}
+ change={totals.projects.current - totals.projects.previous}
+ goodChangeDirection='down'
+ valueMapper={countMetricMapper}
+ />
+ <MetricCard
+ label='Organisations created'
+ value={totals.organisations.current}
+ change={
+ totals.organisations.current - totals.organisations.previous
+ }
+ goodChangeDirection='down'
+ valueMapper={countMetricMapper}
+ />
+ </motion.div>
+ <AdminChart
className='h-72'
- deps={[charts]}
+ series={[
+ {
+ id: 'signups',
+ name: 'Signups',
+ color: ADMIN_CHART_COLORS.blue,
+ data: charts.signups,
+ },
+ {
+ id: 'projects',
+ name: 'Projects created',
+ color: ADMIN_CHART_COLORS.amber,
+ data: charts.projects,
+ },
+ {
+ id: 'organisations',
+ name: 'Organisations created',
+ color: ADMIN_CHART_COLORS.purple,
+ data: charts.organisations,
+ },
+ ]}
/>
</div>
- <div className='rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>
+ <div className='relative rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>
<Text as='h3' size='lg' weight='semibold' className='mb-4'>
Events processed
</Text>
- <BillboardChart
- options={eventsOptions}
+ <motion.div
+ initial='hidden'
+ animate='visible'
+ variants={metricCardsContainerVariants}
+ className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'
+ >
+ <MetricCard
+ label={`Events (${chartDays}d)`}
+ value={totals.events.current}
+ change={totals.events.current - totals.events.previous}
+ goodChangeDirection='down'
+ valueMapper={countMetricMapper}
+ />
+ </motion.div>
+ <AdminChart
className='h-72'
- deps={[charts]}
+ series={[
+ {
+ id: 'events',
+ name: 'Events',
+ color: ADMIN_CHART_COLORS.teal,
+ data: charts.events,
+ },
+ ]}
/>
</div>
+ <ActivationFunnel funnel={charts.funnel} chartDays={chartDays} />
+
<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' className='mb-4'>
@@ -222,12 +350,7 @@ export const OverviewTab = ({
<div className='flex flex-col gap-2'>
{overview.planDistribution.map(({ planCode, count }) => (
<div key={planCode} className='flex items-center gap-3'>
- <Text
- as='span'
- size='sm'
- className='w-24 shrink-0 font-mono'
- truncate
- >
+ <Text as='span' size='sm' className='w-24 shrink-0' truncate>
{planCode}
</Text>
<div className='h-4 flex-1 overflow-hidden rounded-sm bg-gray-200 dark:bg-slate-800'>
@@ -255,6 +378,10 @@ export const OverviewTab = ({
</Text>
<dl className='grid grid-cols-2 gap-x-4 gap-y-3'>
{[
+ {
+ label: 'MRR (est., USD list price)',
+ value: `$${nLocaleFormatter(Math.round(overview.mrr.usdEquivalent))}`,
+ },
{
label: 'Verified users',
value: nLocaleFormatter(overview.users.active),
diff --git a/web/app/pages/Admin/ProjectsTab.tsx b/web/app/pages/Admin/ProjectsTab.tsx
index 25c98fe2d..b87d03234 100644
--- a/web/app/pages/Admin/ProjectsTab.tsx
+++ b/web/app/pages/Admin/ProjectsTab.tsx
@@ -1,4 +1,5 @@
-import { MagnifyingGlassIcon } from '@phosphor-icons/react'
+import { ArrowLeftIcon, MagnifyingGlassIcon } from '@phosphor-icons/react'
+import { Link } from 'react-router'
import { Badge } from '~/ui/Badge'
import Input from '~/ui/Input'
@@ -7,8 +8,24 @@ import Select from '~/ui/Select'
import { Text } from '~/ui/Text'
import { cn, nLocaleFormatter } from '~/utils/generic'
-import { AdminTable, EmptyState, formatDate, Td } from './components'
-import type { AdminProject, AdminProjectsList, AdminTopProjects } from './types'
+import { AdminChart, ADMIN_CHART_COLORS } from './AdminChart'
+import {
+ AdminTable,
+ EmptyState,
+ formatDate,
+ formatDateTime,
+ StatCard,
+ Td,
+ useAdminSort,
+} from './components'
+import { adminLinkClassName } from './UsersTab'
+import type {
+ AdminProject,
+ AdminProjectDetails,
+ AdminProjectsList,
+ AdminTopProjects,
+ SortState,
+} from './types'
const PROJECT_FILTERS = [
{ key: 'all', label: 'All projects' },
@@ -25,7 +42,22 @@ const TOP_PERIODS = [
{ key: 30, label: 'Last 30 days' },
]
-const ProjectBadges = ({ project }: { project: AdminProject }) => (
+const EVENT_TYPE_LABELS: Record<string, string> = {
+ pageview: 'Pageviews',
+ custom_event: 'Custom events',
+ error: 'Errors',
+ captcha: 'Captcha',
+ performance: 'Performance',
+}
+
+const ProjectBadges = ({
+ project,
+}: {
+ project: Pick<
+ AdminProject,
+ 'isArchived' | 'active' | 'public' | 'isPasswordProtected'
+ >
+}) => (
<span className='inline-flex items-center gap-1.5'>
{project.isArchived ? (
<Badge colour='slate' label='archived' size='sm' />
@@ -40,35 +72,283 @@ const ProjectBadges = ({ project }: { project: AdminProject }) => (
</span>
)
+const OwnerCell = ({
+ admin,
+}: {
+ admin: { id: string; email: string; planCode?: string } | null
+}) => {
+ if (!admin) {
+ return <>β€”</>
+ }
+
+ return (
+ <div>
+ <Link
+ to={`/admin?tab=users&user=${admin.id}`}
+ onClick={(e) => e.stopPropagation()}
+ className={adminLinkClassName}
+ >
+ {admin.email}
+ </Link>
+ {admin.planCode ? (
+ <span className='ml-2 text-xs text-gray-500 dark:text-gray-400'>
+ {admin.planCode}
+ </span>
+ ) : null}
+ </div>
+ )
+}
+
+const ProjectDetails = ({
+ details,
+ onBack,
+}: {
+ details: AdminProjectDetails
+ onBack: () => void
+}) => {
+ const { project, series, typeBreakdown, shares } = details
+
+ const infoRows: { label: string; value: React.ReactNode }[] = [
+ { label: 'ID', value: project.id },
+ { label: 'Created', value: formatDateTime(project.created) },
+ {
+ label: 'Owner',
+ value: <OwnerCell admin={project.admin} />,
+ },
+ {
+ label: 'Organisation',
+ value: project.organisation ? (
+ <Link
+ to={`/admin?tab=organisations&org=${project.organisation.id}`}
+ className={adminLinkClassName}
+ >
+ {project.organisation.name}
+ </Link>
+ ) : (
+ 'β€”'
+ ),
+ },
+ { label: 'Bots protection', value: project.botsProtectionLevel },
+ {
+ label: 'Allowed origins',
+ value: project.origins?.length ? project.origins.join(', ') : 'Any',
+ },
+ {
+ label: 'IP blacklist',
+ value: project.ipBlacklist?.length ? project.ipBlacklist.join(', ') : 'β€”',
+ },
+ ]
+
+ return (
+ <div className='flex flex-col gap-6'>
+ <div>
+ <button
+ type='button'
+ onClick={onBack}
+ className='inline-flex cursor-pointer items-center gap-1.5 text-sm font-medium text-gray-700 hover:text-gray-900 dark:text-gray-300 dark:hover:text-gray-50'
+ >
+ <ArrowLeftIcon className='size-4' />
+ Back to projects
+ </button>
+ <div className='mt-3 flex items-center gap-3'>
+ <Text as='h3' size='xl' weight='semibold'>
+ {project.name}
+ </Text>
+ <ProjectBadges project={project} />
+ </div>
+ </div>
+
+ <div className='grid grid-cols-1 gap-4 sm:grid-cols-3'>
+ <StatCard
+ label='Events (24h)'
+ value={nLocaleFormatter(project.events24h)}
+ />
+ <StatCard
+ label='Events (30d)'
+ value={nLocaleFormatter(project.events30d)}
+ />
+ <StatCard
+ label='Events (all-time)'
+ value={nLocaleFormatter(project.totalEvents)}
+ />
+ </div>
+
+ <div className='rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>
+ <Text as='h4' size='lg' weight='semibold' className='mb-4'>
+ Events, last 30 days
+ </Text>
+ {series.length === 0 ? (
+ <EmptyState message='No events in the last 30 days' />
+ ) : (
+ <AdminChart
+ className='h-64'
+ series={[
+ {
+ id: 'events',
+ name: 'Events',
+ color: ADMIN_CHART_COLORS.blue,
+ data: series,
+ },
+ ]}
+ />
+ )}
+ </div>
+
+ <dl className='grid grid-cols-1 gap-x-6 gap-y-3 rounded-lg border border-gray-200 bg-gray-50 p-4 sm:grid-cols-2 lg:grid-cols-3 dark:border-slate-800/60 dark:bg-slate-900/25'>
+ {infoRows.map(({ label, value }) => (
+ <div key={label}>
+ <dt>
+ <Text as='span' size='xs' colour='secondary'>
+ {label}
+ </Text>
+ </dt>
+ <dd className='text-sm text-gray-900 dark:text-gray-100'>
+ {value}
+ </dd>
+ </div>
+ ))}
+ </dl>
+
+ <div className='grid grid-cols-1 gap-6 lg:grid-cols-2'>
+ <div>
+ <Text as='h4' size='lg' weight='semibold' className='mb-3'>
+ Event types
+ </Text>
+ {typeBreakdown.length === 0 ? (
+ <EmptyState message='No events recorded' />
+ ) : (
+ <AdminTable
+ columns={[
+ { key: 'type', label: 'Type' },
+ { key: 'last30d', label: '30d' },
+ { key: 'total', label: 'All-time' },
+ ]}
+ >
+ {typeBreakdown.map(({ type, last30d, total }) => (
+ <tr key={type}>
+ <Td>{EVENT_TYPE_LABELS[type] || type}</Td>
+ <Td className='tabular-nums'>{nLocaleFormatter(last30d)}</Td>
+ <Td className='tabular-nums'>{nLocaleFormatter(total)}</Td>
+ </tr>
+ ))}
+ </AdminTable>
+ )}
+ </div>
+
+ <div>
+ <Text as='h4' size='lg' weight='semibold' className='mb-3'>
+ Shared with ({shares.length})
+ </Text>
+ {shares.length === 0 ? (
+ <EmptyState message='Not shared with anyone' />
+ ) : (
+ <AdminTable
+ columns={[
+ { key: 'user', label: 'User' },
+ { key: 'role', label: 'Role' },
+ { key: 'confirmed', label: 'Confirmed' },
+ { key: 'created', label: 'Shared' },
+ ]}
+ >
+ {shares.map((share) => (
+ <tr key={share.id}>
+ <Td>
+ {share.user ? (
+ <Link
+ to={`/admin?tab=users&user=${share.user.id}`}
+ className={adminLinkClassName}
+ >
+ {share.user.email}
+ </Link>
+ ) : (
+ 'β€”'
+ )}
+ </Td>
+ <Td>
+ <Badge colour='indigo' label={share.role} size='sm' />
+ </Td>
+ <Td>{share.confirmed ? 'Yes' : 'No'}</Td>
+ <Td>{formatDate(share.created)}</Td>
+ </tr>
+ ))}
+ </AdminTable>
+ )}
+ </div>
+ </div>
+ </div>
+ )
+}
+
interface ProjectsTabProps {
projects?: AdminProjectsList
topProjects?: AdminTopProjects
+ projectDetails?: AdminProjectDetails | null
view: 'list' | 'top'
page: number
search: string
filter: string
+ sort: SortState
topDays: number
onViewChange: (view: 'list' | 'top') => void
onPageChange: (page: number) => void
onSearchChange: (search: string) => void
onFilterChange: (filter: string) => void
+ onSortChange: (by: string, order: 'ASC' | 'DESC') => void
onTopDaysChange: (days: number) => void
+ onProjectSelect: (id: string | null) => void
}
export const ProjectsTab = ({
projects,
topProjects,
+ projectDetails,
view,
page,
search,
filter,
+ sort,
topDays,
onViewChange,
onPageChange,
onSearchChange,
onFilterChange,
+ onSortChange,
onTopDaysChange,
+ onProjectSelect,
}: ProjectsTabProps) => {
+ const listSort = useAdminSort<AdminProject>(
+ ['name', 'created'],
+ sort,
+ onSortChange,
+ {
+ events24h: (project) => project.events24h,
+ events30d: (project) => project.events30d,
+ totalEvents: (project) => project.totalEvents,
+ owner: (project) => project.admin?.email || null,
+ },
+ )
+
+ const topSort = useAdminSort<AdminTopProjects['projects'][number]>(
+ [],
+ { by: 'eventCount', order: 'DESC' },
+ () => {},
+ {
+ eventCount: (project) => project.eventCount,
+ name: (project) => project.name,
+ created: (project) => project.created,
+ owner: (project) => project.admin?.email || null,
+ },
+ )
+
+ if (projectDetails) {
+ return (
+ <ProjectDetails
+ details={projectDetails}
+ onBack={() => onProjectSelect(null)}
+ />
+ )
+ }
+
const selectedFilter =
PROJECT_FILTERS.find(({ key }) => key === filter) || PROJECT_FILTERS[0]
const selectedPeriod =
@@ -88,7 +368,7 @@ export const ProjectsTab = ({
type='button'
onClick={() => onViewChange(key)}
className={cn(
- 'rounded px-3 py-1.5 text-sm font-medium transition-colors',
+ 'cursor-pointer rounded px-3 py-1.5 text-sm font-medium transition-colors',
view === key
? 'bg-gray-100 text-gray-900 dark:bg-slate-800 dark:text-gray-50'
: 'text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-50',
@@ -101,7 +381,7 @@ export const ProjectsTab = ({
{view === 'list' && projects ? (
<>
- <div className='flex flex-col gap-3 sm:flex-row sm:items-center'>
+ <div className='flex flex-col gap-3 sm:flex-row sm:items-end'>
<Input
label='Search projects'
className='sm:max-w-xs sm:flex-1'
@@ -121,6 +401,7 @@ export const ProjectsTab = ({
keyExtractor={(item) => item.key}
selectedItem={selectedFilter}
onSelect={(item) => onFilterChange(item.key)}
+ menuClassName='w-max min-w-full'
/>
</div>
@@ -129,40 +410,57 @@ export const ProjectsTab = ({
) : (
<>
<AdminTable
- headers={[
- 'Project',
- 'Owner',
- 'Organisation',
- '24h events',
- '30d events',
- 'Total events',
- 'Created',
+ columns={[
+ { key: 'name', label: 'Project', sortable: true },
+ { key: 'owner', label: 'Owner', sortable: true },
+ { key: 'organisation', label: 'Organisation' },
+ { key: 'events24h', label: '24h events', sortable: true },
+ { key: 'events30d', label: '30d events', sortable: true },
+ { key: 'totalEvents', label: 'Total events', sortable: true },
+ { key: 'created', label: 'Created', sortable: true },
]}
+ sort={listSort.sort}
+ onSort={listSort.onSort}
>
- {projects.projects.map((project) => (
- <tr key={project.id}>
+ {listSort.sortRows(projects.projects).map((project) => (
+ <tr
+ key={project.id}
+ onClick={() => onProjectSelect(project.id)}
+ onKeyDown={(e) => {
+ if (e.target !== e.currentTarget) return
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault()
+ onProjectSelect(project.id)
+ }
+ }}
+ tabIndex={0}
+ className='cursor-pointer transition-colors hover:bg-gray-50 focus-visible:bg-gray-50 focus-visible:-outline-offset-2 dark:hover:bg-slate-900/60 dark:focus-visible:bg-slate-900/60'
+ >
<Td>
<div className='flex items-center gap-2'>
<span className='font-medium'>{project.name}</span>
<ProjectBadges project={project} />
</div>
- <span className='font-mono text-xs text-gray-500 dark:text-gray-400'>
+ <span className='text-xs text-gray-500 dark:text-gray-400'>
{project.id}
</span>
</Td>
<Td>
- {project.admin ? (
- <div>
- {project.admin.email}
- <span className='ml-2 font-mono text-xs text-gray-500 dark:text-gray-400'>
- {project.admin.planCode}
- </span>
- </div>
+ <OwnerCell admin={project.admin} />
+ </Td>
+ <Td>
+ {project.organisation ? (
+ <Link
+ to={`/admin?tab=organisations&org=${project.organisation.id}`}
+ onClick={(e) => e.stopPropagation()}
+ className={adminLinkClassName}
+ >
+ {project.organisation.name}
+ </Link>
) : (
'β€”'
)}
</Td>
- <Td>{project.organisation?.name || 'β€”'}</Td>
<Td className='tabular-nums'>
{nLocaleFormatter(project.events24h)}
</Td>
@@ -205,6 +503,7 @@ export const ProjectsTab = ({
keyExtractor={(item) => item.key.toString()}
selectedItem={selectedPeriod}
onSelect={(item) => onTopDaysChange(item.key)}
+ menuClassName='right-0 w-max min-w-full'
/>
</div>
@@ -212,10 +511,30 @@ export const ProjectsTab = ({
<EmptyState message='No events recorded in this period' />
) : (
<AdminTable
- headers={['#', 'Project', 'Owner', 'Events', 'Created']}
+ columns={[
+ { key: 'rank', label: '#' },
+ { key: 'name', label: 'Project', sortable: true },
+ { key: 'owner', label: 'Owner', sortable: true },
+ { key: 'eventCount', label: 'Events', sortable: true },
+ { key: 'created', label: 'Created', sortable: true },
+ ]}
+ sort={topSort.sort}
+ onSort={topSort.onSort}
>
- {topProjects.projects.map((project, index) => (
- <tr key={project.id}>
+ {topSort.sortRows(topProjects.projects).map((project, index) => (
+ <tr
+ key={project.id}
+ onClick={() => onProjectSelect(project.id)}
+ onKeyDown={(e) => {
+ if (e.target !== e.currentTarget) return
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault()
+ onProjectSelect(project.id)
+ }
+ }}
+ tabIndex={0}
+ className='cursor-pointer transition-colors hover:bg-gray-50 focus-visible:bg-gray-50 focus-visible:-outline-offset-2 dark:hover:bg-slate-900/60 dark:focus-visible:bg-slate-900/60'
+ >
<Td className='text-gray-500 tabular-nums dark:text-gray-400'>
{index + 1}
</Td>
@@ -223,21 +542,12 @@ export const ProjectsTab = ({
<span className='font-medium'>
{project.name || 'Unknown (deleted?)'}
</span>
- <span className='ml-2 font-mono text-xs text-gray-500 dark:text-gray-400'>
+ <span className='ml-2 text-xs text-gray-500 dark:text-gray-400'>
{project.id}
</span>
</Td>
<Td>
- {project.admin ? (
- <div>
- {project.admin.email}
- <span className='ml-2 font-mono text-xs text-gray-500 dark:text-gray-400'>
- {project.admin.planCode}
- </span>
- </div>
- ) : (
- 'β€”'
- )}
+ <OwnerCell admin={project.admin} />
</Td>
<Td className='font-medium tabular-nums'>
{nLocaleFormatter(project.eventCount)}
diff --git a/web/app/pages/Admin/UsersTab.tsx b/web/app/pages/Admin/UsersTab.tsx
index 72a92b190..7c648e470 100644
--- a/web/app/pages/Admin/UsersTab.tsx
+++ b/web/app/pages/Admin/UsersTab.tsx
@@ -1,6 +1,6 @@
import { ArrowLeftIcon, MagnifyingGlassIcon } from '@phosphor-icons/react'
import { useEffect, useState } from 'react'
-import { useFetcher } from 'react-router'
+import { Link, useFetcher } from 'react-router'
import { toast } from 'sonner'
import { Badge } from '~/ui/Badge'
@@ -10,7 +10,7 @@ import Pagination from '~/ui/Pagination'
import Select from '~/ui/Select'
import { Text } from '~/ui/Text'
import Textarea from '~/ui/Textarea'
-import { nFormatter, nLocaleFormatter } from '~/utils/generic'
+import { cn, nFormatter, nLocaleFormatter } from '~/utils/generic'
import {
AdminTable,
@@ -19,12 +19,14 @@ import {
formatDateTime,
Td,
UsageBar,
+ useAdminSort,
} from './components'
import type {
AdminActionData,
AdminUser,
AdminUserDetails,
AdminUsersList,
+ SortState,
} from './types'
const USER_FILTERS = [
@@ -37,9 +39,12 @@ const USER_FILTERS = [
{ key: 'blocked', label: 'Blocked / suspended' },
]
+export const adminLinkClassName =
+ 'font-medium text-indigo-600 hover:text-indigo-500 hover:underline dark:text-indigo-400 dark:hover:text-indigo-300'
+
const PlanCell = ({ user }: { user: AdminUser }) => (
<div className='flex items-center gap-1.5'>
- <span className='font-mono text-sm'>{user.planCode}</span>
+ <span className='text-sm'>{user.planCode}</span>
{user.planType === 'plus' ? (
<Badge colour='indigo' label='plus' size='sm' />
) : null}
@@ -190,6 +195,98 @@ const BillingControls = ({ user }: { user: AdminUser }) => {
)
}
+const formatLimitValue = (value: unknown): string => {
+ if (typeof value === 'number') {
+ return nLocaleFormatter(value)
+ }
+
+ if (value === null || value === undefined || value === '') {
+ return 'β€”'
+ }
+
+ return String(value)
+}
+
+// Human-readable rendering of getEffectiveAccountLimits() output, with a raw
+// JSON escape hatch
+const EffectiveLimits = ({ limits }: { limits: Record<string, unknown> }) => {
+ const [view, setView] = useState<'parsed' | 'json'>('parsed')
+
+ const rows: { label: string; value: string }[] = [
+ { label: 'Plan type', value: formatLimitValue(limits.effectivePlanType) },
+ {
+ label: 'Websites',
+ value: `${formatLimitValue(limits.effectiveProjectLimit)} (${formatLimitValue(limits.includedWebsites)} included + ${formatLimitValue(limits.purchasedWebsiteAddons)} add-ons)`,
+ },
+ {
+ label: 'Session replays / month',
+ value: `${formatLimitValue(limits.sessionReplaysIncluded)}${
+ Number(limits.purchasedSessionReplayAddons) > 0
+ ? ` (incl. ${formatLimitValue(limits.purchasedSessionReplayAddons)} add-ons)`
+ : ''
+ }`,
+ },
+ {
+ label: 'Replay retention',
+ value: `${formatLimitValue(limits.sessionReplayRetentionDays)} days`,
+ },
+ {
+ label: 'API requests / hour',
+ value: formatLimitValue(limits.apiRateLimitPerHour),
+ },
+ { label: 'Team members', value: formatLimitValue(limits.teamMembers) },
+ { label: 'Organisations', value: formatLimitValue(limits.organisations) },
+ ]
+
+ return (
+ <div className='rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>
+ <div className='flex items-center justify-between gap-3'>
+ <Text as='h4' size='lg' weight='semibold'>
+ Effective limits
+ </Text>
+ <div className='flex rounded-md border border-gray-200 p-0.5 dark:border-slate-800/60'>
+ {(['parsed', 'json'] as const).map((key) => (
+ <button
+ key={key}
+ type='button'
+ onClick={() => setView(key)}
+ className={cn(
+ 'rounded px-2.5 py-1 text-xs font-medium transition-colors',
+ view === key
+ ? 'bg-gray-100 text-gray-900 dark:bg-slate-800 dark:text-gray-50'
+ : 'text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-50',
+ )}
+ >
+ {key === 'parsed' ? 'Parsed' : 'JSON'}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {view === 'parsed' ? (
+ <dl className='mt-3 grid grid-cols-1 gap-x-6 gap-y-3 sm:grid-cols-2 lg:grid-cols-3'>
+ {rows.map(({ label, value }) => (
+ <div key={label}>
+ <dt>
+ <Text as='span' size='xs' colour='secondary'>
+ {label}
+ </Text>
+ </dt>
+ <dd className='text-sm text-gray-900 tabular-nums dark:text-gray-100'>
+ {value}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ ) : (
+ <pre className='mt-3 overflow-x-auto rounded-md bg-gray-100 p-3 font-mono text-xs leading-relaxed text-gray-800 dark:bg-slate-900 dark:text-gray-200'>
+ {JSON.stringify(limits, null, 2)}
+ </pre>
+ )}
+ </div>
+ )
+}
+
const UserDetails = ({
details,
onBack,
@@ -200,7 +297,7 @@ const UserDetails = ({
const { user, effectiveLimits, projects, memberships } = details
const infoRows: { label: string; value: React.ReactNode }[] = [
- { label: 'ID', value: <span className='font-mono'>{user.id}</span> },
+ { label: 'ID', value: user.id },
{ label: 'Email', value: user.email },
{ label: 'Nickname', value: user.nickname || 'β€”' },
{ label: 'Registered', value: formatDateTime(user.created) },
@@ -216,14 +313,6 @@ const UserDetails = ({
label: 'Monthly events',
value: `${nLocaleFormatter(user.monthlyEvents)}${user.monthlyUsageLimit ? ` / ${nLocaleFormatter(user.monthlyUsageLimit)}` : ''}`,
},
- {
- label: 'Effective limits',
- value: (
- <span className='font-mono text-xs break-all whitespace-normal'>
- {JSON.stringify(effectiveLimits)}
- </span>
- ),
- },
]
return (
@@ -232,7 +321,7 @@ const UserDetails = ({
<button
type='button'
onClick={onBack}
- className='inline-flex items-center gap-1.5 text-sm font-medium text-gray-700 hover:text-gray-900 dark:text-gray-300 dark:hover:text-gray-50'
+ className='inline-flex cursor-pointer items-center gap-1.5 text-sm font-medium text-gray-700 hover:text-gray-900 dark:text-gray-300 dark:hover:text-gray-50'
>
<ArrowLeftIcon className='size-4' />
Back to users
@@ -260,6 +349,8 @@ const UserDetails = ({
))}
</dl>
+ <EffectiveLimits limits={effectiveLimits} />
+
<BillingControls key={user.id} user={user} />
<div>
@@ -270,27 +361,41 @@ const UserDetails = ({
<EmptyState message='No projects' />
) : (
<AdminTable
- headers={[
- 'Name',
- 'Organisation',
- '24h events',
- '30d events',
- 'Total events',
- 'Created',
- '',
+ columns={[
+ { key: 'name', label: 'Name' },
+ { key: 'organisation', label: 'Organisation' },
+ { key: 'events24h', label: '24h events' },
+ { key: 'events30d', label: '30d events' },
+ { key: 'totalEvents', label: 'Total events' },
+ { key: 'created', label: 'Created' },
+ { key: 'badges', label: '' },
]}
>
{projects.map((project) => (
<tr key={project.id}>
<Td>
- <div>
- <span className='font-medium'>{project.name}</span>
- <span className='ml-2 font-mono text-xs text-gray-500 dark:text-gray-400'>
- {project.id}
- </span>
- </div>
+ <Link
+ to={`/admin?tab=projects&project=${project.id}`}
+ className={adminLinkClassName}
+ >
+ {project.name}
+ </Link>
+ <span className='ml-2 text-xs text-gray-500 dark:text-gray-400'>
+ {project.id}
+ </span>
+ </Td>
+ <Td>
+ {project.organisation ? (
+ <Link
+ to={`/admin?tab=organisations&org=${project.organisation.id}`}
+ className={adminLinkClassName}
+ >
+ {project.organisation.name}
+ </Link>
+ ) : (
+ 'β€”'
+ )}
</Td>
- <Td>{project.organisation?.name || 'β€”'}</Td>
<Td className='tabular-nums'>
{nLocaleFormatter(project.events24h)}
</Td>
@@ -319,10 +424,28 @@ const UserDetails = ({
{memberships.length === 0 ? (
<EmptyState message='No organisation memberships' />
) : (
- <AdminTable headers={['Organisation', 'Role', 'Confirmed', 'Joined']}>
+ <AdminTable
+ columns={[
+ { key: 'organisation', label: 'Organisation' },
+ { key: 'role', label: 'Role' },
+ { key: 'confirmed', label: 'Confirmed' },
+ { key: 'created', label: 'Joined' },
+ ]}
+ >
{memberships.map((membership) => (
<tr key={membership.id}>
- <Td>{membership.organisation?.name || 'β€”'}</Td>
+ <Td>
+ {membership.organisation ? (
+ <Link
+ to={`/admin?tab=organisations&org=${membership.organisation.id}`}
+ className={adminLinkClassName}
+ >
+ {membership.organisation.name}
+ </Link>
+ ) : (
+ 'β€”'
+ )}
+ </Td>
<Td>
<Badge colour='indigo' label={membership.role} size='sm' />
</Td>
@@ -343,9 +466,11 @@ interface UsersTabProps {
page: number
search: string
filter: string
+ sort: SortState
onPageChange: (page: number) => void
onSearchChange: (search: string) => void
onFilterChange: (filter: string) => void
+ onSortChange: (by: string, order: 'ASC' | 'DESC') => void
onUserSelect: (id: string | null) => void
}
@@ -355,11 +480,27 @@ export const UsersTab = ({
page,
search,
filter,
+ sort,
onPageChange,
onSearchChange,
onFilterChange,
+ onSortChange,
onUserSelect,
}: UsersTabProps) => {
+ const {
+ sort: activeSort,
+ onSort,
+ sortRows,
+ } = useAdminSort<AdminUser>(
+ ['email', 'planCode', 'created'],
+ sort,
+ onSortChange,
+ {
+ projectCount: (user) => user.projectCount,
+ monthlyEvents: (user) => user.monthlyEvents,
+ },
+ )
+
if (userDetails) {
return (
<UserDetails details={userDetails} onBack={() => onUserSelect(null)} />
@@ -369,9 +510,11 @@ export const UsersTab = ({
const selectedFilter =
USER_FILTERS.find(({ key }) => key === filter) || USER_FILTERS[0]
+ const rows = sortRows(users.users)
+
return (
<div className='flex flex-col gap-4'>
- <div className='flex flex-col gap-3 sm:flex-row sm:items-center'>
+ <div className='flex flex-col gap-3 sm:flex-row sm:items-end'>
<Input
label='Search users'
className='sm:max-w-xs sm:flex-1'
@@ -389,6 +532,7 @@ export const UsersTab = ({
keyExtractor={(item) => item.key}
selectedItem={selectedFilter}
onSelect={(item) => onFilterChange(item.key)}
+ menuClassName='w-max min-w-full'
/>
</div>
@@ -397,15 +541,17 @@ export const UsersTab = ({
) : (
<>
<AdminTable
- headers={[
- 'Email',
- 'Plan',
- 'Projects',
- 'Monthly events',
- 'Registered',
+ columns={[
+ { key: 'email', label: 'Email', sortable: true },
+ { key: 'planCode', label: 'Plan', sortable: true },
+ { key: 'projectCount', label: 'Projects', sortable: true },
+ { key: 'monthlyEvents', label: 'Monthly events', sortable: true },
+ { key: 'created', label: 'Registered', sortable: true },
]}
+ sort={activeSort}
+ onSort={onSort}
>
- {users.users.map((user) => (
+ {rows.map((user) => (
<tr
key={user.id}
onClick={() => onUserSelect(user.id)}
diff --git a/web/app/pages/Admin/components.tsx b/web/app/pages/Admin/components.tsx
index ecb4700e8..87ee95efa 100644
--- a/web/app/pages/Admin/components.tsx
+++ b/web/app/pages/Admin/components.tsx
@@ -1,8 +1,12 @@
+import { CaretDownIcon, CaretUpIcon } from '@phosphor-icons/react'
import dayjs from 'dayjs'
-import type { ReactNode } from 'react'
+import { useState, type ReactNode } from 'react'
+import { Badge } from '~/ui/Badge'
import { Text } from '~/ui/Text'
-import { cn } from '~/utils/generic'
+import { cn, nFormatter } from '~/utils/generic'
+
+import type { SortState } from './types'
export const formatBytes = (bytes: number): string => {
if (!Number.isFinite(bytes) || bytes <= 0) {
@@ -24,14 +28,41 @@ export const formatDate = (date: string | null): string =>
export const formatDateTime = (date: string | null): string =>
date ? dayjs(date).format('MMM D, YYYY HH:mm') : 'β€”'
+// Positive change is green (growth is good in every admin metric), negative is
+// red, zero is neutral
+export const ChangeBadge = ({
+ change,
+ formatter = (value: number) => nFormatter(Math.abs(value), 1),
+}: {
+ change: number | null | undefined
+ formatter?: (value: number) => string
+}) => {
+ if (change === null || change === undefined || Number.isNaN(change)) {
+ return null
+ }
+
+ if (change === 0) {
+ return <Badge colour='slate' label='Β±0' />
+ }
+
+ return (
+ <Badge
+ colour={change > 0 ? 'green' : 'red'}
+ label={`${change > 0 ? '+' : '-'}${formatter(change)}`}
+ />
+ )
+}
+
export const StatCard = ({
label,
value,
+ badge,
hint,
children,
}: {
label: string
value: ReactNode
+ badge?: ReactNode
hint?: ReactNode
children?: ReactNode
}) => (
@@ -39,9 +70,12 @@ export const StatCard = ({
<Text as='p' size='sm' colour='secondary'>
{label}
</Text>
- <Text as='p' size='2xl' weight='bold' className='mt-1 tabular-nums'>
- {value}
- </Text>
+ <div className='mt-1 flex items-center gap-2'>
+ <Text as='p' size='2xl' weight='bold' className='tabular-nums'>
+ {value}
+ </Text>
+ {badge}
+ </div>
{hint ? (
<Text as='p' size='xs' colour='secondary' className='mt-1'>
{hint}
@@ -51,12 +85,80 @@ export const StatCard = ({
</div>
)
+export interface AdminColumn {
+ key: string
+ label: ReactNode
+ sortable?: boolean
+}
+
+// Shared sorting state for admin tables. Columns whose key is in `serverKeys`
+// sort the whole dataset through the loader; everything else sorts the rows of
+// the current page locally (the computed columns live in ClickHouse and can't
+// be sorted by MySQL).
+export const useAdminSort = <Row,>(
+ serverKeys: string[],
+ serverSort: SortState,
+ onServerSort: (by: string, order: 'ASC' | 'DESC') => void,
+ accessors: Record<string, (row: Row) => string | number | null>,
+) => {
+ const [clientSort, setClientSort] = useState<SortState | null>(null)
+
+ const sort = clientSort ?? serverSort
+
+ const onSort = (key: string) => {
+ const nextOrder: 'ASC' | 'DESC' =
+ sort.by === key && sort.order === 'DESC' ? 'ASC' : 'DESC'
+
+ if (serverKeys.includes(key)) {
+ setClientSort(null)
+ onServerSort(key, nextOrder)
+ } else {
+ setClientSort({ by: key, order: nextOrder })
+ }
+ }
+
+ const sortRows = (rows: Row[]): Row[] => {
+ if (!clientSort) {
+ return rows
+ }
+
+ const accessor = accessors[clientSort.by]
+
+ if (!accessor) {
+ return rows
+ }
+
+ const sorted = [...rows].sort((a, b) => {
+ const aValue = accessor(a)
+ const bValue = accessor(b)
+
+ if (aValue === bValue) return 0
+ if (aValue === null || aValue === undefined) return 1
+ if (bValue === null || bValue === undefined) return -1
+
+ if (typeof aValue === 'number' && typeof bValue === 'number') {
+ return aValue - bValue
+ }
+
+ return String(aValue).localeCompare(String(bValue))
+ })
+
+ return clientSort.order === 'DESC' ? sorted.reverse() : sorted
+ }
+
+ return { sort, onSort, sortRows }
+}
+
export const AdminTable = ({
- headers,
+ columns,
+ sort,
+ onSort,
children,
className,
}: {
- headers: ReactNode[]
+ columns: AdminColumn[]
+ sort?: SortState
+ onSort?: (key: string) => void
children: ReactNode
className?: string
}) => (
@@ -69,15 +171,48 @@ export const AdminTable = ({
<table className='min-w-full divide-y divide-gray-200 dark:divide-slate-800/60'>
<thead className='bg-gray-50 dark:bg-slate-900/50'>
<tr>
- {headers.map((header, index) => (
- <th
- key={index}
- scope='col'
- className='px-3 py-2.5 text-left text-xs font-semibold whitespace-nowrap text-gray-500 uppercase dark:text-gray-400'
- >
- {header}
- </th>
- ))}
+ {columns.map((column) => {
+ const isSorted = sort?.by === column.key
+ const isSortable = Boolean(column.sortable && onSort)
+
+ return (
+ <th
+ key={column.key}
+ scope='col'
+ aria-sort={
+ isSorted
+ ? sort?.order === 'ASC'
+ ? 'ascending'
+ : 'descending'
+ : undefined
+ }
+ className='px-3 py-2.5 text-left text-xs font-semibold whitespace-nowrap text-gray-500 uppercase dark:text-gray-400'
+ >
+ {isSortable ? (
+ <button
+ type='button'
+ onClick={() => onSort?.(column.key)}
+ className='group inline-flex cursor-pointer items-center gap-1 uppercase hover:text-gray-900 dark:hover:text-gray-100'
+ >
+ {column.label}
+ <span
+ className={cn('transition-opacity', {
+ 'opacity-0 group-hover:opacity-60': !isSorted,
+ })}
+ >
+ {isSorted && sort?.order === 'ASC' ? (
+ <CaretUpIcon weight='bold' className='size-3' />
+ ) : (
+ <CaretDownIcon weight='bold' className='size-3' />
+ )}
+ </span>
+ </button>
+ ) : (
+ column.label
+ )}
+ </th>
+ )
+ })}
</tr>
</thead>
<tbody className='divide-y divide-gray-200 bg-white dark:divide-slate-800/60 dark:bg-slate-950'>
diff --git a/web/app/pages/Admin/index.tsx b/web/app/pages/Admin/index.tsx
index 6ca5f3378..7d5534cbe 100644
--- a/web/app/pages/Admin/index.tsx
+++ b/web/app/pages/Admin/index.tsx
@@ -1,32 +1,37 @@
import {
BuildingsIcon,
ChartLineUpIcon,
+ ChatCircleTextIcon,
+ CreditCardIcon,
DatabaseIcon,
GlobeIcon,
+ RobotIcon,
UsersIcon,
} from '@phosphor-icons/react'
import _debounce from 'lodash/debounce'
import { useMemo, useRef } from 'react'
import { useLoaderData, useNavigation, useSearchParams } from 'react-router'
+import type { SettingsTabConfig } from '~/pages/Project/Settings/SettingsSidebar'
import type {
- SettingsTabConfig,
- SettingsTabGroup,
-} from '~/pages/Project/Settings/SettingsSidebar'
-import SettingsSidebar from '~/pages/Project/Settings/SettingsSidebar'
-import type { AdminLoaderData, AdminTab } from '~/pages/Admin/types'
+ AdminFeedbackType,
+ AdminLoaderData,
+ AdminTab,
+ SortState,
+} from '~/pages/Admin/types'
import Select from '~/ui/Select'
import { Text } from '~/ui/Text'
import { cn } from '~/utils/generic'
+import { BillingTab } from './BillingTab'
+import { BotBlocksTab } from './BotBlocksTab'
import { DatabaseTab } from './DatabaseTab'
+import { FeedbackTab } from './FeedbackTab'
import { OrganisationsTab } from './OrganisationsTab'
import { OverviewTab } from './OverviewTab'
import { ProjectsTab } from './ProjectsTab'
import { UsersTab } from './UsersTab'
-const SIDEBAR_STORAGE_KEY = 'admin-sidebar-groups'
-
const TABS: SettingsTabConfig<AdminTab>[] = [
{
id: 'overview',
@@ -36,6 +41,14 @@ const TABS: SettingsTabConfig<AdminTab>[] = [
iconColor: 'text-blue-500',
visible: true,
},
+ {
+ id: 'billing',
+ label: 'Billing',
+ description: 'Trials, churn risk and payments',
+ icon: CreditCardIcon,
+ iconColor: 'text-teal-500',
+ visible: true,
+ },
{
id: 'users',
label: 'Users',
@@ -60,6 +73,22 @@ const TABS: SettingsTabConfig<AdminTab>[] = [
iconColor: 'text-purple-500',
visible: true,
},
+ {
+ id: 'feedback',
+ label: 'Feedback',
+ description: 'What users say when they stay or leave',
+ icon: ChatCircleTextIcon,
+ iconColor: 'text-pink-500',
+ visible: true,
+ },
+ {
+ id: 'bot-blocks',
+ label: 'Bot blocks',
+ description: 'Why events get dropped',
+ icon: RobotIcon,
+ iconColor: 'text-orange-500',
+ visible: true,
+ },
{
id: 'database',
label: 'Database',
@@ -70,13 +99,53 @@ const TABS: SettingsTabConfig<AdminTab>[] = [
},
]
-const TAB_GROUPS: SettingsTabGroup<AdminTab>[] = [
- {
- id: 'admin',
- label: 'Admin',
- tabIds: ['overview', 'users', 'projects', 'organisations', 'database'],
- },
-]
+// Flat tab list (same look as the settings sidebar buttons, minus the
+// collapsible group wrapper)
+const AdminSidebar = ({
+ activeTab,
+ onTabChange,
+}: {
+ activeTab: AdminTab
+ onTabChange: (tab: AdminTab) => void
+}) => (
+ <nav className='flex flex-col gap-0.5' aria-label='Admin sections'>
+ {TABS.map((tab) => {
+ const TabIcon = tab.icon
+ const isCurrent = tab.id === activeTab
+
+ return (
+ <button
+ key={tab.id}
+ type='button'
+ onClick={() => onTabChange(tab.id)}
+ className={cn(
+ 'flex cursor-pointer items-center gap-1.5 rounded-md px-2.5 py-2 text-left transition-colors',
+ {
+ 'bg-gray-100 dark:bg-slate-900': isCurrent,
+ 'hover:bg-gray-100 dark:hover:bg-slate-900/60': !isCurrent,
+ },
+ )}
+ aria-current={isCurrent ? 'page' : undefined}
+ >
+ <TabIcon
+ className={cn('size-4 shrink-0', tab.iconColor)}
+ weight='duotone'
+ aria-hidden='true'
+ />
+ <Text
+ as='span'
+ size='sm'
+ weight='medium'
+ truncate
+ className='max-w-full'
+ >
+ {tab.label}
+ </Text>
+ </button>
+ )
+ })}
+ </nav>
+)
const AdminPage = () => {
const data = useLoaderData<AdminLoaderData>()
@@ -127,6 +196,8 @@ const AdminPage = () => {
next.delete('page')
next.delete('user')
+ next.delete('project')
+ next.delete('org')
return next
},
@@ -140,6 +211,15 @@ const AdminPage = () => {
const search = searchParams.get('search') || ''
const filter = searchParams.get('filter') || 'all'
+ const sort: SortState = {
+ by: searchParams.get('sortBy') || 'created',
+ order: searchParams.get('order') === 'ASC' ? 'ASC' : 'DESC',
+ }
+
+ const onSortChange = (by: string, order: 'ASC' | 'DESC') => {
+ updateParams({ sortBy: by, order, page: null })
+ }
+
const isNavigating = navigation.state === 'loading'
const selectedTabConfig = TABS.find(({ id }) => id === activeTab) || TABS[0]
@@ -166,13 +246,7 @@ const AdminPage = () => {
</div>
<aside className='hidden w-56 shrink-0 md:block'>
- <SettingsSidebar
- tabs={TABS}
- activeTab={activeTab}
- onTabChange={onTabChange}
- groups={TAB_GROUPS}
- storageKey={SIDEBAR_STORAGE_KEY}
- />
+ <AdminSidebar activeTab={activeTab} onTabChange={onTabChange} />
</aside>
<section
@@ -185,12 +259,24 @@ const AdminPage = () => {
overview={data.overview}
charts={data.charts}
chartDays={data.chartDays || 30}
+ revenue={data.revenue}
onChartDaysChange={(days) =>
updateParams({ days: days.toString() })
}
/>
) : null}
+ {activeTab === 'billing' && data.billing ? (
+ <BillingTab billing={data.billing} />
+ ) : null}
+
+ {activeTab === 'bot-blocks' && data.botBlocks ? (
+ <BotBlocksTab
+ botBlocks={data.botBlocks}
+ onDaysChange={(days) => updateParams({ days: days.toString() })}
+ />
+ ) : null}
+
{activeTab === 'users' && data.users ? (
<UsersTab
users={data.users}
@@ -198,6 +284,7 @@ const AdminPage = () => {
page={page}
search={search}
filter={filter}
+ sort={sort}
onPageChange={(newPage) =>
updateParams({ page: newPage.toString(), user: null })
}
@@ -205,6 +292,7 @@ const AdminPage = () => {
onFilterChange={(newFilter) =>
updateParams({ filter: newFilter, page: null, user: null })
}
+ onSortChange={onSortChange}
onUserSelect={(id) => updateParams({ user: id })}
/>
) : null}
@@ -213,10 +301,12 @@ const AdminPage = () => {
<ProjectsTab
projects={data.projects}
topProjects={data.topProjects}
+ projectDetails={data.projectDetails || null}
view={searchParams.get('view') === 'top' ? 'top' : 'list'}
page={page}
search={search}
filter={filter}
+ sort={sort}
topDays={Number(searchParams.get('days')) || 7}
onViewChange={(view) =>
updateParams({
@@ -225,30 +315,69 @@ const AdminPage = () => {
search: null,
filter: null,
days: null,
+ project: null,
})
}
onPageChange={(newPage) =>
- updateParams({ page: newPage.toString() })
+ updateParams({ page: newPage.toString(), project: null })
}
onSearchChange={onSearchChange}
onFilterChange={(newFilter) =>
- updateParams({ filter: newFilter, page: null })
+ updateParams({ filter: newFilter, page: null, project: null })
}
+ onSortChange={onSortChange}
onTopDaysChange={(days) =>
updateParams({ days: days.toString() })
}
+ onProjectSelect={(id) => updateParams({ project: id })}
/>
) : null}
{activeTab === 'organisations' && data.organisations ? (
<OrganisationsTab
organisations={data.organisations}
+ organisationDetails={data.organisationDetails || null}
page={page}
search={search}
+ sort={sort}
+ onPageChange={(newPage) =>
+ updateParams({ page: newPage.toString(), org: null })
+ }
+ onSearchChange={onSearchChange}
+ onSortChange={onSortChange}
+ onOrganisationSelect={(id) => updateParams({ org: id })}
+ />
+ ) : null}
+
+ {activeTab === 'feedback' && data.feedback ? (
+ <FeedbackTab
+ feedback={data.feedback}
+ type={
+ (['user', 'cancellation', 'deletion'].includes(
+ searchParams.get('type') || '',
+ )
+ ? searchParams.get('type')
+ : 'user') as AdminFeedbackType
+ }
+ page={page}
+ search={search}
+ order={sort.order}
+ onTypeChange={(type) =>
+ updateParams({
+ type: type === 'user' ? null : type,
+ page: null,
+ })
+ }
onPageChange={(newPage) =>
updateParams({ page: newPage.toString() })
}
onSearchChange={onSearchChange}
+ onOrderChange={(order) =>
+ updateParams({
+ order: order === 'DESC' ? null : order,
+ page: null,
+ })
+ }
/>
) : null}
diff --git a/web/app/pages/Admin/types.ts b/web/app/pages/Admin/types.ts
index 18ab11c63..25039e927 100644
--- a/web/app/pages/Admin/types.ts
+++ b/web/app/pages/Admin/types.ts
@@ -1,10 +1,107 @@
export type AdminTab =
| 'overview'
+ | 'billing'
| 'users'
| 'projects'
| 'organisations'
+ | 'feedback'
+ | 'bot-blocks'
| 'database'
+export interface AdminBillingUser {
+ id: string
+ email: string
+ planCode: string
+ planType: string | null
+ billingFrequency: string | null
+ created: string
+ trialEndDate: string | null
+ nextBillDate: string | null
+ cancellationEffectiveDate: string | null
+ dashboardBlockReason: string | null
+ isAccountBillingSuspended: boolean
+ monthlyRevenueUsd: number | null
+}
+
+export interface AdminPayment {
+ id: number
+ date: string
+ amount: number
+ currency: string
+ isOneOff: boolean
+ receiptUrl: string | null
+ subscriptionId: number
+ user: { id: string; email: string; planCode: string } | null
+}
+
+export interface AdminBilling {
+ trialsEndingSoon: (AdminBillingUser & {
+ projectCount: number
+ monthlyEvents: number
+ })[]
+ cancellationPipeline: AdminBillingUser[]
+ suspended: AdminBillingUser[]
+ churnRisk: {
+ atRisk: (AdminBillingUser & {
+ events30d: number
+ eventsPrev30d: number
+ dropPercent: number
+ })[]
+ analyzed: number
+ }
+ payments: {
+ available: boolean
+ recent: AdminPayment[]
+ upcoming: AdminPayment[]
+ fetchedAt?: string
+ }
+}
+
+export interface AdminBotBlocks {
+ days: number
+ totals: { total: number; last24h: number }
+ byReason: { reason: string; count: number }[]
+ series: { date: string; reason: string; count: number }[]
+ topProjects: {
+ id: string
+ name: string | null
+ botsProtectionLevel: string | null
+ admin: { id: string; email: string } | null
+ blocked: number
+ accepted: number
+ blockRatio: number
+ topReason: string | null
+ }[]
+}
+
+interface AdminActivationFunnel {
+ signups: number
+ verified: number
+ createdProject: number
+ sentData: number
+ paid: number
+}
+
+export type AdminFeedbackType = 'user' | 'cancellation' | 'deletion'
+
+export interface AdminFeedbackItem {
+ id: string
+ message: string | null
+ createdAt: string
+ attachmentUrls?: string[]
+ email?: string | null
+ planCode?: string | null
+ userId?: string
+ user?: { id: string; email: string; planCode: string } | null
+}
+
+export interface AdminFeedbackList {
+ total: number
+ pageSize: number
+ items: AdminFeedbackItem[]
+ counts: { user: number; cancellation: number; deletion: number }
+}
+
export interface SeriesPoint {
date: string
count: number
@@ -21,6 +118,7 @@ export interface AdminOverview {
signups24h: number
signups7d: number
signups30d: number
+ signupsPrev30d: number
}
projects: {
total: number
@@ -34,6 +132,7 @@ export interface AdminOverview {
last24h: number
last7d: number
last30d: number
+ prev30d: number
}
mrr: {
byCurrency: { USD: number; EUR: number; GBP: number }
@@ -44,11 +143,45 @@ export interface AdminOverview {
planDistribution: { planCode: string; count: number }[]
}
+interface RevenueBucket {
+ byCurrency: Record<string, number>
+ approxUsd: number
+ payments: number
+ oneOffPayments: number
+ payers: number
+}
+
+export interface AdminRevenue {
+ available: boolean
+ currentMonth?: RevenueBucket
+ previousMonth?: RevenueBucket
+ previousMonthToDate?: RevenueBucket
+ upcoming?: RevenueBucket
+ fetchedAt?: string
+}
+
+interface WindowTotals {
+ current: number
+ previous: number
+}
+
export interface AdminCharts {
signups: SeriesPoint[]
projects: SeriesPoint[]
organisations: SeriesPoint[]
events: SeriesPoint[]
+ totals: {
+ signups: WindowTotals
+ projects: WindowTotals
+ organisations: WindowTotals
+ events: WindowTotals
+ }
+ funnel: AdminActivationFunnel
+}
+
+export interface SortState {
+ by: string
+ order: 'ASC' | 'DESC'
}
export interface AdminUser {
@@ -141,6 +274,50 @@ export interface AdminTopProjects {
projects: AdminTopProject[]
}
+export interface AdminProjectDetails {
+ project: AdminProject & {
+ origins: string[] | null
+ ipBlacklist: string[] | null
+ }
+ series: SeriesPoint[]
+ typeBreakdown: { type: string; last30d: number; total: number }[]
+ shares: {
+ id: string
+ role: string
+ confirmed: boolean
+ created: string
+ user: { id: string; email: string } | null
+ }[]
+}
+
+export interface AdminOrganisationDetails {
+ organisation: {
+ id: string
+ name: string
+ created: string
+ memberCount: number
+ projectCount: number
+ }
+ members: {
+ id: string
+ role: string
+ confirmed: boolean
+ created: string
+ user: { id: string; email: string } | null
+ }[]
+ projects: {
+ id: string
+ name: string
+ active: boolean
+ isArchived: boolean
+ created: string
+ admin: { id: string; email: string } | null
+ events24h: number
+ events30d: number
+ totalEvents: number
+ }[]
+}
+
interface AdminOrganisation {
id: string
name: string
@@ -198,10 +375,16 @@ export interface AdminLoaderData {
overview?: AdminOverview
charts?: AdminCharts
chartDays?: number
+ revenue?: AdminRevenue | null
users?: AdminUsersList
userDetails?: AdminUserDetails | null
projects?: AdminProjectsList
topProjects?: AdminTopProjects
+ projectDetails?: AdminProjectDetails | null
organisations?: AdminOrganisationsList
+ organisationDetails?: AdminOrganisationDetails | null
+ feedback?: AdminFeedbackList
+ billing?: AdminBilling
+ botBlocks?: AdminBotBlocks
database?: AdminDatabaseInfo
}
diff --git a/web/app/routes/admin.tsx b/web/app/routes/admin.tsx
index 260e72f19..91b1db216 100644
--- a/web/app/routes/admin.tsx
+++ b/web/app/routes/admin.tsx
@@ -13,12 +13,18 @@ import AdminPage from '~/pages/Admin'
import NotFound from '~/pages/NotFound'
import type {
AdminActionData,
+ AdminBilling,
+ AdminBotBlocks,
AdminCharts,
AdminDatabaseInfo,
+ AdminFeedbackList,
AdminLoaderData,
+ AdminOrganisationDetails,
AdminOrganisationsList,
AdminOverview,
+ AdminProjectDetails,
AdminProjectsList,
+ AdminRevenue,
AdminTab,
AdminTopProjects,
AdminUserDetails,
@@ -49,9 +55,12 @@ export const sitemap: SitemapFunction = () => ({
const TABS: AdminTab[] = [
'overview',
+ 'billing',
'users',
'projects',
'organisations',
+ 'feedback',
+ 'bot-blocks',
'database',
]
@@ -117,12 +126,32 @@ export async function loader({ request }: LoaderFunctionArgs) {
? Number(searchParams.get('days'))
: 30
- const [overview, charts] = await Promise.all([
+ const [overview, charts, revenue] = await Promise.all([
adminFetch<AdminOverview>('admin/overview'),
adminFetch<AdminCharts>(`admin/charts?days=${chartDays}`),
+ // Paddle can be slow/unavailable - the page still renders without it
+ adminFetch<AdminRevenue>('admin/revenue').catch(() => null),
])
- return { tab, overview, charts, chartDays }
+ return { tab, overview, charts, chartDays, revenue }
+ }
+
+ if (tab === 'billing') {
+ const billing = await adminFetch<AdminBilling>('admin/billing')
+
+ return { tab, billing }
+ }
+
+ if (tab === 'bot-blocks') {
+ const days = [7, 30, 90].includes(Number(searchParams.get('days')))
+ ? Number(searchParams.get('days'))
+ : 7
+
+ const botBlocks = await adminFetch<AdminBotBlocks>(
+ `admin/bot-blocks?days=${days}`,
+ )
+
+ return { tab, botBlocks }
}
if (tab === 'users') {
@@ -141,6 +170,16 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
if (tab === 'projects') {
+ const projectId = searchParams.get('project')
+
+ if (projectId) {
+ const projectDetails = await adminFetch<AdminProjectDetails>(
+ `admin/projects/${encodeURIComponent(projectId)}`,
+ ).catch(() => null)
+
+ return { tab, projectDetails }
+ }
+
if (searchParams.get('view') === 'top') {
const days = [1, 7, 30].includes(Number(searchParams.get('days')))
? Number(searchParams.get('days'))
@@ -161,11 +200,39 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
if (tab === 'organisations') {
- const organisations = await adminFetch<AdminOrganisationsList>(
- `admin/organisations?${listParams}`,
+ const organisationId = searchParams.get('org')
+
+ const [organisations, organisationDetails] = await Promise.all([
+ adminFetch<AdminOrganisationsList>(`admin/organisations?${listParams}`),
+ organisationId
+ ? adminFetch<AdminOrganisationDetails>(
+ `admin/organisations/${encodeURIComponent(organisationId)}`,
+ ).catch(() => null)
+ : Promise.resolve(null),
+ ])
+
+ return { tab, organisations, organisationDetails }
+ }
+
+ if (tab === 'feedback') {
+ const type = ['user', 'cancellation', 'deletion'].includes(
+ searchParams.get('type') || '',
+ )
+ ? searchParams.get('type')
+ : 'user'
+
+ const feedbackParams = new URLSearchParams({
+ type: type as string,
+ page,
+ search,
+ order,
+ }).toString()
+
+ const feedback = await adminFetch<AdminFeedbackList>(
+ `admin/feedback?${feedbackParams}`,
)
- return { tab, organisations }
+ return { tab, feedback }
}
const database = await adminFetch<AdminDatabaseInfo>('admin/database')
diff --git a/web/app/ui/Select.tsx b/web/app/ui/Select.tsx
index 693155c5b..b4e9be036 100644
--- a/web/app/ui/Select.tsx
+++ b/web/app/ui/Select.tsx
@@ -21,6 +21,8 @@ interface SelectProps<T> {
labelClassName?: string
buttonClassName?: string
hintClassName?: string
+ /** Overrides the options panel sizing/positioning classes (defaults to `w-full`) */
+ menuClassName?: string
capitalise?: boolean
items: readonly T[]
id?: string
@@ -55,6 +57,7 @@ function Select<T>({
fieldLabelClassName,
selectedItem,
hintClassName,
+ menuClassName,
wrap,
disabled,
}: SelectProps<T>) {
@@ -157,7 +160,10 @@ function Select<T>({
<ListboxOptions
modal={false}
transition
- className='absolute z-30 mt-1.5 max-h-72 w-full origin-top-left overflow-auto rounded-lg bg-white py-1 text-sm shadow-lg ring-1 ring-gray-200/80 transition-[opacity,transform] duration-150 ease-out-quint focus:outline-hidden data-closed:scale-95 data-closed:opacity-0 data-leave:duration-100 dark:bg-slate-950 dark:ring-slate-700/60'
+ className={cx(
+ 'absolute z-30 mt-1.5 max-h-72 origin-top-left overflow-auto rounded-lg bg-white py-1 text-sm shadow-lg ring-1 ring-gray-200/80 transition-[opacity,transform] duration-150 ease-out-quint focus:outline-hidden data-closed:scale-95 data-closed:opacity-0 data-leave:duration-100 dark:bg-slate-950 dark:ring-slate-700/60',
+ menuClassName || 'w-full',
+ )}
>
{_map(items, (item, index) => {
const selected = isItemSelected(item)