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!

Observability improvements

Blue Mouse53aeed0cd570
diff --git a/admin/src/commands/InactiveProjectsCommand.tsx b/admin/src/commands/InactiveProjectsCommand.tsx
new file mode 100644
index 000000000..4c41f1c13
--- /dev/null
+++ b/admin/src/commands/InactiveProjectsCommand.tsx
@@ -0,0 +1,188 @@
+import React, { useState, useEffect } from 'react'
+import { Box, Text, useInput } from 'ink'
+import SelectInput from 'ink-select-input'
+import { Spinner } from '../components/Spinner.js'
+import { getProjectsWithRecentEvents, getProjectEventCount } from '../db/clickhouse.js'
+import { AppDataSource, Project } from '../db/mysql.js'
+
+interface InactiveProjectsCommandProps {
+ onBack: () => void
+}
+
+type Period = '30d' | '60d' | '90d'
+type Mode = 'list' | 'detail'
+
+const periodDays: Record<Period, number> = {
+ '30d': 30,
+ '60d': 60,
+ '90d': 90,
+}
+
+interface InactiveProject extends Project {
+ adminEmail?: string
+ lastEventDays?: number
+}
+
+export function InactiveProjectsCommand({ onBack }: InactiveProjectsCommandProps) {
+ const [mode, setMode] = useState<Mode>('list')
+ const [loading, setLoading] = useState(true)
+ const [period, setPeriod] = useState<Period>('30d')
+ const [projects, setProjects] = useState<InactiveProject[]>([])
+ const [selectedProject, setSelectedProject] = useState<Project | null>(null)
+ const [eventCount, setEventCount] = useState<number>(0)
+ const [error, setError] = useState<string | null>(null)
+
+ useInput((input, key) => {
+ if (key.escape) {
+ if (mode === 'detail') {
+ setMode('list')
+ setSelectedProject(null)
+ } else {
+ onBack()
+ }
+ }
+ if (mode === 'list') {
+ if (input === '1') setPeriod('30d')
+ if (input === '2') setPeriod('60d')
+ if (input === '3') setPeriod('90d')
+ }
+ })
+
+ useEffect(() => {
+ loadInactiveProjects()
+ }, [period])
+
+ async function loadInactiveProjects() {
+ setLoading(true)
+ setError(null)
+ try {
+ const activeProjectPids = await getProjectsWithRecentEvents(periodDays[period])
+
+ const projectRepo = AppDataSource.getRepository(Project)
+ const allProjects = await projectRepo
+ .createQueryBuilder('project')
+ .leftJoinAndSelect('project.admin', 'admin')
+ .where('project.isArchived = :archived', { archived: false })
+ .orderBy('project.created', 'DESC')
+ .getMany()
+
+ const inactiveProjects: InactiveProject[] = allProjects
+ .filter(p => !activeProjectPids.has(p.id))
+ .map(p => ({
+ ...p,
+ adminEmail: p.admin?.email || 'N/A',
+ }))
+ .slice(0, 50)
+
+ setProjects(inactiveProjects)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load inactive projects')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ async function loadProjectDetails(project: Project) {
+ setLoading(true)
+ try {
+ const count = await getProjectEventCount(project.id)
+ setEventCount(count)
+ setSelectedProject(project)
+ setMode('detail')
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load project details')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ if (loading) {
+ return <Spinner text="Finding inactive projects..." />
+ }
+
+ if (error) {
+ return (
+ <Box flexDirection="column">
+ <Text color="red">Error: {error}</Text>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ )
+ }
+
+ if (mode === 'detail' && selectedProject) {
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">πŸ“ Project Details</Text>
+
+ <Box flexDirection="column" marginTop={1}>
+ <Text><Text color="cyan">ID:</Text> {selectedProject.id}</Text>
+ <Text><Text color="cyan">Name:</Text> {selectedProject.name}</Text>
+ <Text>
+ <Text color="cyan">Status:</Text>{' '}
+ <Text color={selectedProject.active ? 'green' : 'red'}>
+ {selectedProject.active ? 'Active' : 'Inactive'}
+ </Text>
+ </Text>
+ <Text><Text color="cyan">Website URL:</Text> {selectedProject.origins?.[0] || 'Not set'}</Text>
+ <Text><Text color="cyan">Created:</Text> {new Date(selectedProject.created).toLocaleString()}</Text>
+ <Text><Text color="cyan">Owner:</Text> {selectedProject.admin?.email || 'N/A'}</Text>
+ <Text>
+ <Text color="cyan">Total Events (all time):</Text>{' '}
+ <Text color="yellow">{eventCount.toLocaleString()}</Text>
+ </Text>
+ <Text color="red" bold>
+ ⚠️ No events in the last {periodDays[period]} days
+ </Text>
+ </Box>
+
+ <Box marginTop={1}>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ </Box>
+ )
+ }
+
+ const projectItems = projects.map(p => ({
+ label: `[${p.id}] ${p.name} - ${p.adminEmail}`,
+ value: p.id,
+ }))
+
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">πŸ’€ Inactive/Zombie Projects</Text>
+
+ <Box marginTop={1} marginBottom={1}>
+ <Text>
+ No events in:{' '}
+ <Text color={period === '30d' ? 'green' : 'gray'} bold={period === '30d'}>[1] 30 days</Text>
+ {' | '}
+ <Text color={period === '60d' ? 'green' : 'gray'} bold={period === '60d'}>[2] 60 days</Text>
+ {' | '}
+ <Text color={period === '90d' ? 'green' : 'gray'} bold={period === '90d'}>[3] 90 days</Text>
+ </Text>
+ </Box>
+
+ <Box marginBottom={1}>
+ <Text color="gray">Found {projects.length} inactive projects (showing first 50)</Text>
+ </Box>
+
+ {projects.length === 0 ? (
+ <Text color="green">No inactive projects found!</Text>
+ ) : (
+ <Box flexDirection="column">
+ <SelectInput
+ items={projectItems}
+ onSelect={(item) => {
+ const project = projects.find(p => p.id === item.value)
+ if (project) loadProjectDetails(project)
+ }}
+ />
+ </Box>
+ )}
+
+ <Box marginTop={1}>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ </Box>
+ )
+}
diff --git a/admin/src/commands/LimitsCommand.tsx b/admin/src/commands/LimitsCommand.tsx
new file mode 100644
index 000000000..e83848a43
--- /dev/null
+++ b/admin/src/commands/LimitsCommand.tsx
@@ -0,0 +1,211 @@
+import React, { useState, useEffect } from 'react'
+import { Box, Text, useInput } from 'ink'
+import SelectInput from 'ink-select-input'
+import { Spinner } from '../components/Spinner.js'
+import { AppDataSource, User, Project, OrganisationMember } from '../db/mysql.js'
+
+interface LimitsCommandProps {
+ onBack: () => void
+}
+
+type Mode = 'list' | 'detail'
+
+interface UserWithLimits extends User {
+ projectCount: number
+ usagePercent: number
+}
+
+export function LimitsCommand({ onBack }: LimitsCommandProps) {
+ const [mode, setMode] = useState<Mode>('list')
+ const [loading, setLoading] = useState(true)
+ const [users, setUsers] = useState<UserWithLimits[]>([])
+ const [selectedUser, setSelectedUser] = useState<User | null>(null)
+ const [userProjects, setUserProjects] = useState<Project[]>([])
+ const [userOrgs, setUserOrgs] = useState<OrganisationMember[]>([])
+ const [error, setError] = useState<string | null>(null)
+ const [threshold, setThreshold] = useState<number>(80)
+
+ useInput((input, key) => {
+ if (key.escape) {
+ if (mode === 'detail') {
+ setMode('list')
+ setSelectedUser(null)
+ } else {
+ onBack()
+ }
+ }
+ if (mode === 'list') {
+ if (input === '1') setThreshold(50)
+ if (input === '2') setThreshold(80)
+ if (input === '3') setThreshold(90)
+ }
+ })
+
+ useEffect(() => {
+ loadUsersApproachingLimits()
+ }, [threshold])
+
+ async function loadUsersApproachingLimits() {
+ setLoading(true)
+ setError(null)
+ try {
+ const userRepo = AppDataSource.getRepository(User)
+
+ const usersWithCounts = await userRepo
+ .createQueryBuilder('user')
+ .loadRelationCountAndMap('user.projectCount', 'user.projects')
+ .where('user.isActive = :active', { active: true })
+ .orderBy('user.created', 'DESC')
+ .getMany()
+
+ const usersApproaching: UserWithLimits[] = (usersWithCounts as (User & { projectCount: number })[])
+ .map(user => ({
+ ...user,
+ projectCount: user.projectCount || 0,
+ usagePercent: user.maxProjects > 0
+ ? Math.round((user.projectCount / user.maxProjects) * 100)
+ : 0,
+ }))
+ .filter(user => user.usagePercent >= threshold)
+ .sort((a, b) => b.usagePercent - a.usagePercent)
+ .slice(0, 50)
+
+ setUsers(usersApproaching)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load users')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ async function loadUserDetails(user: User) {
+ setLoading(true)
+ try {
+ const projectRepo = AppDataSource.getRepository(Project)
+ const projects = await projectRepo.find({
+ where: { admin: { id: user.id } },
+ order: { created: 'DESC' },
+ take: 10,
+ })
+ setUserProjects(projects)
+
+ const memberRepo = AppDataSource.getRepository(OrganisationMember)
+ const orgs = await memberRepo.find({
+ where: { user: { id: user.id } },
+ relations: ['organisation'],
+ })
+ setUserOrgs(orgs)
+
+ setSelectedUser(user)
+ setMode('detail')
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load user details')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ if (loading) {
+ return <Spinner text="Loading users approaching limits..." />
+ }
+
+ if (error) {
+ return (
+ <Box flexDirection="column">
+ <Text color="red">Error: {error}</Text>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ )
+ }
+
+ if (mode === 'detail' && selectedUser) {
+ const userWithLimits = users.find(u => u.id === selectedUser.id)
+
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">πŸ‘€ User Details</Text>
+
+ <Box flexDirection="column" marginTop={1} marginBottom={1}>
+ <Text><Text color="cyan">ID:</Text> {selectedUser.id}</Text>
+ <Text><Text color="cyan">Email:</Text> {selectedUser.email}</Text>
+ <Text><Text color="cyan">Nickname:</Text> {selectedUser.nickname || 'N/A'}</Text>
+ <Text><Text color="cyan">Plan:</Text> {selectedUser.planCode}</Text>
+ <Text>
+ <Text color="cyan">Projects:</Text>{' '}
+ <Text color={userWithLimits && userWithLimits.usagePercent >= 90 ? 'red' : 'yellow'} bold>
+ {userWithLimits?.projectCount || 0} / {selectedUser.maxProjects}
+ </Text>
+ <Text color="gray"> ({userWithLimits?.usagePercent || 0}%)</Text>
+ </Text>
+ <Text><Text color="cyan">Created:</Text> {new Date(selectedUser.created).toLocaleString()}</Text>
+ {selectedUser.trialEndDate && (
+ <Text>
+ <Text color="cyan">Trial Ends:</Text>{' '}
+ {new Date(selectedUser.trialEndDate).toLocaleString()}
+ </Text>
+ )}
+ </Box>
+
+ {userProjects.length > 0 && (
+ <Box flexDirection="column">
+ <Text bold>Recent Projects:</Text>
+ {userProjects.slice(0, 5).map(p => (
+ <Text key={p.id} color="gray"> β€’ [{p.id}] {p.name}</Text>
+ ))}
+ </Box>
+ )}
+
+ <Box marginTop={1}>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ </Box>
+ )
+ }
+
+ const userItems = users.map(user => {
+ const color = user.usagePercent >= 100 ? 'red' : user.usagePercent >= 90 ? 'yellow' : 'white'
+ return {
+ label: `${user.email} (${user.planCode}) - ${user.projectCount}/${user.maxProjects} projects (${user.usagePercent}%)`,
+ value: user.id,
+ }
+ })
+
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">⚠️ Users Approaching Limits</Text>
+
+ <Box marginTop={1} marginBottom={1}>
+ <Text>
+ Threshold:{' '}
+ <Text color={threshold === 50 ? 'green' : 'gray'} bold={threshold === 50}>[1] 50%+</Text>
+ {' | '}
+ <Text color={threshold === 80 ? 'green' : 'gray'} bold={threshold === 80}>[2] 80%+</Text>
+ {' | '}
+ <Text color={threshold === 90 ? 'green' : 'gray'} bold={threshold === 90}>[3] 90%+</Text>
+ </Text>
+ </Box>
+
+ <Box marginBottom={1}>
+ <Text color="gray">Found {users.length} users at {threshold}%+ capacity</Text>
+ </Box>
+
+ {users.length === 0 ? (
+ <Text color="gray">No users approaching this limit</Text>
+ ) : (
+ <Box flexDirection="column">
+ <SelectInput
+ items={userItems}
+ onSelect={(item) => {
+ const user = users.find(u => u.id === item.value)
+ if (user) loadUserDetails(user)
+ }}
+ />
+ </Box>
+ )}
+
+ <Box marginTop={1}>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ </Box>
+ )
+}
diff --git a/admin/src/commands/RecentActivityCommand.tsx b/admin/src/commands/RecentActivityCommand.tsx
new file mode 100644
index 000000000..d268581f2
--- /dev/null
+++ b/admin/src/commands/RecentActivityCommand.tsx
@@ -0,0 +1,270 @@
+import React, { useState, useEffect } from 'react'
+import { Box, Text, useInput } from 'ink'
+import SelectInput from 'ink-select-input'
+import { Spinner } from '../components/Spinner.js'
+import { AppDataSource, User, Project, OrganisationMember } from '../db/mysql.js'
+import { getProjectEventCount } from '../db/clickhouse.js'
+
+interface RecentActivityCommandProps {
+ onBack: () => void
+}
+
+type Tab = 'users' | 'projects'
+type Mode = 'list' | 'user-detail' | 'project-detail'
+
+export function RecentActivityCommand({ onBack }: RecentActivityCommandProps) {
+ const [mode, setMode] = useState<Mode>('list')
+ const [tab, setTab] = useState<Tab>('users')
+ const [loading, setLoading] = useState(true)
+ const [recentUsers, setRecentUsers] = useState<User[]>([])
+ const [recentProjects, setRecentProjects] = useState<Project[]>([])
+ const [error, setError] = useState<string | null>(null)
+
+ const [selectedUser, setSelectedUser] = useState<User | null>(null)
+ const [userProjects, setUserProjects] = useState<Project[]>([])
+ const [userOrgs, setUserOrgs] = useState<OrganisationMember[]>([])
+
+ const [selectedProject, setSelectedProject] = useState<Project | null>(null)
+ const [projectEventCount, setProjectEventCount] = useState<number>(0)
+
+ useInput((input, key) => {
+ if (key.escape) {
+ if (mode === 'user-detail' || mode === 'project-detail') {
+ setMode('list')
+ setSelectedUser(null)
+ setSelectedProject(null)
+ } else {
+ onBack()
+ }
+ }
+ if (mode === 'list') {
+ if (input === '1') setTab('users')
+ if (input === '2') setTab('projects')
+ }
+ })
+
+ useEffect(() => {
+ loadRecentActivity()
+ }, [])
+
+ async function loadRecentActivity() {
+ setLoading(true)
+ setError(null)
+ try {
+ const userRepo = AppDataSource.getRepository(User)
+ const users = await userRepo.find({
+ order: { created: 'DESC' },
+ take: 20,
+ })
+ setRecentUsers(users)
+
+ const projectRepo = AppDataSource.getRepository(Project)
+ const projects = await projectRepo.find({
+ relations: ['admin'],
+ order: { created: 'DESC' },
+ take: 20,
+ })
+ setRecentProjects(projects)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load recent activity')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ async function loadUserDetails(user: User) {
+ setLoading(true)
+ try {
+ const projectRepo = AppDataSource.getRepository(Project)
+ const projects = await projectRepo.find({
+ where: { admin: { id: user.id } },
+ order: { created: 'DESC' },
+ take: 10,
+ })
+ setUserProjects(projects)
+
+ const memberRepo = AppDataSource.getRepository(OrganisationMember)
+ const orgs = await memberRepo.find({
+ where: { user: { id: user.id } },
+ relations: ['organisation'],
+ })
+ setUserOrgs(orgs)
+
+ setSelectedUser(user)
+ setMode('user-detail')
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load user details')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ async function loadProjectDetails(project: Project) {
+ setLoading(true)
+ try {
+ const count = await getProjectEventCount(project.id)
+ setProjectEventCount(count)
+ setSelectedProject(project)
+ setMode('project-detail')
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load project details')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ function formatTimeAgo(date: Date): string {
+ const now = new Date()
+ const diffMs = now.getTime() - new Date(date).getTime()
+ const diffMins = Math.floor(diffMs / 60000)
+ const diffHours = Math.floor(diffMs / 3600000)
+ const diffDays = Math.floor(diffMs / 86400000)
+
+ if (diffMins < 60) return `${diffMins}m ago`
+ if (diffHours < 24) return `${diffHours}h ago`
+ if (diffDays < 7) return `${diffDays}d ago`
+ return new Date(date).toLocaleDateString()
+ }
+
+ if (loading) {
+ return <Spinner text="Loading recent activity..." />
+ }
+
+ if (error) {
+ return (
+ <Box flexDirection="column">
+ <Text color="red">Error: {error}</Text>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ )
+ }
+
+ if (mode === 'user-detail' && selectedUser) {
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">πŸ‘€ User Details</Text>
+
+ <Box flexDirection="column" marginTop={1} marginBottom={1}>
+ <Text><Text color="cyan">ID:</Text> {selectedUser.id}</Text>
+ <Text><Text color="cyan">Email:</Text> {selectedUser.email}</Text>
+ <Text><Text color="cyan">Nickname:</Text> {selectedUser.nickname || 'N/A'}</Text>
+ <Text>
+ <Text color="cyan">Status:</Text>{' '}
+ <Text color={selectedUser.isActive ? 'green' : 'red'}>
+ {selectedUser.isActive ? 'Active' : 'Inactive'}
+ </Text>
+ </Text>
+ <Text><Text color="cyan">Plan:</Text> {selectedUser.planCode}</Text>
+ <Text><Text color="cyan">Created:</Text> {new Date(selectedUser.created).toLocaleString()}</Text>
+ <Text><Text color="cyan">Projects:</Text> {userProjects.length}</Text>
+ {selectedUser.trialEndDate && (
+ <Text>
+ <Text color="cyan">Trial Ends:</Text>{' '}
+ {new Date(selectedUser.trialEndDate).toLocaleString()}
+ </Text>
+ )}
+ </Box>
+
+ {userProjects.length > 0 && (
+ <Box flexDirection="column">
+ <Text bold>Projects:</Text>
+ {userProjects.slice(0, 5).map(p => (
+ <Text key={p.id} color="gray"> β€’ [{p.id}] {p.name}</Text>
+ ))}
+ </Box>
+ )}
+
+ <Box marginTop={1}>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ </Box>
+ )
+ }
+
+ if (mode === 'project-detail' && selectedProject) {
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">πŸ“ Project Details</Text>
+
+ <Box flexDirection="column" marginTop={1}>
+ <Text><Text color="cyan">ID:</Text> {selectedProject.id}</Text>
+ <Text><Text color="cyan">Name:</Text> {selectedProject.name}</Text>
+ <Text>
+ <Text color="cyan">Status:</Text>{' '}
+ <Text color={selectedProject.active ? 'green' : 'red'}>
+ {selectedProject.active ? 'Active' : 'Inactive'}
+ </Text>
+ </Text>
+ <Text><Text color="cyan">Website URL:</Text> {selectedProject.origins?.[0] || 'Not set'}</Text>
+ <Text><Text color="cyan">Created:</Text> {new Date(selectedProject.created).toLocaleString()}</Text>
+ <Text><Text color="cyan">Owner:</Text> {selectedProject.admin?.email || 'N/A'}</Text>
+ <Text>
+ <Text color="cyan">Total Events:</Text>{' '}
+ <Text color="green" bold>{projectEventCount.toLocaleString()}</Text>
+ </Text>
+ </Box>
+
+ <Box marginTop={1}>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ </Box>
+ )
+ }
+
+ const userItems = recentUsers.map(user => ({
+ label: `${formatTimeAgo(user.created)} - ${user.email} (${user.planCode}) ${user.isActive ? '' : '[inactive]'}`,
+ value: user.id,
+ }))
+
+ const projectItems = recentProjects.map(project => ({
+ label: `${formatTimeAgo(project.created)} - [${project.id}] ${project.name} (${project.admin?.email || 'N/A'})`,
+ value: project.id,
+ }))
+
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">πŸ“ˆ Recent Activity</Text>
+
+ <Box marginTop={1} marginBottom={1}>
+ <Text>
+ View:{' '}
+ <Text color={tab === 'users' ? 'green' : 'gray'} bold={tab === 'users'}>[1] Recent Signups</Text>
+ {' | '}
+ <Text color={tab === 'projects' ? 'green' : 'gray'} bold={tab === 'projects'}>[2] New Projects</Text>
+ </Text>
+ </Box>
+
+ {tab === 'users' ? (
+ <Box flexDirection="column">
+ <Box marginBottom={1}>
+ <Text color="gray">Last 20 signups:</Text>
+ </Box>
+ <SelectInput
+ items={userItems}
+ onSelect={(item) => {
+ const user = recentUsers.find(u => u.id === item.value)
+ if (user) loadUserDetails(user)
+ }}
+ />
+ </Box>
+ ) : (
+ <Box flexDirection="column">
+ <Box marginBottom={1}>
+ <Text color="gray">Last 20 projects created:</Text>
+ </Box>
+ <SelectInput
+ items={projectItems}
+ onSelect={(item) => {
+ const project = recentProjects.find(p => p.id === item.value)
+ if (project) loadProjectDetails(project)
+ }}
+ />
+ </Box>
+ )}
+
+ <Box marginTop={1}>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ </Box>
+ )
+}
diff --git a/admin/src/commands/SearchCommand.tsx b/admin/src/commands/SearchCommand.tsx
new file mode 100644
index 000000000..f4421e683
--- /dev/null
+++ b/admin/src/commands/SearchCommand.tsx
@@ -0,0 +1,323 @@
+import React, { useState } from 'react'
+import { Box, Text, useInput } from 'ink'
+import TextInput from 'ink-text-input'
+import SelectInput from 'ink-select-input'
+import { Spinner } from '../components/Spinner.js'
+import { AppDataSource, User, Project, Organisation, OrganisationMember } from '../db/mysql.js'
+import { getProjectEventCount } from '../db/clickhouse.js'
+
+interface SearchCommandProps {
+ onBack: () => void
+}
+
+type Mode = 'input' | 'results' | 'user-detail' | 'project-detail' | 'org-detail'
+
+interface SearchResult {
+ type: 'user' | 'project' | 'org'
+ id: string
+ label: string
+ data: User | Project | Organisation
+}
+
+export function SearchCommand({ onBack }: SearchCommandProps) {
+ const [mode, setMode] = useState<Mode>('input')
+ const [loading, setLoading] = useState(false)
+ const [searchQuery, setSearchQuery] = useState('')
+ const [results, setResults] = useState<SearchResult[]>([])
+ const [error, setError] = useState<string | null>(null)
+
+ const [selectedUser, setSelectedUser] = useState<User | null>(null)
+ const [userProjects, setUserProjects] = useState<Project[]>([])
+ const [userOrgs, setUserOrgs] = useState<OrganisationMember[]>([])
+
+ const [selectedProject, setSelectedProject] = useState<Project | null>(null)
+ const [projectEventCount, setProjectEventCount] = useState<number>(0)
+
+ const [selectedOrg, setSelectedOrg] = useState<Organisation | null>(null)
+ const [orgMembers, setOrgMembers] = useState<OrganisationMember[]>([])
+
+ useInput((input, key) => {
+ if (key.escape) {
+ if (mode === 'user-detail' || mode === 'project-detail' || mode === 'org-detail') {
+ setMode('results')
+ } else if (mode === 'results') {
+ setMode('input')
+ setResults([])
+ } else {
+ onBack()
+ }
+ }
+ })
+
+ async function performSearch() {
+ if (!searchQuery.trim()) return
+
+ setLoading(true)
+ setError(null)
+ setResults([])
+
+ try {
+ const query = searchQuery.trim().toLowerCase()
+ const searchResults: SearchResult[] = []
+
+ const userRepo = AppDataSource.getRepository(User)
+ const users = await userRepo
+ .createQueryBuilder('user')
+ .where('LOWER(user.email) LIKE :query', { query: `%${query}%` })
+ .orWhere('LOWER(user.id) LIKE :query', { query: `%${query}%` })
+ .orWhere('LOWER(user.nickname) LIKE :query', { query: `%${query}%` })
+ .take(10)
+ .getMany()
+
+ users.forEach(user => {
+ searchResults.push({
+ type: 'user',
+ id: user.id,
+ label: `πŸ‘€ User: ${user.email} (${user.planCode})`,
+ data: user,
+ })
+ })
+
+ const projectRepo = AppDataSource.getRepository(Project)
+ const projects = await projectRepo
+ .createQueryBuilder('project')
+ .leftJoinAndSelect('project.admin', 'admin')
+ .where('LOWER(project.name) LIKE :query', { query: `%${query}%` })
+ .orWhere('LOWER(project.id) LIKE :query', { query: `%${query}%` })
+ .take(10)
+ .getMany()
+
+ projects.forEach(project => {
+ searchResults.push({
+ type: 'project',
+ id: project.id,
+ label: `πŸ“ Project: [${project.id}] ${project.name}`,
+ data: project,
+ })
+ })
+
+ const orgRepo = AppDataSource.getRepository(Organisation)
+ const orgs = await orgRepo
+ .createQueryBuilder('org')
+ .leftJoinAndSelect('org.members', 'members')
+ .leftJoinAndSelect('org.projects', 'projects')
+ .where('LOWER(org.name) LIKE :query', { query: `%${query}%` })
+ .orWhere('LOWER(org.id) LIKE :query', { query: `%${query}%` })
+ .take(10)
+ .getMany()
+
+ orgs.forEach(org => {
+ searchResults.push({
+ type: 'org',
+ id: org.id,
+ label: `🏒 Org: ${org.name} (${org.members?.length || 0} members)`,
+ data: org,
+ })
+ })
+
+ setResults(searchResults)
+ setMode('results')
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Search failed')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ async function handleSelectResult(item: { value: string }) {
+ const result = results.find(r => `${r.type}-${r.id}` === item.value)
+ if (!result) return
+
+ setLoading(true)
+ try {
+ if (result.type === 'user') {
+ const user = result.data as User
+ const projectRepo = AppDataSource.getRepository(Project)
+ const projects = await projectRepo.find({
+ where: { admin: { id: user.id } },
+ order: { created: 'DESC' },
+ take: 10,
+ })
+ setUserProjects(projects)
+
+ const memberRepo = AppDataSource.getRepository(OrganisationMember)
+ const orgs = await memberRepo.find({
+ where: { user: { id: user.id } },
+ relations: ['organisation'],
+ })
+ setUserOrgs(orgs)
+
+ setSelectedUser(user)
+ setMode('user-detail')
+ } else if (result.type === 'project') {
+ const project = result.data as Project
+ const count = await getProjectEventCount(project.id)
+ setProjectEventCount(count)
+ setSelectedProject(project)
+ setMode('project-detail')
+ } else if (result.type === 'org') {
+ const org = result.data as Organisation
+ const memberRepo = AppDataSource.getRepository(OrganisationMember)
+ const members = await memberRepo.find({
+ where: { organisation: { id: org.id } },
+ relations: ['user'],
+ })
+ setOrgMembers(members)
+ setSelectedOrg(org)
+ setMode('org-detail')
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load details')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ if (loading) {
+ return <Spinner text="Searching..." />
+ }
+
+ if (error) {
+ return (
+ <Box flexDirection="column">
+ <Text color="red">Error: {error}</Text>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ )
+ }
+
+ if (mode === 'user-detail' && selectedUser) {
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">πŸ‘€ User Details</Text>
+
+ <Box flexDirection="column" marginTop={1} marginBottom={1}>
+ <Text><Text color="cyan">ID:</Text> {selectedUser.id}</Text>
+ <Text><Text color="cyan">Email:</Text> {selectedUser.email}</Text>
+ <Text><Text color="cyan">Nickname:</Text> {selectedUser.nickname || 'N/A'}</Text>
+ <Text>
+ <Text color="cyan">Status:</Text>{' '}
+ <Text color={selectedUser.isActive ? 'green' : 'red'}>
+ {selectedUser.isActive ? 'Active' : 'Inactive'}
+ </Text>
+ </Text>
+ <Text><Text color="cyan">Plan:</Text> {selectedUser.planCode}</Text>
+ <Text><Text color="cyan">Projects:</Text> {userProjects.length}</Text>
+ <Text><Text color="cyan">Organizations:</Text> {userOrgs.length}</Text>
+ </Box>
+
+ <Box marginTop={1}>
+ <Text color="gray">Press ESC to go back to results</Text>
+ </Box>
+ </Box>
+ )
+ }
+
+ if (mode === 'project-detail' && selectedProject) {
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">πŸ“ Project Details</Text>
+
+ <Box flexDirection="column" marginTop={1}>
+ <Text><Text color="cyan">ID:</Text> {selectedProject.id}</Text>
+ <Text><Text color="cyan">Name:</Text> {selectedProject.name}</Text>
+ <Text>
+ <Text color="cyan">Status:</Text>{' '}
+ <Text color={selectedProject.active ? 'green' : 'red'}>
+ {selectedProject.active ? 'Active' : 'Inactive'}
+ </Text>
+ </Text>
+ <Text><Text color="cyan">Website URL:</Text> {selectedProject.origins?.[0] || 'Not set'}</Text>
+ <Text><Text color="cyan">Owner:</Text> {selectedProject.admin?.email || 'N/A'}</Text>
+ <Text>
+ <Text color="cyan">Total Events:</Text>{' '}
+ <Text color="green" bold>{projectEventCount.toLocaleString()}</Text>
+ </Text>
+ </Box>
+
+ <Box marginTop={1}>
+ <Text color="gray">Press ESC to go back to results</Text>
+ </Box>
+ </Box>
+ )
+ }
+
+ if (mode === 'org-detail' && selectedOrg) {
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">🏒 Organization Details</Text>
+
+ <Box flexDirection="column" marginTop={1}>
+ <Text><Text color="cyan">ID:</Text> {selectedOrg.id}</Text>
+ <Text><Text color="cyan">Name:</Text> {selectedOrg.name}</Text>
+ <Text><Text color="cyan">Created:</Text> {new Date(selectedOrg.created).toLocaleString()}</Text>
+ <Text><Text color="cyan">Members:</Text> {orgMembers.length}</Text>
+ <Text><Text color="cyan">Projects:</Text> {selectedOrg.projects?.length || 0}</Text>
+ </Box>
+
+ {orgMembers.length > 0 && (
+ <Box flexDirection="column" marginTop={1}>
+ <Text bold>Members:</Text>
+ {orgMembers.slice(0, 5).map(m => (
+ <Text key={m.id} color="gray"> β€’ {m.user?.email} ({m.role})</Text>
+ ))}
+ </Box>
+ )}
+
+ <Box marginTop={1}>
+ <Text color="gray">Press ESC to go back to results</Text>
+ </Box>
+ </Box>
+ )
+ }
+
+ if (mode === 'results') {
+ const resultItems = results.map(r => ({
+ label: r.label,
+ value: `${r.type}-${r.id}`,
+ }))
+
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">πŸ” Search Results for "{searchQuery}"</Text>
+
+ <Box marginTop={1} marginBottom={1}>
+ <Text color="gray">Found {results.length} results</Text>
+ </Box>
+
+ {results.length === 0 ? (
+ <Text color="gray">No results found</Text>
+ ) : (
+ <SelectInput items={resultItems} onSelect={handleSelectResult} />
+ )}
+
+ <Box marginTop={1}>
+ <Text color="gray">Press ESC to search again</Text>
+ </Box>
+ </Box>
+ )
+ }
+
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">πŸ” Global Search</Text>
+
+ <Box marginTop={1}>
+ <Text>Search: </Text>
+ <TextInput
+ value={searchQuery}
+ onChange={setSearchQuery}
+ onSubmit={performSearch}
+ placeholder="Enter email, project ID, name, org..."
+ />
+ </Box>
+
+ <Box marginTop={1}>
+ <Text color="gray">Searches across users, projects, and organizations</Text>
+ </Box>
+ <Box>
+ <Text color="gray">Press Enter to search, ESC to go back</Text>
+ </Box>
+ </Box>
+ )
+}
diff --git a/admin/src/commands/TopProjectsCommand.tsx b/admin/src/commands/TopProjectsCommand.tsx
new file mode 100644
index 000000000..97f071a4b
--- /dev/null
+++ b/admin/src/commands/TopProjectsCommand.tsx
@@ -0,0 +1,201 @@
+import React, { useState, useEffect } from 'react'
+import { Box, Text, useInput } from 'ink'
+import SelectInput from 'ink-select-input'
+import { Spinner } from '../components/Spinner.js'
+import { Table } from '../components/Table.js'
+import { getTopProjectsByEvents, TopProject, getProjectEventCount } from '../db/clickhouse.js'
+import { AppDataSource, Project } from '../db/mysql.js'
+
+interface TopProjectsCommandProps {
+ onBack: () => void
+}
+
+type Period = '24h' | '7d' | '30d'
+type Mode = 'list' | 'detail'
+
+const periodDays: Record<Period, number> = {
+ '24h': 1,
+ '7d': 7,
+ '30d': 30,
+}
+
+interface ProjectWithEvents extends TopProject {
+ name?: string
+ adminEmail?: string
+}
+
+export function TopProjectsCommand({ onBack }: TopProjectsCommandProps) {
+ const [mode, setMode] = useState<Mode>('list')
+ const [loading, setLoading] = useState(true)
+ const [period, setPeriod] = useState<Period>('7d')
+ const [projects, setProjects] = useState<ProjectWithEvents[]>([])
+ const [selectedProject, setSelectedProject] = useState<Project | null>(null)
+ const [eventCount, setEventCount] = useState<number>(0)
+ const [error, setError] = useState<string | null>(null)
+
+ useInput((input, key) => {
+ if (key.escape) {
+ if (mode === 'detail') {
+ setMode('list')
+ setSelectedProject(null)
+ } else {
+ onBack()
+ }
+ }
+ if (mode === 'list') {
+ if (input === '1') setPeriod('24h')
+ if (input === '2') setPeriod('7d')
+ if (input === '3') setPeriod('30d')
+ }
+ })
+
+ useEffect(() => {
+ loadTopProjects()
+ }, [period])
+
+ async function loadTopProjects() {
+ setLoading(true)
+ setError(null)
+ try {
+ const topProjects = await getTopProjectsByEvents(periodDays[period], 20)
+
+ if (topProjects.length === 0) {
+ setProjects([])
+ setLoading(false)
+ return
+ }
+
+ const projectRepo = AppDataSource.getRepository(Project)
+ const pids = topProjects.map(p => p.pid)
+
+ const dbProjects = await projectRepo
+ .createQueryBuilder('project')
+ .leftJoinAndSelect('project.admin', 'admin')
+ .where('project.id IN (:...pids)', { pids })
+ .getMany()
+
+ const projectMap = new Map(dbProjects.map(p => [p.id, p]))
+
+ const enrichedProjects: ProjectWithEvents[] = topProjects.map(tp => ({
+ ...tp,
+ name: projectMap.get(tp.pid)?.name || 'Unknown',
+ adminEmail: projectMap.get(tp.pid)?.admin?.email || 'N/A',
+ }))
+
+ setProjects(enrichedProjects)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load top projects')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ async function loadProjectDetails(pid: string) {
+ setLoading(true)
+ try {
+ const projectRepo = AppDataSource.getRepository(Project)
+ const project = await projectRepo.findOne({
+ where: { id: pid },
+ relations: ['admin', 'organisation'],
+ })
+
+ if (project) {
+ const count = await getProjectEventCount(pid)
+ setEventCount(count)
+ setSelectedProject(project)
+ setMode('detail')
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load project details')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ if (loading) {
+ return <Spinner text="Loading top projects..." />
+ }
+
+ if (error) {
+ return (
+ <Box flexDirection="column">
+ <Text color="red">Error: {error}</Text>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ )
+ }
+
+ if (mode === 'detail' && selectedProject) {
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">πŸ“ Project Details</Text>
+
+ <Box flexDirection="column" marginTop={1}>
+ <Text><Text color="cyan">ID:</Text> {selectedProject.id}</Text>
+ <Text><Text color="cyan">Name:</Text> {selectedProject.name}</Text>
+ <Text>
+ <Text color="cyan">Status:</Text>{' '}
+ <Text color={selectedProject.active ? 'green' : 'red'}>
+ {selectedProject.active ? 'Active' : 'Inactive'}
+ </Text>
+ {selectedProject.isArchived && <Text color="yellow"> (Archived)</Text>}
+ </Text>
+ <Text><Text color="cyan">Website URL:</Text> {selectedProject.origins?.[0] || 'Not set'}</Text>
+ <Text><Text color="cyan">Owner:</Text> {selectedProject.admin?.email || 'N/A'}</Text>
+ <Text>
+ <Text color="cyan">Organization:</Text>{' '}
+ {selectedProject.organisation?.name || 'None'}
+ </Text>
+ <Text>
+ <Text color="cyan">Total Events:</Text>{' '}
+ <Text color="green" bold>{eventCount.toLocaleString()}</Text>
+ </Text>
+ </Box>
+
+ <Box marginTop={1}>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ </Box>
+ )
+ }
+
+ const projectItems = projects.map((p, index) => ({
+ label: `${index + 1}. [${p.pid}] ${p.name} - ${p.eventCount.toLocaleString()} events (${p.adminEmail})`,
+ value: p.pid,
+ }))
+
+ return (
+ <Box flexDirection="column">
+ <Text bold color="yellow">πŸ”₯ Top Projects by Events</Text>
+
+ <Box marginTop={1} marginBottom={1}>
+ <Text>
+ Period:{' '}
+ <Text color={period === '24h' ? 'green' : 'gray'} bold={period === '24h'}>[1] 24h</Text>
+ {' | '}
+ <Text color={period === '7d' ? 'green' : 'gray'} bold={period === '7d'}>[2] 7 days</Text>
+ {' | '}
+ <Text color={period === '30d' ? 'green' : 'gray'} bold={period === '30d'}>[3] 30 days</Text>
+ </Text>
+ </Box>
+
+ {projects.length === 0 ? (
+ <Text color="gray">No projects with events in this period</Text>
+ ) : (
+ <Box flexDirection="column">
+ <Box marginBottom={1}>
+ <Text color="gray">Select a project to view details:</Text>
+ </Box>
+ <SelectInput
+ items={projectItems}
+ onSelect={(item) => loadProjectDetails(item.value)}
+ />
+ </Box>
+ )}
+
+ <Box marginTop={1}>
+ <Text color="gray">Press ESC to go back</Text>
+ </Box>
+ </Box>
+ )
+}
diff --git a/admin/src/components/App.tsx b/admin/src/components/App.tsx
index a64ec59f5..d63fead2a 100644
--- a/admin/src/components/App.tsx
+++ b/admin/src/components/App.tsx
@@ -6,12 +6,22 @@ import { OrgsCommand } from "../commands/OrgsCommand.js";
import { ProjectsCommand } from "../commands/ProjectsCommand.js";
import { UsersCommand } from "../commands/UsersCommand.js";
import { StatsCommand } from "../commands/StatsCommand.js";
+import { TopProjectsCommand } from "../commands/TopProjectsCommand.js";
+import { LimitsCommand } from "../commands/LimitsCommand.js";
+import { InactiveProjectsCommand } from "../commands/InactiveProjectsCommand.js";
+import { SearchCommand } from "../commands/SearchCommand.js";
+import { RecentActivityCommand } from "../commands/RecentActivityCommand.js";
import { initializeDatabase, testMySQLConnection } from "../db/mysql.js";
import { testClickHouseConnection } from "../db/clickhouse.js";
-type View = "menu" | "orgs" | "projects" | "users" | "stats";
+type View = "menu" | "orgs" | "projects" | "users" | "stats" | "top" | "limits" | "inactive" | "search" | "recent";
const menuItems = [
+ { label: "πŸ” Global Search", value: "search" as const },
+ { label: "πŸ“ˆ Recent Activity", value: "recent" as const },
+ { label: "πŸ”₯ Top Projects", value: "top" as const },
+ { label: "⚠️ Users Near Limits", value: "limits" as const },
+ { label: "πŸ’€ Inactive Projects", value: "inactive" as const },
{ label: "πŸ“Š ClickHouse Stats", value: "stats" as const },
{ label: "🏒 Organizations", value: "orgs" as const },
{ label: "πŸ“ Projects", value: "projects" as const },
@@ -145,6 +155,11 @@ export function App() {
)}
{view === "users" && <UsersCommand onBack={() => setView("menu")} />}
{view === "stats" && <StatsCommand onBack={() => setView("menu")} />}
+ {view === "top" && <TopProjectsCommand onBack={() => setView("menu")} />}
+ {view === "limits" && <LimitsCommand onBack={() => setView("menu")} />}
+ {view === "inactive" && <InactiveProjectsCommand onBack={() => setView("menu")} />}
+ {view === "search" && <SearchCommand onBack={() => setView("menu")} />}
+ {view === "recent" && <RecentActivityCommand onBack={() => setView("menu")} />}
</Box>
);
diff --git a/admin/src/db/clickhouse.ts b/admin/src/db/clickhouse.ts
index 065d99e28..2e4f960b3 100644
--- a/admin/src/db/clickhouse.ts
+++ b/admin/src/db/clickhouse.ts
@@ -140,4 +140,60 @@ export async function testClickHouseConnection(): Promise<boolean> {
}
}
+export interface TopProject {
+ pid: string;
+ eventCount: number;
+}
+
+export async function getTopProjectsByEvents(
+ days: number,
+ limit: number = 20
+): Promise<TopProject[]> {
+ const client = getClient();
+ const database = process.env.CLICKHOUSE_DATABASE || "analytics";
+
+ try {
+ const result = await client.query({
+ query: `
+ SELECT
+ pid,
+ count() as eventCount
+ FROM ${database}.analytics
+ WHERE created >= now() - INTERVAL ${days} DAY
+ GROUP BY pid
+ ORDER BY eventCount DESC
+ LIMIT ${limit}
+ `,
+ format: "JSONEachRow",
+ });
+ const data = await result.json<TopProject>();
+ return data as unknown as TopProject[];
+ } catch {
+ return [];
+ }
+}
+
+export async function getProjectsWithRecentEvents(
+ days: number
+): Promise<Set<string>> {
+ const client = getClient();
+ const database = process.env.CLICKHOUSE_DATABASE || "analytics";
+
+ try {
+ const result = await client.query({
+ query: `
+ SELECT DISTINCT pid
+ FROM ${database}.analytics
+ WHERE created >= now() - INTERVAL ${days} DAY
+ `,
+ format: "JSONEachRow",
+ });
+ const data = await result.json<{ pid: string }>();
+ const dataArray = data as unknown as { pid: string }[];
+ return new Set(dataArray.map((row) => row.pid));
+ } catch {
+ return new Set();
+ }
+}
+
export { getClient as clickhouse };