Files
MileVault/frontend/src/pages/DashboardPage.jsx
T
owain 04689a29bd
Build and push images / validate (push) Successful in 3s
Build and push images / build-backend (push) Successful in 6s
Build and push images / build-worker (push) Successful in 4s
Build and push images / build-frontend (push) Successful in 9s
Cut Garmin sync API volume; dashboard/health/records/UI improvements
Garmin Connect sync:
- Incremental syncs now re-fetch only a 1-day buffer (yesterday + today)
  instead of the full lookback window every run. Full lookback applies on
  the first sync only. Cuts steady-state API calls ~10x.
- Beat interval is now configurable via GARMIN_SYNC_INTERVAL_MINUTES and
  surfaced to the UI; the sync toggle is relabelled to the real cadence.

Frontend:
- Collapsible sidebar; clearer logged-in user + role display.
- Unified Body Battery colouring between dashboard and health (shared util).
- Sleep score trend chart on health page.
- Segments + medals on the dashboard's most-recent activity.
- Segments tab on the Records page.

Repo hygiene: add .gitignore, untrack committed __pycache__/*.pyc.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 11:52:52 +01:00

364 lines
17 KiB
React

import { Link, useNavigate } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { useMemo } from 'react'
import { BarChart, Bar, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'
import { startOfWeek, format, subWeeks, eachWeekOfInterval, subDays, addDays } from 'date-fns'
import api from '../utils/api'
import StatCard from '../components/ui/StatCard'
import ActivityMap from '../components/activity/ActivityMap'
import {
formatDuration, formatDistance, formatPace, formatHeartRate, formatElevation,
formatDate, sportIcon, formatSleep,
} from '../utils/format'
import { BB_INFERRED_COLOR, BB_INFERRED_LABEL, bbLevelColor, inferBBType } from '../utils/bodyBattery'
const MEDALS = { 1: '🥇', 2: '🥈', 3: '🥉' }
function Stat({ label, value }) {
return (
<div className="bg-gray-900 px-4 py-3 flex flex-col justify-center">
<p className="text-xs text-gray-500">{label}</p>
<p className="text-lg font-semibold text-white">{value}</p>
</div>
)
}
function MiniBodyBattery({ bb, hires, sleepStart, sleepEnd }) {
const raw = (hires?.length ? hires : bb?.values || []).map(([ts, level]) => ({ ts, level }))
const sleepStartMs = sleepStart ? new Date(sleepStart).getTime() : null
const sleepEndMs = sleepEnd ? new Date(sleepEnd).getTime() : null
// Same classification the Health page uses, so colours match across views.
const data = raw.map((d, i) => ({
...d,
type: inferBBType(d.ts, d.level, i > 0 ? raw[i - 1].level : null, sleepStartMs, sleepEndMs),
}))
const charged = bb?.charged, drained = bb?.drained, end_level = bb?.end_level
const peak = data.length ? Math.max(...data.map(d => d.level)) : end_level
const hasGraph = data.length >= 2
const presentTypes = [...new Set(data.map(d => d.type))]
return (
<div className="bg-gray-900 rounded-xl border border-gray-800 p-4 h-full flex flex-col">
<div className="flex items-center justify-between mb-2">
<h3 className="text-sm font-medium text-gray-300">Body Battery</h3>
<Link to="/health" className="text-xs text-blue-400 hover:underline">View </Link>
</div>
<div className="flex items-baseline gap-3 flex-wrap">
{peak != null && (
<span className="text-3xl font-bold" style={{ color: bbLevelColor(peak) }}>{Math.round(peak)}</span>
)}
{charged != null && <span className="text-sm font-semibold text-green-400">+{charged}</span>}
{drained != null && <span className="text-sm font-semibold text-orange-400">-{drained}</span>}
{end_level != null && <span className="text-xs text-gray-500">now {Math.round(end_level)}</span>}
</div>
{hasGraph ? (
<>
<div className="mt-3 flex-1">
<ResponsiveContainer width="100%" height={70}>
<BarChart data={data} margin={{ top: 2, right: 0, bottom: 0, left: 0 }} barCategoryGap={0}>
<YAxis domain={[0, 100]} hide />
<Tooltip
contentStyle={{ background: '#111827', border: '1px solid #374151', borderRadius: 6, fontSize: 11, color: '#fff' }}
itemStyle={{ color: '#fff' }} labelStyle={{ color: '#fff' }}
labelFormatter={ts => format(new Date(ts), 'HH:mm')}
formatter={v => [`${Math.round(v)}%`, 'Battery']}
/>
<Bar dataKey="level" isAnimationActive={false} radius={0}>
{data.map((d, i) => <Cell key={i} fill={BB_INFERRED_COLOR[d.type]} />)}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
<div className="flex flex-wrap gap-x-3 gap-y-1 mt-2">
{presentTypes.map(type => (
<div key={type} className="flex items-center gap-1">
<div className="w-2 h-2 rounded-sm" style={{ backgroundColor: BB_INFERRED_COLOR[type] }} />
<span className="text-xs text-gray-500">{BB_INFERRED_LABEL[type]}</span>
</div>
))}
</div>
</>
) : (
<p className="text-xs text-gray-600 mt-3">No body battery data today</p>
)}
</div>
)
}
function WeeklyChart({ activities }) {
const navigate = useNavigate()
if (!activities?.length) return (
<div className="flex items-center justify-center h-36 text-gray-600 text-sm">No activities yet</div>
)
// Build last 8 weeks in chronological order
const now = new Date()
const weeks = eachWeekOfInterval({
start: subWeeks(startOfWeek(now), 7),
end: startOfWeek(now),
})
const data = weeks.map(weekStart => {
const weekKey = format(weekStart, 'MMM d')
const weekEnd = addDays(weekStart, 7)
const km = activities
.filter(a => {
const t = new Date(a.start_time)
return t >= weekStart && t < weekEnd
})
.reduce((s, a) => s + (a.distance_m || 0) / 1000, 0)
return {
week: weekKey,
km: parseFloat(km.toFixed(2)),
weekStartISO: format(weekStart, 'yyyy-MM-dd'),
weekEndISO: format(weekEnd, 'yyyy-MM-dd'),
}
})
const handleBarClick = (entry) => {
if (entry?.activePayload?.[0]?.payload) {
const { weekStartISO, weekEndISO } = entry.activePayload[0].payload
navigate(`/activities?from=${weekStartISO}&to=${weekEndISO}`)
}
}
return (
<ResponsiveContainer width="100%" height={140}>
<BarChart data={data} margin={{ top: 4, right: 4, bottom: 4, left: 0 }} barSize={20}
onClick={handleBarClick} style={{ cursor: 'pointer' }}>
<CartesianGrid strokeDasharray="3 3" stroke="#1f2937" vertical={false} />
<XAxis dataKey="week" tick={{ fontSize: 10, fill: '#6b7280' }} axisLine={false} tickLine={false} />
<YAxis tick={{ fontSize: 10, fill: '#6b7280' }} axisLine={false} tickLine={false} width={28}
tickFormatter={v => `${v.toFixed(0)}`} />
<Tooltip contentStyle={{ background: '#111827', border: '1px solid #374151', borderRadius: 8, fontSize: 12 }}
formatter={(v) => [`${v.toFixed(1)} km`, 'Distance']}
cursor={{ fill: 'rgba(59,130,246,0.1)' }} />
<Bar dataKey="km" fill="#3b82f6" radius={[3, 3, 0, 0]} isAnimationActive={false} />
</BarChart>
</ResponsiveContainer>
)
}
export default function DashboardPage() {
const { data: recentActivities } = useQuery({
queryKey: ['activities-recent'],
queryFn: () => api.get('/activities/', { params: { per_page: 10 } }).then(r => r.data),
})
const { data: allActivities } = useQuery({
queryKey: ['activities-all-chart'],
queryFn: () =>
api.get('/activities/', {
params: { per_page: 100, from_date: subDays(new Date(), 60).toISOString() },
}).then(r => r.data),
})
const { data: recentHealth } = useQuery({
queryKey: ['health-metrics', 'dash'],
queryFn: () => api.get('/health-metrics/', { params: { limit: 365 } }).then(r => r.data),
})
// Latest available (non-null) value per metric — Garmin updates some fields
// less often than daily, so "today" can be sparse.
const health = useMemo(() => {
const rows = [...(recentHealth || [])].sort((a, b) => new Date(b.date) - new Date(a.date))
const pick = f => rows.find(d => d[f] != null)?.[f] ?? null
return {
date: rows[0]?.date ? rows[0].date.slice(0, 10) : null, // intraday endpoint wants YYYY-MM-DD
resting_hr: pick('resting_hr'),
sleep_duration_s: pick('sleep_duration_s'),
sleep_start: pick('sleep_start'),
sleep_end: pick('sleep_end'),
hrv_nightly_avg: pick('hrv_nightly_avg'),
sleep_score: pick('sleep_score'),
steps: pick('steps'),
vo2max: pick('vo2max'),
avg_stress: pick('avg_stress'),
}
}, [recentHealth])
const { data: intraday } = useQuery({
queryKey: ['health-intraday-dash', health.date],
queryFn: () => api.get('/health-metrics/intraday', { params: { date: health.date } }).then(r => r.data),
enabled: !!health.date,
})
const { data: records } = useQuery({
queryKey: ['records-running'],
queryFn: () => api.get('/records/', { params: { sport_type: 'running' } }).then(r => r.data),
})
const { data: ytdStats } = useQuery({
queryKey: ['ytd-stats'],
queryFn: () => api.get('/activities/stats/ytd').then(r => r.data),
})
const featured = recentActivities?.[0]
const { data: featuredSegments } = useQuery({
queryKey: ['activity-segments', featured?.id],
queryFn: () => api.get(`/segments/by-activity/${featured.id}`).then(r => r.data),
enabled: !!featured?.id,
})
return (
<div className="p-6 space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold text-white">Dashboard</h1>
<Link to="/upload" className="text-sm text-blue-400 hover:text-blue-300 transition-colors">+ Import data</Link>
</div>
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
<StatCard label="Running this year" value={ytdStats ? `${ytdStats.running_km.toFixed(0)} km` : '--'} accent="blue" />
<StatCard label="Cycling this year" value={ytdStats ? `${ytdStats.cycling_km.toFixed(0)} km` : '--'} accent="orange" />
<StatCard label="Resting HR" value={formatHeartRate(health.resting_hr)} accent="red" />
<StatCard label="Sleep" value={formatSleep(health.sleep_duration_s)} />
</div>
<div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
<div className="lg:col-span-2 bg-gray-900 rounded-xl border border-gray-800 p-4">
<h3 className="text-sm font-medium text-gray-300 mb-3">Weekly distance (km)</h3>
<WeeklyChart activities={allActivities} />
</div>
<div className="lg:col-span-1">
<MiniBodyBattery bb={intraday?.body_battery} hires={intraday?.body_battery_hires}
sleepStart={health.sleep_start} sleepEnd={health.sleep_end} />
</div>
<div className="lg:col-span-1 bg-gray-900 rounded-xl border border-gray-800 p-4 space-y-3">
<h3 className="text-sm font-medium text-gray-300">Health today</h3>
{health.date ? (
<>
{[
['HRV', health.hrv_nightly_avg ? `${Math.round(health.hrv_nightly_avg)} ms` : '--'],
['Sleep score', health.sleep_score ? Math.round(health.sleep_score) : '--'],
['Steps', health.steps?.toLocaleString() ?? '--'],
['VO2 Max', health.vo2max ? health.vo2max.toFixed(1) : '--'],
['Stress', health.avg_stress ? Math.round(health.avg_stress) : '--'],
].map(([label, val]) => (
<div key={label} className="flex justify-between text-sm">
<span className="text-gray-500">{label}</span>
<span className="text-white">{val}</span>
</div>
))}
<Link to="/health" className="block text-xs text-blue-400 hover:underline mt-2">View full health dashboard </Link>
</>
) : (
<p className="text-xs text-gray-600">No health data. Import a Garmin export.</p>
)}
</div>
</div>
{/* Featured most-recent activity */}
{featured && (
<div className="bg-gray-900 rounded-xl border border-gray-800 overflow-hidden">
<div className="flex items-center justify-between px-4 py-3 border-b border-gray-800">
<div className="flex items-center gap-2 min-w-0">
<span className="text-xl">{sportIcon(featured.sport_type)}</span>
<div className="min-w-0">
<Link to={`/activities/${featured.id}`} className="text-sm font-semibold text-white hover:text-blue-400 transition-colors truncate block">
{featured.name}
</Link>
<p className="text-xs text-gray-500">{formatDate(featured.start_time)}</p>
</div>
</div>
<Link to={`/activities/${featured.id}`} className="text-xs text-blue-400 hover:underline flex-shrink-0">Open </Link>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3">
<div className="lg:col-span-2 h-64 bg-gray-950">
{featured.polyline
? <ActivityMap polyline={featured.polyline} sportType={featured.sport_type} colorMode="solid" />
: <div className="flex items-center justify-center h-full text-gray-600 text-sm">No GPS track</div>}
</div>
<div className="grid grid-cols-2 lg:grid-cols-1 gap-px bg-gray-800/50">
<Stat label="Distance" value={formatDistance(featured.distance_m)} />
<Stat label="Elevation ↑" value={formatElevation(featured.elevation_gain_m)} />
<Stat label="Moving time" value={formatDuration(featured.duration_s)} />
<Stat label="Calories" value={featured.calories ? `${Math.round(featured.calories)} kcal` : '--'} />
</div>
</div>
{featuredSegments?.length > 0 && (
<div className="border-t border-gray-800 px-4 py-3">
<div className="flex items-center justify-between mb-2">
<h4 className="text-xs font-medium text-gray-400 uppercase tracking-wide">Segments</h4>
<Link to={`/activities/${featured.id}`} className="text-xs text-blue-400 hover:underline">Details </Link>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-1.5">
{featuredSegments.map(seg => {
const isPodium = seg.rank && seg.rank <= 3
const delta = seg.best_s != null ? seg.duration_s - seg.best_s : null
return (
<div key={seg.segment_id} className="flex items-center gap-2 text-sm">
<span className="flex-1 text-gray-300 text-xs truncate">{seg.name}</span>
<span className={`font-mono text-xs ${isPodium ? 'text-yellow-400 font-semibold' : 'text-gray-200'}`}>
{formatDuration(seg.duration_s)}
</span>
<span className="w-8 text-right text-xs">
{isPodium
? <span title={`#${seg.rank} of ${seg.effort_count}`}>{MEDALS[seg.rank]}</span>
: delta != null
? <span className="text-red-400 font-mono">+{formatDuration(delta)}</span>
: <span className="text-gray-700">--</span>}
</span>
</div>
)
})}
</div>
</div>
)}
</div>
)}
{/* Recent activities */}
<div className="bg-gray-900 rounded-xl border border-gray-800 p-4">
<div className="flex items-center justify-between mb-4">
<h3 className="text-sm font-medium text-gray-300">Recent activities</h3>
<Link to="/activities" className="text-xs text-blue-400 hover:underline">View all </Link>
</div>
<div className="space-y-2">
{recentActivities?.slice(0, 5).map(activity => (
<Link key={activity.id} to={`/activities/${activity.id}`}
className="flex items-center gap-3 py-2 border-b border-gray-800/50 hover:bg-gray-800/30 rounded-lg px-2 -mx-2 transition-colors">
<span className="text-lg">{sportIcon(activity.sport_type)}</span>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-white truncate">{activity.name}</p>
<p className="text-xs text-gray-500">{formatDate(activity.start_time)}</p>
</div>
<div className="flex gap-4 text-sm text-right">
<div><p className="text-gray-200">{formatDistance(activity.distance_m)}</p><p className="text-xs text-gray-600">dist</p></div>
<div><p className="text-gray-200">{formatDuration(activity.duration_s)}</p><p className="text-xs text-gray-600">time</p></div>
<div><p className="text-red-400">{formatHeartRate(activity.avg_heart_rate)}</p><p className="text-xs text-gray-600">HR</p></div>
</div>
</Link>
))}
{!recentActivities?.length && (
<p className="text-gray-600 text-sm text-center py-8">
No activities yet <Link to="/upload" className="text-blue-400 hover:underline">import some data</Link>
</p>
)}
</div>
</div>
{records?.length > 0 && (
<div className="bg-gray-900 rounded-xl border border-gray-800 p-4">
<div className="flex items-center justify-between mb-4">
<h3 className="text-sm font-medium text-gray-300">Running PRs</h3>
<Link to="/records" className="text-xs text-blue-400 hover:underline">View all </Link>
</div>
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
{records.slice(0, 5).map(rec => (
<div key={rec.id} className="bg-gray-800/60 rounded-lg p-3 text-center">
<p className="text-xs text-gray-500 mb-1">{rec.distance_label}</p>
<p className="font-mono font-semibold text-yellow-400">{formatDuration(rec.duration_s)}</p>
</div>
))}
</div>
</div>
)}
</div>
)
}