Add persistent admin analytics, backup restore workflow, and tabbed admin UI

This commit is contained in:
nmemmert
2026-04-12 13:12:03 -04:00
parent bac22950ba
commit 738cc2a412
6 changed files with 1707 additions and 109 deletions
+635 -104
View File
@@ -1,4 +1,4 @@
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import type { SiteContent, CustomLink, CustomBlock } from './App'
import { DEFAULTS } from './App'
@@ -8,6 +8,53 @@ interface Props {
onSave: (c: SiteContent) => void
}
interface BackupPreview {
filename: string
sizeBytes: number
createdAt: string | null
reason: string
adminUpdatedAt: string | null
totalHits: number
totalVisits: number
}
interface AdminStats {
totalHits: number
firstHitAt: string | null
lastHitAt: string | null
topPaths: Array<{ path: string; hits: number }>
last7Days: Array<{ day: string; hits: number }>
last30DaysTotal: number
visitors: {
totalVisits: number
uniqueVisitors: number
returningVisits: number
firstVisitAt: string | null
lastVisitAt: string | null
topCountries: Array<{ name: string; hits: number }>
topStates: Array<{ name: string; hits: number }>
topCounties: Array<{ name: string; hits: number }>
topCities: Array<{ name: string; hits: number }>
recentVisits: Array<{
at: string
visitorId: string
ip: string
path: string
country: string
state: string
county: string
city: string
returningVisitor: boolean
visitCount: number
}>
}
writeStatus: {
hitStats: { ok: boolean; at: string | null; error: string | null }
visitorStats: { ok: boolean; at: string | null; error: string | null }
backups: { ok: boolean; at: string | null; error: string | null; file: string | null }
}
}
type StringField = Exclude<keyof SiteContent, 'customLinks' | 'customBlocks'>
const FIELDS: { key: StringField; label: string; multiline?: boolean }[] = [
@@ -31,6 +78,194 @@ export default function AdminPage({ content, onSave }: Props) {
const [form, setForm] = useState<SiteContent>(content)
const [status, setStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle')
const [errorMsg, setErrorMsg] = useState('')
const [adminTab, setAdminTab] = useState<'content' | 'stats'>('content')
const [contentTab, setContentTab] = useState<'main' | 'custom'>('main')
const [stats, setStats] = useState<AdminStats | null>(null)
const [statsStatus, setStatsStatus] = useState<'loading' | 'ready' | 'error'>('loading')
const [maintenanceMsg, setMaintenanceMsg] = useState('')
const [backupFiles, setBackupFiles] = useState<BackupPreview[]>([])
const [selectedBackup, setSelectedBackup] = useState('')
const [selectedBackupPreview, setSelectedBackupPreview] = useState<BackupPreview | null>(null)
useEffect(() => {
fetch('/api/admin-stats')
.then(r => (r.ok ? r.json() : Promise.reject(new Error('Failed to load stats'))))
.then(data => {
setStats(data as AdminStats)
setStatsStatus('ready')
})
.catch(() => {
setStatsStatus('error')
})
fetch('/api/admin-stats/backups')
.then(r => (r.ok ? r.json() : Promise.reject(new Error('Failed to load backups'))))
.then(data => {
const files = Array.isArray((data as { backups?: unknown }).backups) ? (data as { backups: BackupPreview[] }).backups : []
setBackupFiles(files)
if (files.length > 0) {
setSelectedBackup(files[0].filename)
}
})
.catch(() => {})
}, [])
useEffect(() => {
if (!selectedBackup) {
setSelectedBackupPreview(null)
return
}
fetch('/api/admin-stats/backup-preview', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ filename: selectedBackup }),
})
.then(r => (r.ok ? r.json() : Promise.reject(new Error('Preview failed'))))
.then(data => {
const preview = (data as { preview?: BackupPreview }).preview ?? null
setSelectedBackupPreview(preview)
})
.catch(() => {
setSelectedBackupPreview(null)
})
}, [selectedBackup])
async function reloadStats() {
const r = await fetch('/api/admin-stats')
if (!r.ok) throw new Error('Could not refresh stats')
const data = await r.json()
setStats(data as AdminStats)
setStatsStatus('ready')
}
async function reloadBackups() {
const r = await fetch('/api/admin-stats/backups')
if (!r.ok) throw new Error('Could not refresh backups')
const data = await r.json() as { backups?: BackupPreview[] }
const files = Array.isArray(data.backups) ? data.backups : []
setBackupFiles(files)
const names = files.map(f => f.filename)
if (files.length > 0 && !names.includes(selectedBackup)) {
setSelectedBackup(files[0].filename)
}
}
async function reloadContentFromServer() {
const r = await fetch('/api/admin-content')
if (!r.ok) return
const data = await r.json() as { siteContent?: Partial<SiteContent> }
if (data?.siteContent && typeof data.siteContent === 'object') {
const next = { ...DEFAULTS, ...data.siteContent }
setForm(next)
onSave(next)
}
}
function maskIp(ip: string) {
if (!ip || ip === 'unknown') return 'unknown'
if (ip.includes('.')) {
const parts = ip.split('.')
if (parts.length === 4) return `${parts[0]}.${parts[1]}.x.x`
}
if (ip.includes(':')) {
const parts = ip.split(':')
return `${parts.slice(0, 3).join(':')}:x:x`
}
return ip
}
async function handleExport() {
try {
const r = await fetch('/api/admin-stats/export')
if (!r.ok) throw new Error('Export failed')
const data = await r.json()
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `siteforge-admin-export-${new Date().toISOString().slice(0, 10)}.json`
a.click()
URL.revokeObjectURL(url)
setMaintenanceMsg('Export downloaded.')
} catch {
setMaintenanceMsg('Export failed.')
}
}
async function handlePrune() {
const input = prompt('Keep how many days of analytics data?', '180')
if (input === null) return
const days = Number(input)
if (!Number.isFinite(days) || days <= 0) {
setMaintenanceMsg('Invalid retention days.')
return
}
try {
const r = await fetch('/api/admin-stats/prune', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ days }),
})
if (!r.ok) throw new Error('Prune failed')
await reloadStats()
setMaintenanceMsg(`Pruned analytics to ${Math.floor(days)} days.`)
} catch {
setMaintenanceMsg('Prune failed.')
}
}
async function handleClear() {
if (!confirm('Clear ALL analytics data now? This cannot be undone.')) return
try {
const r = await fetch('/api/admin-stats/clear', { method: 'POST' })
if (!r.ok) throw new Error('Clear failed')
await reloadStats()
setMaintenanceMsg('All analytics data cleared.')
} catch {
setMaintenanceMsg('Clear failed.')
}
}
async function handleBackupNow() {
try {
const r = await fetch('/api/admin-stats/backup', { method: 'POST' })
if (!r.ok) throw new Error('Backup failed')
await reloadStats()
await reloadBackups()
setMaintenanceMsg('Backup snapshot created.')
} catch {
setMaintenanceMsg('Backup failed.')
}
}
async function handleRestoreBackup() {
if (!selectedBackup) {
setMaintenanceMsg('Select a backup first.')
return
}
if (!confirm(`Restore backup ${selectedBackup}? This will overwrite current admin data and analytics.`)) return
try {
const r = await fetch('/api/admin-stats/restore', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ filename: selectedBackup }),
})
if (!r.ok) throw new Error('Restore failed')
await reloadContentFromServer()
await reloadStats()
await reloadBackups()
setMaintenanceMsg(`Restored from ${selectedBackup}. Content fields were refreshed from backup.`)
} catch {
setMaintenanceMsg('Restore failed.')
}
}
function formatDate(value: string | null) {
if (!value) return 'Not available yet'
const d = new Date(value)
return Number.isNaN(d.getTime()) ? 'Not available yet' : d.toLocaleString()
}
function handleChange(key: StringField, value: string) {
setForm(f => ({ ...f, [key]: value }))
@@ -117,118 +352,413 @@ export default function AdminPage({ content, onSave }: Props) {
</div>
<div className="admin-form-wrap">
<div className="admin-top-tabs" role="tablist" aria-label="Admin sections">
<button
type="button"
role="tab"
aria-selected={adminTab === 'content'}
className={`admin-tab ${adminTab === 'content' ? 'admin-tab--active' : ''}`}
onClick={() => setAdminTab('content')}
>
Content
</button>
<button
type="button"
role="tab"
aria-selected={adminTab === 'stats'}
className={`admin-tab ${adminTab === 'stats' ? 'admin-tab--active' : ''}`}
onClick={() => setAdminTab('stats')}
>
Site Stats
</button>
</div>
{adminTab === 'stats' && (
<section className="admin-stats" aria-label="Site hit statistics">
<div className="admin-stats-head">
<h2>Site Hit Stats</h2>
<p>Built-in page traffic and visitor intelligence from this server.</p>
</div>
{statsStatus === 'loading' && <p className="admin-stats-note">Loading stats...</p>}
{statsStatus === 'error' && <p className="admin-stats-note admin-stats-note--err">Could not load stats right now.</p>}
{statsStatus === 'ready' && stats && (
<>
<div className="admin-stats-grid">
<article>
<h3>Total Hits</h3>
<p>{stats.totalHits.toLocaleString()}</p>
</article>
<article>
<h3>Last 30 Days</h3>
<p>{stats.last30DaysTotal.toLocaleString()}</p>
</article>
<article>
<h3>First Hit</h3>
<p>{formatDate(stats.firstHitAt)}</p>
</article>
<article>
<h3>Latest Hit</h3>
<p>{formatDate(stats.lastHitAt)}</p>
</article>
</div>
<div className="admin-stats-lists">
<div>
<h3>Top Paths</h3>
{stats.topPaths.length === 0 ? (
<p className="admin-stats-note">No hits tracked yet.</p>
) : (
<ul>
{stats.topPaths.map(item => (
<li key={item.path}>
<span>{item.path}</span>
<strong>{item.hits.toLocaleString()}</strong>
</li>
))}
</ul>
)}
</div>
<div>
<h3>Daily Hits (7 Days)</h3>
<ul>
{stats.last7Days.map(item => (
<li key={item.day}>
<span>{item.day}</span>
<strong>{item.hits.toLocaleString()}</strong>
</li>
))}
</ul>
</div>
</div>
<div className="admin-stats-head admin-stats-head--visitors">
<h2>Visitor Details</h2>
<p>IP, geography, and returning visitor behavior.</p>
</div>
<p className="admin-privacy-note">
Privacy: visitor analytics only run after cookie consent. IPs below are masked.
</p>
<div className="admin-stats-grid">
<article>
<h3>Total Visits</h3>
<p>{stats.visitors.totalVisits.toLocaleString()}</p>
</article>
<article>
<h3>Unique Visitors</h3>
<p>{stats.visitors.uniqueVisitors.toLocaleString()}</p>
</article>
<article>
<h3>Returning Visits</h3>
<p>{stats.visitors.returningVisits.toLocaleString()}</p>
</article>
<article>
<h3>Returning Rate</h3>
<p>
{stats.visitors.totalVisits > 0
? `${Math.round((stats.visitors.returningVisits / stats.visitors.totalVisits) * 100)}%`
: '0%'}
</p>
</article>
</div>
<div className="admin-stats-lists">
<div>
<h3>Top Countries</h3>
<ul>
{stats.visitors.topCountries.map(item => (
<li key={item.name}>
<span>{item.name}</span>
<strong>{item.hits.toLocaleString()}</strong>
</li>
))}
</ul>
</div>
<div>
<h3>Top States</h3>
<ul>
{stats.visitors.topStates.map(item => (
<li key={item.name}>
<span>{item.name}</span>
<strong>{item.hits.toLocaleString()}</strong>
</li>
))}
</ul>
</div>
<div>
<h3>Top Counties</h3>
<ul>
{stats.visitors.topCounties.map(item => (
<li key={item.name}>
<span>{item.name}</span>
<strong>{item.hits.toLocaleString()}</strong>
</li>
))}
</ul>
</div>
<div>
<h3>Top Cities</h3>
<ul>
{stats.visitors.topCities.map(item => (
<li key={item.name}>
<span>{item.name}</span>
<strong>{item.hits.toLocaleString()}</strong>
</li>
))}
</ul>
</div>
</div>
<div className="admin-visits-table-wrap">
<h3>Recent Visitor Log</h3>
{stats.visitors.recentVisits.length === 0 ? (
<p className="admin-stats-note">No visitor records yet.</p>
) : (
<div className="admin-visits-table-scroll">
<table className="admin-visits-table">
<thead>
<tr>
<th>Time</th>
<th>IP</th>
<th>Country</th>
<th>State</th>
<th>County</th>
<th>City</th>
<th>Path</th>
<th>Returning</th>
<th>Visit #</th>
</tr>
</thead>
<tbody>
{stats.visitors.recentVisits.map(row => (
<tr key={`${row.visitorId}-${row.at}`}>
<td>{formatDate(row.at)}</td>
<td>{maskIp(row.ip)}</td>
<td>{row.country}</td>
<td>{row.state}</td>
<td>{row.county}</td>
<td>{row.city}</td>
<td>{row.path}</td>
<td>{row.returningVisitor ? 'Yes' : 'No'}</td>
<td>{row.visitCount}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
<div className="admin-stats-head admin-stats-head--visitors">
<h2>Data Management</h2>
<p>Export, backup, or retain only recent analytics data.</p>
</div>
<div className="admin-stats-grid">
<article>
<h3>Hit Stats Write</h3>
<p>{stats.writeStatus.hitStats.ok ? 'Healthy' : 'Error'}</p>
<p>{formatDate(stats.writeStatus.hitStats.at)}</p>
</article>
<article>
<h3>Visitor Stats Write</h3>
<p>{stats.writeStatus.visitorStats.ok ? 'Healthy' : 'Error'}</p>
<p>{formatDate(stats.writeStatus.visitorStats.at)}</p>
</article>
<article>
<h3>Backup Status</h3>
<p>{stats.writeStatus.backups.ok ? 'Healthy' : 'Error'}</p>
<p>{formatDate(stats.writeStatus.backups.at)}</p>
</article>
<article>
<h3>Latest Backup File</h3>
<p>{stats.writeStatus.backups.file ?? 'Not available yet'}</p>
</article>
</div>
<div className="admin-actions admin-actions--maintenance">
<button type="button" className="btn-admin-reset" onClick={handleExport}>Export JSON</button>
<button type="button" className="btn-admin-reset" onClick={handleBackupNow}>Backup Now</button>
<button type="button" className="btn-admin-reset" onClick={handlePrune}>Prune Old Data</button>
<button type="button" className="btn-admin-remove" onClick={handleClear}>Clear Analytics</button>
</div>
<div className="admin-restore-row">
<label htmlFor="restore-backup">Restore Backup</label>
<select
id="restore-backup"
value={selectedBackup}
onChange={e => setSelectedBackup(e.target.value)}
disabled={backupFiles.length === 0}
>
{backupFiles.length === 0 && <option value="">No backups found</option>}
{backupFiles.map(file => (
<option key={file.filename} value={file.filename}>{file.filename}</option>
))}
</select>
<button type="button" className="btn-admin-reset" onClick={handleRestoreBackup} disabled={!selectedBackup}>
Restore Selected Backup
</button>
</div>
{selectedBackupPreview && (
<div className="admin-restore-preview">
<h3>Restore Preview</h3>
<p><strong>Backup:</strong> {selectedBackupPreview.filename}</p>
<p><strong>Created:</strong> {formatDate(selectedBackupPreview.createdAt)}</p>
<p><strong>Reason:</strong> {selectedBackupPreview.reason}</p>
<p><strong>Size:</strong> {(selectedBackupPreview.sizeBytes / 1024).toFixed(1)} KB</p>
<p><strong>Content Updated At:</strong> {formatDate(selectedBackupPreview.adminUpdatedAt)}</p>
<p><strong>Total Hits:</strong> {selectedBackupPreview.totalHits.toLocaleString()}</p>
<p><strong>Total Visits:</strong> {selectedBackupPreview.totalVisits.toLocaleString()}</p>
</div>
)}
{maintenanceMsg && <p className="admin-stats-note">{maintenanceMsg}</p>}
</>
)}
</section>
)}
{adminTab === 'content' && (
<form
className="admin-form"
onSubmit={e => { e.preventDefault(); handleSave() }}
>
{FIELDS.map(({ key, label, multiline }) => (
<div className="admin-field" key={key}>
<label htmlFor={`field-${key}`}>{label}</label>
{multiline ? (
<textarea
id={`field-${key}`}
value={form[key] as string}
onChange={e => handleChange(key, e.target.value)}
rows={4}
/>
) : (
<input
id={`field-${key}`}
type="text"
value={form[key] as string}
onChange={e => handleChange(key, e.target.value)}
/>
)}
</div>
))}
{/* ── Custom Links ── */}
<div className="admin-section-header">
<h3>Custom Links</h3>
<p>Add links to show in the platform buttons row, footer, or a dedicated "More Resources" section.</p>
<div className="admin-tabs" role="tablist" aria-label="Content editor tabs">
<button
type="button"
role="tab"
aria-selected={contentTab === 'main'}
className={`admin-tab ${contentTab === 'main' ? 'admin-tab--active' : ''}`}
onClick={() => setContentTab('main')}
>
Main Content
</button>
<button
type="button"
role="tab"
aria-selected={contentTab === 'custom'}
className={`admin-tab ${contentTab === 'custom' ? 'admin-tab--active' : ''}`}
onClick={() => setContentTab('custom')}
>
Custom Content
</button>
</div>
{(form.customLinks ?? []).map(link => (
<div key={link.id} className="admin-array-row">
<div className="admin-array-fields">
<div className="admin-field">
<label htmlFor={`link-label-${link.id}`}>Label</label>
<input
id={`link-label-${link.id}`}
type="text"
value={link.label}
placeholder="e.g. iHeart Radio"
onChange={e => updateLink(link.id, 'label', e.target.value)}
/>
</div>
<div className="admin-field">
<label htmlFor={`link-url-${link.id}`}>URL</label>
<input
id={`link-url-${link.id}`}
type="url"
value={link.url}
placeholder="https://..."
onChange={e => updateLink(link.id, 'url', e.target.value)}
/>
</div>
<div className="admin-field">
<label htmlFor={`link-placement-${link.id}`}>Show in</label>
<select
id={`link-placement-${link.id}`}
value={link.placement}
onChange={e => updateLink(link.id, 'placement', e.target.value)}
>
<option value="platforms">Platform Buttons (Listen section)</option>
<option value="footer">Footer Nav</option>
<option value="resources">More Resources Section</option>
</select>
</div>
</div>
<button type="button" className="btn-admin-remove" onClick={() => removeLink(link.id)}>
Remove
</button>
</div>
))}
<button type="button" className="btn-admin-add" onClick={addLink}>
+ Add Link
</button>
{/* ── Custom Blocks ── */}
<div className="admin-section-header">
<h3>Custom Content Blocks</h3>
<p>Add extra text sections. They appear below the share/QR section on the site.</p>
</div>
{(form.customBlocks ?? []).map(block => (
<div key={block.id} className="admin-array-row">
<div className="admin-array-fields">
<div className="admin-field">
<label htmlFor={`block-heading-${block.id}`}>Heading</label>
<input
id={`block-heading-${block.id}`}
type="text"
value={block.heading}
placeholder="Section heading"
onChange={e => updateBlock(block.id, 'heading', e.target.value)}
/>
</div>
<div className="admin-field">
<label htmlFor={`block-body-${block.id}`}>Body Text</label>
<textarea
id={`block-body-${block.id}`}
value={block.body}
rows={3}
placeholder="Write your content here…"
onChange={e => updateBlock(block.id, 'body', e.target.value)}
/>
{contentTab === 'main' && (
<>
{FIELDS.map(({ key, label, multiline }) => (
<div className="admin-field" key={key}>
<label htmlFor={`field-${key}`}>{label}</label>
{multiline ? (
<textarea
id={`field-${key}`}
value={form[key] as string}
onChange={e => handleChange(key, e.target.value)}
rows={4}
/>
) : (
<input
id={`field-${key}`}
type="text"
value={form[key] as string}
onChange={e => handleChange(key, e.target.value)}
/>
)}
</div>
))}
</>
)}
{contentTab === 'custom' && (
<>
<div className="admin-section-header">
<h3>Custom Links</h3>
<p>Add links to show in the platform buttons row, footer, or a dedicated "More Resources" section.</p>
</div>
<button type="button" className="btn-admin-remove" onClick={() => removeBlock(block.id)}>
Remove
{(form.customLinks ?? []).map(link => (
<div key={link.id} className="admin-array-row">
<div className="admin-array-fields">
<div className="admin-field">
<label htmlFor={`link-label-${link.id}`}>Label</label>
<input
id={`link-label-${link.id}`}
type="text"
value={link.label}
placeholder="e.g. iHeart Radio"
onChange={e => updateLink(link.id, 'label', e.target.value)}
/>
</div>
<div className="admin-field">
<label htmlFor={`link-url-${link.id}`}>URL</label>
<input
id={`link-url-${link.id}`}
type="url"
value={link.url}
placeholder="https://..."
onChange={e => updateLink(link.id, 'url', e.target.value)}
/>
</div>
<div className="admin-field">
<label htmlFor={`link-placement-${link.id}`}>Show in</label>
<select
id={`link-placement-${link.id}`}
value={link.placement}
onChange={e => updateLink(link.id, 'placement', e.target.value)}
>
<option value="platforms">Platform Buttons (Listen section)</option>
<option value="footer">Footer Nav</option>
<option value="resources">More Resources Section</option>
</select>
</div>
</div>
<button type="button" className="btn-admin-remove" onClick={() => removeLink(link.id)}>
Remove
</button>
</div>
))}
<button type="button" className="btn-admin-add" onClick={addLink}>
+ Add Link
</button>
</div>
))}
<button type="button" className="btn-admin-add" onClick={addBlock}>
+ Add Content Block
</button>
<div className="admin-section-header">
<h3>Custom Content Blocks</h3>
<p>Add extra text sections. They appear below the share/QR section on the site.</p>
</div>
{(form.customBlocks ?? []).map(block => (
<div key={block.id} className="admin-array-row">
<div className="admin-array-fields">
<div className="admin-field">
<label htmlFor={`block-heading-${block.id}`}>Heading</label>
<input
id={`block-heading-${block.id}`}
type="text"
value={block.heading}
placeholder="Section heading"
onChange={e => updateBlock(block.id, 'heading', e.target.value)}
/>
</div>
<div className="admin-field">
<label htmlFor={`block-body-${block.id}`}>Body Text</label>
<textarea
id={`block-body-${block.id}`}
value={block.body}
rows={3}
placeholder="Write your content here…"
onChange={e => updateBlock(block.id, 'body', e.target.value)}
/>
</div>
</div>
<button type="button" className="btn-admin-remove" onClick={() => removeBlock(block.id)}>
Remove
</button>
</div>
))}
<button type="button" className="btn-admin-add" onClick={addBlock}>
+ Add Content Block
</button>
</>
)}
<div className="admin-actions">
<button
@@ -254,6 +784,7 @@ export default function AdminPage({ content, onSave }: Props) {
<p className="admin-status admin-status--err"> {errorMsg}</p>
)}
</form>
)}
</div>
</div>
)