mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
The detail surface at /insights/workouts/[id] gains a real heart-rate curve, effort zones, an aspect-true GPS route, and per-kilometre splits — all read from data already stored, no new integration, no migration. - HR curve: one server path with strict provenance — stored WorkoutSamples series first, a raw-PULSE window reconstruction second (quality-gated so sparse data hides rather than lies), nothing third. Adaptive bucketing keeps on-screen density constant across a 20-minute HIIT and a 6-hour ride; a min/max envelope surfaces intervals. - Effort zones: five %HRmax bands via the Tanaka HRmax, with a device's own reported time-in-zone winning when present. Descriptive only. - GPS route: self-rendered inline SVG with an equirectangular cos(midLat) longitude correction (fixes the ~40% horizontal stretch), aspect-clamped viewBox, RDP downsampling, start/end markers, and an optional elevation profile. Nothing leaves the origin — no map tiles. - Per-km splits and a GPX export, both derived client/server-side from the geometry already on the payload. - The endpoint extends additively (hrSeries, zones, splits, sportContext, a reserved insight seam) behind an opt-in compact=1 param that drops the raw sample/timestamp blobs for the web client; without the param the response is unchanged. - Every data-less section now hides instead of rendering an empty card; the growing detail component is split into a workout-detail/ directory. - List rows flag which sessions open into a rich detail.
233 lines
6.5 KiB
TypeScript
233 lines
6.5 KiB
TypeScript
"use client";
|
|
|
|
import { useQuery } from "@tanstack/react-query";
|
|
|
|
import { useAuth } from "@/hooks/use-auth";
|
|
import { queryKeys } from "@/lib/query-keys";
|
|
import { apiGet } from "@/lib/api/api-fetch";
|
|
|
|
/**
|
|
* v1.4.32 — TanStack Query wrapper for `GET /api/workouts`.
|
|
*
|
|
* Consumers:
|
|
* - `/insights/workouts` — the workout list page reads the most
|
|
* recent N workouts and renders them as one-line rows.
|
|
* - `<RecentWorkoutsTile>` — the dashboard tile reads the top 3.
|
|
*
|
|
* Cache key shape:
|
|
* - `["workouts", "recent", { limit, since }]` — keyed on the
|
|
* pagination + filter inputs so the recent-tile and the list page
|
|
* keep separate cache slots without colliding.
|
|
* - `["workouts", id]` — single-workout detail (the workout-detail
|
|
* page consumes this separately via `useWorkoutDetail`).
|
|
*/
|
|
|
|
export interface WorkoutListEntry {
|
|
id: string;
|
|
sportType: string;
|
|
startedAt: string;
|
|
endedAt: string;
|
|
durationSec: number;
|
|
distanceM: number | null;
|
|
activeEnergyKcal: number | null;
|
|
avgHr: number | null;
|
|
maxHr: number | null;
|
|
source: string;
|
|
externalId: string | null;
|
|
/**
|
|
* #67 list glyphs — whether the workout opens into a rich detail with
|
|
* a map / HR curve. Optional so pre-#67 fixtures (and the dashboard
|
|
* recent-tile) still satisfy the type; the list endpoint always sends
|
|
* them.
|
|
*/
|
|
hasRoute?: boolean;
|
|
hasHrSeries?: boolean;
|
|
}
|
|
|
|
export interface WorkoutListMeta {
|
|
total: number;
|
|
limit: number;
|
|
offset: number;
|
|
droppedDuplicates: number;
|
|
}
|
|
|
|
export interface WorkoutListPayload {
|
|
workouts: WorkoutListEntry[];
|
|
meta: WorkoutListMeta;
|
|
}
|
|
|
|
export interface UseWorkoutsOptions {
|
|
/** Page size — defaults to 50, capped at 200 by the server. */
|
|
limit?: number;
|
|
/** Page offset — defaults to 0. */
|
|
offset?: number;
|
|
/**
|
|
* ISO timestamp — only workouts with `startedAt >= since` are
|
|
* returned. The dashboard tile passes a 7-day window; the list page
|
|
* leaves it open so the user can scroll back through history.
|
|
*/
|
|
since?: string;
|
|
/** Optional sport-type filter. Pass through the canonical string. */
|
|
sportType?: string;
|
|
}
|
|
|
|
async function fetchWorkouts(
|
|
opts: UseWorkoutsOptions,
|
|
): Promise<WorkoutListPayload> {
|
|
const params = new URLSearchParams();
|
|
if (opts.limit != null) params.set("limit", String(opts.limit));
|
|
if (opts.offset != null) params.set("offset", String(opts.offset));
|
|
if (opts.since) params.set("since", opts.since);
|
|
if (opts.sportType) params.set("sportType", opts.sportType);
|
|
const query = params.toString();
|
|
const url = query ? `/api/workouts?${query}` : "/api/workouts";
|
|
|
|
return apiGet<WorkoutListPayload>(url);
|
|
}
|
|
|
|
export interface UseWorkoutsResult {
|
|
data: WorkoutListPayload | undefined;
|
|
isLoading: boolean;
|
|
isEmpty: boolean;
|
|
error: Error | null;
|
|
/** True once the query has exhausted retries and settled on a failure. */
|
|
isError: boolean;
|
|
/** Re-runs the query — the retry action for a failed fetch. */
|
|
refetch: () => void;
|
|
}
|
|
|
|
export function useWorkouts(opts: UseWorkoutsOptions = {}): UseWorkoutsResult {
|
|
const { isAuthenticated } = useAuth();
|
|
|
|
const query = useQuery({
|
|
queryKey: queryKeys.workoutsRecentList({
|
|
limit: opts.limit,
|
|
offset: opts.offset,
|
|
since: opts.since,
|
|
sportType: opts.sportType,
|
|
}),
|
|
queryFn: () => fetchWorkouts(opts),
|
|
enabled: isAuthenticated,
|
|
staleTime: 60 * 1000,
|
|
});
|
|
|
|
const isEmpty =
|
|
Boolean(isAuthenticated) &&
|
|
query.data !== undefined &&
|
|
query.data.workouts.length === 0;
|
|
|
|
return {
|
|
data: query.data,
|
|
isLoading: query.isLoading,
|
|
isEmpty,
|
|
error: query.error as Error | null,
|
|
isError: query.isError,
|
|
refetch: () => void query.refetch(),
|
|
};
|
|
}
|
|
|
|
export interface WorkoutHrSeriesPoint {
|
|
tSec: number;
|
|
mean: number;
|
|
min: number;
|
|
max: number;
|
|
}
|
|
|
|
export interface WorkoutHrSeriesDto {
|
|
source: "workout_series" | "pulse_window";
|
|
bucketSec: number;
|
|
points: WorkoutHrSeriesPoint[];
|
|
envelope: boolean;
|
|
}
|
|
|
|
export interface WorkoutZoneBandDto {
|
|
zone: number;
|
|
lowBpm: number | null;
|
|
highBpm: number | null;
|
|
seconds: number;
|
|
}
|
|
|
|
export interface WorkoutZonesDto {
|
|
model: "whoop" | "tanaka";
|
|
hrMax: number | null;
|
|
zones: WorkoutZoneBandDto[];
|
|
}
|
|
|
|
export interface WorkoutSplitDto {
|
|
km: number;
|
|
durationSec: number;
|
|
paceSecPerKm: number;
|
|
}
|
|
|
|
export interface WorkoutSportContextDto {
|
|
count: number;
|
|
avgDurationSec: number;
|
|
avgDistanceM: number | null;
|
|
avgAvgHr: number | null;
|
|
}
|
|
|
|
/**
|
|
* Reserved Activity-Insight payload (strategic-concept Wave C, bet 5).
|
|
* The wire field is `null` today; the Phase-2 job will populate it and
|
|
* the detail page's seam mounts a card with zero rework. Declared here
|
|
* so the type is stable in advance — widen the union (never change the
|
|
* seam shape) when the job ships.
|
|
*/
|
|
export type WorkoutActivityInsight = null;
|
|
|
|
export interface WorkoutDetailPayload extends WorkoutListEntry {
|
|
minHr: number | null;
|
|
stepCount: number | null;
|
|
elevationM: number | null;
|
|
pauseDurationSec: number | null;
|
|
metadata: unknown;
|
|
route: {
|
|
geometry: unknown;
|
|
sampleTimestamps: string[] | null;
|
|
} | null;
|
|
/**
|
|
* Raw per-workout HR sample envelope. `samples.samples` is dropped
|
|
* (null) under `compact=1` — the web curve reads `hrSeries` instead —
|
|
* but `sampleCount` is retained. Finally declared as of #67.
|
|
*/
|
|
samples: { sampleCount: number; samples: unknown } | null;
|
|
hrSeries: WorkoutHrSeriesDto | null;
|
|
zones: WorkoutZonesDto | null;
|
|
splits: WorkoutSplitDto[] | null;
|
|
sportContext: WorkoutSportContextDto | null;
|
|
aiInsight: WorkoutActivityInsight;
|
|
canonicalId: string;
|
|
}
|
|
|
|
async function fetchWorkoutDetail(id: string): Promise<WorkoutDetailPayload> {
|
|
// Web always sends `compact=1`: the SVG needs geometry, not the raw
|
|
// 30k-sample / route-timestamp blobs (those ride the iOS path only).
|
|
return apiGet<WorkoutDetailPayload>(
|
|
`/api/workouts/${encodeURIComponent(id)}?compact=1`,
|
|
);
|
|
}
|
|
|
|
export interface UseWorkoutDetailResult {
|
|
data: WorkoutDetailPayload | undefined;
|
|
isLoading: boolean;
|
|
error: Error | null;
|
|
/** Re-runs the query — the retry action for the detail error card. */
|
|
refetch: () => void;
|
|
}
|
|
|
|
export function useWorkoutDetail(id: string): UseWorkoutDetailResult {
|
|
const { isAuthenticated } = useAuth();
|
|
const query = useQuery({
|
|
queryKey: queryKeys.workoutDetail(id),
|
|
queryFn: () => fetchWorkoutDetail(id),
|
|
enabled: isAuthenticated && id.length > 0,
|
|
staleTime: 60 * 1000,
|
|
});
|
|
return {
|
|
data: query.data,
|
|
isLoading: query.isLoading,
|
|
error: query.error as Error | null,
|
|
refetch: () => void query.refetch(),
|
|
};
|
|
}
|