feat(analytics): add site settings and public dashboard

This commit is contained in:
Usman Baig
2026-01-18 18:39:26 +01:00
parent dcfead33d6
commit 8fe2500d19
4 changed files with 583 additions and 35 deletions

321
app/share/[id]/page.tsx Normal file
View File

@@ -0,0 +1,321 @@
'use client'
import { useEffect, useState } from 'react'
import { useParams, useSearchParams, useRouter } from 'next/navigation'
import { getPublicDashboard, type DashboardData } from '@/lib/api/stats'
import { toast } from 'sonner'
import LoadingOverlay from '@/components/LoadingOverlay'
import StatsCard from '@/components/dashboard/StatsCard'
import Chart from '@/components/dashboard/Chart'
import TopPages from '@/components/dashboard/TopPages'
import TopReferrers from '@/components/dashboard/TopReferrers'
import Locations from '@/components/dashboard/Locations'
import TechSpecs from '@/components/dashboard/TechSpecs'
import PerformanceStats from '@/components/dashboard/PerformanceStats'
import Select from '@/components/Select'
import { CalendarIcon } from '@heroicons/react/outline'
import { LightningBoltIcon } from '@heroicons/react/solid'
import DatePickerModal from '@/components/dashboard/DatePickerModal'
// Helper to get date ranges
const getDateRange = (days: number) => {
const end = new Date()
const start = new Date()
start.setDate(end.getDate() - (days - 1)) // -1 because today counts as 1 day
return {
start: start.toISOString().split('T')[0],
end: end.toISOString().split('T')[0]
}
}
export default function PublicDashboardPage() {
const params = useParams()
const searchParams = useSearchParams()
const router = useRouter()
const siteId = params.id as string
const passwordParam = searchParams.get('password') || undefined
const [loading, setLoading] = useState(true)
const [data, setData] = useState<DashboardData | null>(null)
const [password, setPassword] = useState(passwordParam || '')
const [isPasswordProtected, setIsPasswordProtected] = useState(false)
// Date range state
const [dateRange, setDateRange] = useState(getDateRange(30))
const [isDatePickerOpen, setIsDatePickerOpen] = useState(false)
// Auto-refresh interval (for realtime)
useEffect(() => {
const interval = setInterval(() => {
// Only refresh realtime count if we have data
if (data && !isPasswordProtected) {
loadDashboard(true)
}
}, 10000) // 10 seconds
return () => clearInterval(interval)
}, [data, isPasswordProtected, dateRange, password])
useEffect(() => {
loadDashboard()
}, [siteId, dateRange])
const loadDashboard = async (silent = false) => {
try {
if (!silent) setLoading(true)
const dashboardData = await getPublicDashboard(
siteId,
dateRange.start,
dateRange.end,
10,
dateRange.start === dateRange.end ? 'hour' : 'day',
password
)
setData(dashboardData)
setIsPasswordProtected(false)
} catch (error: any) {
if (error.response?.status === 401 && error.response?.data?.is_protected) {
setIsPasswordProtected(true)
} else if (error.response?.status === 404) {
toast.error('Site not found')
} else if (!silent) {
toast.error('Failed to load dashboard: ' + (error.message || 'Unknown error'))
}
} finally {
if (!silent) setLoading(false)
}
}
const handlePasswordSubmit = (e: React.FormEvent) => {
e.preventDefault()
loadDashboard()
}
if (loading && !data && !isPasswordProtected) {
return <LoadingOverlay logoSrc="/ciphera_icon_no_margins.png" title="Ciphera Analytics" />
}
if (isPasswordProtected && !data) {
return (
<div className="min-h-screen flex items-center justify-center bg-neutral-50 dark:bg-black px-4">
<div className="max-w-md w-full bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-xl p-8 shadow-lg">
<div className="text-center mb-6">
<div className="w-12 h-12 bg-brand-orange/10 rounded-xl flex items-center justify-center mx-auto mb-4 text-brand-orange">
<LightningBoltIcon className="w-6 h-6" />
</div>
<h1 className="text-2xl font-bold text-neutral-900 dark:text-white mb-2">
Protected Dashboard
</h1>
<p className="text-neutral-600 dark:text-neutral-400">
This dashboard is password protected. Please enter the password to view stats.
</p>
</div>
<form onSubmit={handlePasswordSubmit}>
<div className="mb-4">
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter password"
className="w-full px-4 py-2 border border-neutral-300 dark:border-neutral-700 rounded-lg bg-white dark:bg-neutral-800 text-neutral-900 dark:text-white focus:ring-2 focus:ring-brand-orange focus:border-transparent"
autoFocus
/>
</div>
<button
type="submit"
className="w-full btn-primary"
>
Access Dashboard
</button>
</form>
</div>
</div>
)
}
if (!data) return null
const { site, stats, daily_stats, top_pages, entry_pages, exit_pages, top_referrers, countries, cities, regions, browsers, os, devices, screen_resolutions, performance, realtime_visitors } = data
// Provide defaults for potentially undefined data
const safeDailyStats = daily_stats || []
const safeStats = stats || { pageviews: 0, visitors: 0, bounce_rate: 0, avg_duration: 0 }
const safeTopPages = top_pages || []
const safeEntryPages = entry_pages || []
const safeExitPages = exit_pages || []
const safeTopReferrers = top_referrers || []
const safeCountries = countries || []
const safeCities = cities || []
const safeRegions = regions || []
const safeBrowsers = browsers || []
const safeOS = os || []
const safeDevices = devices || []
const safeScreenResolutions = screen_resolutions || []
return (
<div className="min-h-screen bg-neutral-50 dark:bg-black">
<div className="container mx-auto px-4 py-8">
{/* Header */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
<div>
<div className="flex items-center gap-2 mb-1">
<div className="w-2 h-2 rounded-full bg-brand-orange animate-pulse" />
<span className="text-sm font-medium text-brand-orange uppercase tracking-wider">Public Dashboard</span>
</div>
<h1 className="text-3xl font-bold text-neutral-900 dark:text-white flex items-center gap-3">
<img
src={`https://www.google.com/s2/favicons?domain=${site.domain}&sz=64`}
alt={site.name}
className="w-8 h-8 rounded-lg"
onError={(e) => {
(e.target as HTMLImageElement).src = '/globe.svg'
}}
/>
{site.domain}
</h1>
</div>
<div className="flex gap-2">
<Select
value={
dateRange.start === new Date().toISOString().split('T')[0] && dateRange.end === new Date().toISOString().split('T')[0]
? 'today'
: dateRange.start === getDateRange(7).start
? '7'
: dateRange.start === getDateRange(30).start
? '30'
: 'custom'
}
onChange={(value) => {
if (value === '7') setDateRange(getDateRange(7))
else if (value === '30') setDateRange(getDateRange(30))
else if (value === 'today') {
const today = new Date().toISOString().split('T')[0]
setDateRange({ start: today, end: today })
}
else if (value === 'custom') {
setIsDatePickerOpen(true)
}
}}
options={[
{ value: 'today', label: 'Today' },
{ value: '7', label: 'Last 7 days' },
{ value: '30', label: 'Last 30 days' },
{ value: 'custom', label: 'Custom' },
]}
/>
{/* Powered by Ciphera Badge */}
<a
href="https://ciphera.net"
target="_blank"
rel="noopener noreferrer"
className="hidden md:flex items-center gap-2 px-3 py-2 bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-lg text-sm text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange transition-colors"
>
<LightningBoltIcon className="w-4 h-4" />
<span>Powered by Ciphera</span>
</a>
</div>
</div>
{/* Realtime & Key Stats */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
<div className="col-span-2 lg:col-span-4 bg-gradient-to-r from-brand-orange/10 to-transparent border border-brand-orange/20 rounded-xl p-4 flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="relative">
<div className="w-3 h-3 bg-brand-orange rounded-full animate-ping absolute top-0 left-0 opacity-75"></div>
<div className="w-3 h-3 bg-brand-orange rounded-full relative z-10"></div>
</div>
<span className="text-brand-orange font-medium">Current Visitors</span>
</div>
<span className="text-2xl font-bold text-brand-orange">{realtime_visitors}</span>
</div>
<StatsCard
title="Total Visitors"
value={safeStats.visitors}
change={0}
loading={false}
/>
<StatsCard
title="Total Pageviews"
value={safeStats.pageviews}
change={0}
loading={false}
/>
<StatsCard
title="Bounce Rate"
value={`${Math.round(safeStats.bounce_rate)}%`}
change={0}
loading={false}
inverse
/>
<StatsCard
title="Avg Duration"
value={`${Math.round(safeStats.avg_duration)}s`}
change={0}
loading={false}
/>
</div>
{/* Chart */}
<div className="mb-8">
<Chart
data={safeDailyStats}
prevData={[]} // No comparison for public view yet
stats={safeStats}
prevStats={{ pageviews: 0, visitors: 0, bounce_rate: 0, avg_duration: 0 }}
interval={dateRange.start === dateRange.end ? 'hour' : 'day'}
/>
</div>
{/* Performance Stats */}
{performance && (
<div className="mb-8">
<PerformanceStats stats={performance} />
</div>
)}
{/* Details Grid */}
<div className="grid gap-6 lg:grid-cols-2 mb-8">
<TopPages
pages={safeTopPages}
entryPages={safeEntryPages}
exitPages={safeExitPages}
/>
<TopReferrers referrers={safeTopReferrers} />
</div>
<div className="grid gap-6 lg:grid-cols-2 mb-8">
<Locations
countries={safeCountries}
cities={safeCities}
regions={safeRegions}
/>
<TechSpecs
browsers={safeBrowsers}
os={safeOS}
devices={safeDevices}
screenResolutions={safeScreenResolutions}
/>
</div>
<footer className="mt-12 pt-8 border-t border-neutral-200 dark:border-neutral-800 text-center text-sm text-neutral-500">
<p>© {new Date().getFullYear()} {site.name}. Analytics by <a href="https://ciphera.net" className="text-brand-orange hover:underline">Ciphera</a>.</p>
</footer>
</div>
<DatePickerModal
isOpen={isDatePickerOpen}
onClose={() => setIsDatePickerOpen(false)}
dateRange={dateRange}
onApply={(start, end) => {
setDateRange({ start, end })
setIsDatePickerOpen(false)
}}
/>
</div>
)
}

View File

@@ -2,11 +2,28 @@
import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { getSite, updateSite, type Site } from '@/lib/api/sites'
import { getSite, updateSite, resetSiteData, deleteSite, type Site } from '@/lib/api/sites'
import { toast } from 'sonner'
import LoadingOverlay from '@/components/LoadingOverlay'
import { APP_URL, API_URL } from '@/lib/api/client'
const TIMEZONES = [
'UTC',
'America/New_York',
'America/Los_Angeles',
'America/Chicago',
'America/Toronto',
'Europe/London',
'Europe/Paris',
'Europe/Berlin',
'Europe/Amsterdam',
'Asia/Tokyo',
'Asia/Singapore',
'Asia/Dubai',
'Australia/Sydney',
'Pacific/Auckland',
]
export default function SiteSettingsPage() {
const params = useParams()
const router = useRouter()
@@ -17,6 +34,10 @@ export default function SiteSettingsPage() {
const [saving, setSaving] = useState(false)
const [formData, setFormData] = useState({
name: '',
timezone: 'UTC',
is_public: false,
password: '',
excluded_paths: ''
})
const [scriptCopied, setScriptCopied] = useState(false)
@@ -29,7 +50,13 @@ export default function SiteSettingsPage() {
setLoading(true)
const data = await getSite(siteId)
setSite(data)
setFormData({ name: data.name })
setFormData({
name: data.name,
timezone: data.timezone || 'UTC',
is_public: data.is_public || false,
password: '', // Don't show existing password
excluded_paths: (data.excluded_paths || []).join('\n')
})
} catch (error: any) {
toast.error('Failed to load site: ' + (error.message || 'Unknown error'))
} finally {
@@ -42,7 +69,18 @@ export default function SiteSettingsPage() {
setSaving(true)
try {
await updateSite(siteId, formData)
const excludedPathsArray = formData.excluded_paths
.split('\n')
.map(p => p.trim())
.filter(p => p.length > 0)
await updateSite(siteId, {
name: formData.name,
timezone: formData.timezone,
is_public: formData.is_public,
password: formData.password || undefined,
excluded_paths: excludedPathsArray
})
toast.success('Site updated successfully')
loadSite()
} catch (error: any) {
@@ -52,6 +90,35 @@ export default function SiteSettingsPage() {
}
}
const handleResetData = async () => {
if (!confirm('Are you sure you want to delete ALL data for this site? This action cannot be undone.')) {
return
}
try {
await resetSiteData(siteId)
toast.success('All site data has been reset')
} catch (error: any) {
toast.error('Failed to reset data: ' + (error.message || 'Unknown error'))
}
}
const handleDeleteSite = async () => {
const confirmation = prompt('To confirm deletion, please type the site domain:')
if (confirmation !== site?.domain) {
if (confirmation) toast.error('Domain does not match')
return
}
try {
await deleteSite(siteId)
toast.success('Site deleted successfully')
router.push('/')
} catch (error: any) {
toast.error('Failed to delete site: ' + (error.message || 'Unknown error'))
}
}
const copyScript = () => {
const script = `<script defer data-domain="${site?.domain}" data-api="${API_URL}" src="${APP_URL}/script.js"></script>`
navigator.clipboard.writeText(script)
@@ -98,12 +165,15 @@ export default function SiteSettingsPage() {
</button>
</div>
<form onSubmit={handleSubmit} className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-xl p-6">
<form onSubmit={handleSubmit} className="space-y-6">
{/* General Configuration */}
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-xl p-6">
<h2 className="text-xl font-semibold mb-4 text-neutral-900 dark:text-white">
Site Information
General Configuration
</h2>
<div className="mb-4">
<div className="space-y-4">
<div>
<label htmlFor="name" className="block text-sm font-medium mb-2 text-neutral-900 dark:text-white">
Site Name
</label>
@@ -117,7 +187,25 @@ export default function SiteSettingsPage() {
/>
</div>
<div className="mb-6">
<div>
<label htmlFor="timezone" className="block text-sm font-medium mb-2 text-neutral-900 dark:text-white">
Timezone
</label>
<select
id="timezone"
value={formData.timezone}
onChange={(e) => setFormData({ ...formData, timezone: e.target.value })}
className="w-full px-4 py-2 border border-neutral-300 dark:border-neutral-700 rounded-lg bg-white dark:bg-neutral-800 text-neutral-900 dark:text-white focus:ring-2 focus:ring-brand-orange focus:border-transparent"
>
{TIMEZONES.map((tz) => (
<option key={tz} value={tz}>
{tz}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium mb-2 text-neutral-900 dark:text-white">
Domain
</label>
@@ -131,19 +219,135 @@ export default function SiteSettingsPage() {
Domain cannot be changed after creation
</p>
</div>
</div>
</div>
<div className="flex gap-4">
{/* Data Filters */}
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-xl p-6">
<h2 className="text-xl font-semibold mb-4 text-neutral-900 dark:text-white">
Data Filters
</h2>
<div>
<label htmlFor="excludedPaths" className="block text-sm font-medium mb-2 text-neutral-900 dark:text-white">
Excluded Paths
</label>
<p className="text-sm text-neutral-600 dark:text-neutral-400 mb-2">
Enter paths to exclude from tracking (one per line). Supports simple matching (e.g., /admin/*).
</p>
<textarea
id="excludedPaths"
rows={4}
value={formData.excluded_paths}
onChange={(e) => setFormData({ ...formData, excluded_paths: e.target.value })}
placeholder="/admin/*&#10;/staging/*"
className="w-full px-4 py-2 border border-neutral-300 dark:border-neutral-700 rounded-lg bg-white dark:bg-neutral-800 text-neutral-900 dark:text-white focus:ring-2 focus:ring-brand-orange focus:border-transparent font-mono text-sm"
/>
</div>
</div>
{/* Visibility */}
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-xl p-6">
<h2 className="text-xl font-semibold mb-4 text-neutral-900 dark:text-white">
Visibility
</h2>
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<label htmlFor="isPublic" className="font-medium text-neutral-900 dark:text-white">
Public Dashboard
</label>
<p className="text-sm text-neutral-600 dark:text-neutral-400">
Allow anyone with the link to view this dashboard
</p>
</div>
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
id="isPublic"
checked={formData.is_public}
onChange={(e) => setFormData({ ...formData, is_public: e.target.checked })}
className="sr-only peer"
/>
<div className="w-11 h-6 bg-neutral-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-brand-orange/20 dark:peer-focus:ring-brand-orange/20 rounded-full peer dark:bg-neutral-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-brand-orange"></div>
</label>
</div>
{formData.is_public && (
<div className="pt-4 border-t border-neutral-200 dark:border-neutral-800">
<label htmlFor="password" className="block text-sm font-medium mb-2 text-neutral-900 dark:text-white">
Password Protection (Optional)
</label>
<input
type="password"
id="password"
value={formData.password}
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
placeholder="Leave empty to keep existing password (if any)"
className="w-full px-4 py-2 border border-neutral-300 dark:border-neutral-700 rounded-lg bg-white dark:bg-neutral-800 text-neutral-900 dark:text-white focus:ring-2 focus:ring-brand-orange focus:border-transparent"
/>
<p className="mt-1 text-xs text-neutral-500">
Set a password to restrict access to the public dashboard.
</p>
</div>
)}
</div>
</div>
{/* Danger Zone */}
<div className="bg-white dark:bg-neutral-900 border border-red-200 dark:border-red-900 rounded-xl p-6">
<h2 className="text-xl font-semibold mb-4 text-red-600 dark:text-red-400">
Danger Zone
</h2>
<div className="space-y-4">
<div className="flex items-center justify-between py-2">
<div>
<h3 className="font-medium text-neutral-900 dark:text-white">Reset Data</h3>
<p className="text-sm text-neutral-600 dark:text-neutral-400">
Delete all stats and events for this site. This cannot be undone.
</p>
</div>
<button
type="button"
onClick={handleResetData}
className="px-4 py-2 border border-red-200 dark:border-red-900 text-red-600 dark:text-red-400 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
>
Reset Data
</button>
</div>
<div className="pt-4 border-t border-neutral-200 dark:border-neutral-800 flex items-center justify-between py-2">
<div>
<h3 className="font-medium text-neutral-900 dark:text-white">Delete Site</h3>
<p className="text-sm text-neutral-600 dark:text-neutral-400">
Permanently delete this site and all its data.
</p>
</div>
<button
type="button"
onClick={handleDeleteSite}
className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
>
Delete Site
</button>
</div>
</div>
</div>
<div className="flex gap-4 sticky bottom-6 bg-white/80 dark:bg-neutral-950/80 backdrop-blur-sm p-4 rounded-xl border border-neutral-200 dark:border-neutral-800 shadow-lg">
<button
type="submit"
disabled={saving}
className="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
className="btn-primary flex-1"
>
{saving ? 'Saving...' : 'Save Changes'}
</button>
<button
type="button"
onClick={() => router.back()}
className="btn-secondary"
className="btn-secondary flex-1"
>
Cancel
</button>

View File

@@ -5,6 +5,9 @@ export interface Site {
user_id: string
domain: string
name: string
timezone?: string
is_public?: boolean
excluded_paths?: string[]
created_at: string
updated_at: string
}
@@ -16,6 +19,10 @@ export interface CreateSiteRequest {
export interface UpdateSiteRequest {
name: string
timezone?: string
is_public?: boolean
password?: string
excluded_paths?: string[]
}
export async function listSites(): Promise<Site[]> {
@@ -46,3 +53,9 @@ export async function deleteSite(id: string): Promise<void> {
method: 'DELETE',
})
}
export async function resetSiteData(id: string): Promise<void> {
await apiRequest(`/sites/${id}/reset`, {
method: 'POST',
})
}

View File

@@ -207,3 +207,13 @@ export async function getDashboard(siteId: string, startDate?: string, endDate?:
params.append('limit', limit.toString())
return apiRequest<DashboardData>(`/sites/${siteId}/dashboard?${params.toString()}`)
}
export async function getPublicDashboard(siteId: string, startDate?: string, endDate?: string, limit = 10, interval?: string, password?: string): Promise<DashboardData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
if (interval) params.append('interval', interval)
if (password) params.append('password', password)
params.append('limit', limit.toString())
return apiRequest<DashboardData>(`/public/sites/${siteId}/dashboard?${params.toString()}`)
}