diff --git a/messages/de.json b/messages/de.json index 168a8cd97..4eccd9736 100644 --- a/messages/de.json +++ b/messages/de.json @@ -5545,7 +5545,7 @@ "nightscoutDisconnectTitle": "Nightscout trennen?", "nightscoutDisconnectDescription": "Künftige Synchronisierungen stoppen. Bereits importierte Glukosewerte bleiben in deinem Verlauf.", "polar": "Polar", - "polarDescription": "Verbinde dein Polar-Konto, um Nightly-Recharge-Erholung, Schlafphasen und tägliche Aktivität zu synchronisieren.", + "polarDescription": "Verbinde dein Polar-Konto, um Nightly-Recharge-Erholung, Schlafphasen, tägliche Aktivität und Trainingseinheiten zu synchronisieren.", "polarViewData": "Schlaf & Erholung ansehen", "polarHelp": "Melde dich bei Polar an, um den Zugriff zu erlauben. Daten werden stündlich im Hintergrund abgerufen.", "polarCredentials": "API-Zugangsdaten", diff --git a/messages/en.json b/messages/en.json index 257b7cfbe..d15eec67f 100644 --- a/messages/en.json +++ b/messages/en.json @@ -5535,7 +5535,7 @@ "nightscoutDisconnectTitle": "Disconnect Nightscout?", "nightscoutDisconnectDescription": "Future syncs stop. Glucose readings already imported stay in your history.", "polar": "Polar", - "polarDescription": "Connect your Polar account to sync Nightly Recharge recovery, sleep stages, and daily activity.", + "polarDescription": "Connect your Polar account to sync Nightly Recharge recovery, sleep stages, daily activity, and training sessions.", "polarViewData": "View your sleep & recovery", "polarHelp": "Sign in with Polar to grant access. Data is pulled in the background once an hour.", "polarCredentials": "API Credentials", diff --git a/messages/es.json b/messages/es.json index 8ef65c75d..846f043ad 100644 --- a/messages/es.json +++ b/messages/es.json @@ -5547,7 +5547,7 @@ "nightscoutDisconnectTitle": "¿Desconectar Nightscout?", "nightscoutDisconnectDescription": "Las sincronizaciones futuras se detienen. Las lecturas de glucosa ya importadas permanecen en tu historial.", "polar": "Polar", - "polarDescription": "Conecta tu cuenta de Polar para sincronizar la recuperación Nightly Recharge, fases de sueño y actividad diaria.", + "polarDescription": "Conecta tu cuenta de Polar para sincronizar la recuperación Nightly Recharge, fases de sueño, actividad diaria y sesiones de entrenamiento.", "polarViewData": "Ver tu sueño y recuperación", "polarHelp": "Inicia sesión en Polar para conceder acceso. Los datos se obtienen en segundo plano una vez por hora.", "polarCredentials": "Credenciales de API", diff --git a/messages/fr.json b/messages/fr.json index a40154fb5..0f4af6e6e 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -5549,7 +5549,7 @@ "nightscoutDisconnectTitle": "Déconnecter Nightscout ?", "nightscoutDisconnectDescription": "Les synchronisations futures s'arrêtent. Les mesures de glycémie déjà importées restent dans votre historique.", "polar": "Polar", - "polarDescription": "Connecte ton compte Polar pour synchroniser la récupération Nightly Recharge, les phases de sommeil et l'activité.", + "polarDescription": "Connecte ton compte Polar pour synchroniser la récupération Nightly Recharge, les phases de sommeil, l'activité et les séances d'entraînement.", "polarViewData": "Voir votre sommeil et récupération", "polarHelp": "Connectez-vous à Polar pour accorder l'accès. Les données sont récupérées en arrière-plan une fois par heure.", "polarCredentials": "Identifiants API", diff --git a/messages/it.json b/messages/it.json index dfeb62985..28a474487 100644 --- a/messages/it.json +++ b/messages/it.json @@ -5539,7 +5539,7 @@ "nightscoutDisconnectTitle": "Disconnettere Nightscout?", "nightscoutDisconnectDescription": "Le sincronizzazioni future si interrompono. Le letture della glicemia già importate restano nella tua cronologia.", "polar": "Polar", - "polarDescription": "Collega il tuo account Polar per sincronizzare il recupero Nightly Recharge, le fasi del sonno e l'attività giornaliera.", + "polarDescription": "Collega il tuo account Polar per sincronizzare il recupero Nightly Recharge, le fasi del sonno, l'attività giornaliera e le sessioni di allenamento.", "polarViewData": "Vedi sonno e recupero", "polarHelp": "Accedi a Polar per concedere l'accesso. I dati vengono recuperati in background una volta all'ora.", "polarCredentials": "Credenziali API", diff --git a/messages/pl.json b/messages/pl.json index 33b15221a..d3cc56145 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -5533,7 +5533,7 @@ "nightscoutDisconnectTitle": "Rozłączyć Nightscout?", "nightscoutDisconnectDescription": "Przyszłe synchronizacje zostaną zatrzymane. Już zaimportowane odczyty glukozy pozostaną w historii.", "polar": "Polar", - "polarDescription": "Połącz konto Polar, aby synchronizować regenerację Nightly Recharge, fazy snu i dzienną aktywność.", + "polarDescription": "Połącz konto Polar, aby synchronizować regenerację Nightly Recharge, fazy snu, dzienną aktywność i treningi.", "polarViewData": "Zobacz sen i regenerację", "polarHelp": "Zaloguj się w Polar, aby przyznać dostęp. Dane są pobierane w tle raz na godzinę.", "polarCredentials": "Dane API", diff --git a/package.json b/package.json index 07988043f..71c76cbdb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "healthlog", - "version": "1.32.14", + "version": "1.32.15", "description": "Self-hosted personal-health-tracking PWA with Withings integration, AI insights, and doctor-report PDF export.", "license": "PolyForm-Noncommercial-1.0.0", "homepage": "https://healthlog.dev", diff --git a/src/lib/jobs/reminder/polar-sync.ts b/src/lib/jobs/reminder/polar-sync.ts index 2ae9c78df..b73efee48 100644 --- a/src/lib/jobs/reminder/polar-sync.ts +++ b/src/lib/jobs/reminder/polar-sync.ts @@ -1,20 +1,58 @@ /** * v1.17.0 (F4) — Polar poll-cohort sync handler. + * v1.32.15 — the per-user arm now runs BOTH Polar legs: vitals + * (`syncUserPolar`) then exercises/workouts (`syncUserPolarWorkouts`). * * Poll-only: Polar AccessLink has a webhook, but HealthLog runs the simpler * poll model (matching Nightscout). One hourly cron tick carries no `userId` * and the handler iterates every user with a stored Polar token, re-syncing - * each via `syncUserPolar`. One user's revoked grant / outage is warned and the - * pass continues. The shared control flow lives in `./poll-cohort`. + * each via `syncUserPolarLegs`. One user's revoked grant / outage is warned and + * the pass continues. The shared control flow lives in `./poll-cohort`. * * The queue name, cron schedule, and boss.work registration live in - * reminder-worker.ts. + * reminder-worker.ts — no new queue: the workout leg rides the existing hourly + * `polar-sync` tick (one extra request per connected user per hour). */ import { syncUserPolar } from "@/lib/polar/sync"; +import { syncUserPolarWorkouts } from "@/lib/polar/sync-workouts"; import { makePollCohortHandler, type PollCohortPayload } from "./poll-cohort"; export type PolarSyncPayload = PollCohortPayload; +/** + * Run both Polar legs for one user with INDEPENDENT attribution on the shared + * `polar` ledger. Sequentially awaited (not `Promise.all`) so a workouts error + * stays attributable. Each leg records its own failure; the vitals leg owns the + * single success write. A failure in either leg is isolated — both legs are + * always attempted, so a workouts-leg failure can never mask a vitals success + * and vice versa — then the FIRST error is rethrown so the cohort handler warns + * and skips this user's success accounting without losing the error. + */ +export async function syncUserPolarLegs(userId: string): Promise { + let total = 0; + let firstError: unknown; + let hadError = false; + + try { + total += await syncUserPolar(userId); + } catch (err) { + firstError = err; + hadError = true; + } + + try { + total += await syncUserPolarWorkouts(userId); + } catch (err) { + if (!hadError) { + firstError = err; + hadError = true; + } + } + + if (hadError) throw firstError; + return total; +} + export const handlePolarSync = makePollCohortHandler({ taskName: "job.polar_sync", findCohort: async (prisma) => { @@ -24,5 +62,5 @@ export const handlePolarSync = makePollCohortHandler({ }); return users.map((u) => u.id); }, - syncUser: syncUserPolar, + syncUser: syncUserPolarLegs, }); diff --git a/src/lib/polar/client.ts b/src/lib/polar/client.ts index 5679d7a8c..de3a4dc94 100644 --- a/src/lib/polar/client.ts +++ b/src/lib/polar/client.ts @@ -24,7 +24,10 @@ import { getEvent } from "@/lib/logging/context"; import { canonicalDailyTimestamp } from "@/lib/measurements/consolidation-tz"; import { safeFetch } from "@/lib/safe-fetch"; import { reconstructContiguousSleepTimeline } from "@/lib/sleep/reconstruct-timeline"; +import type { Prisma } from "@/generated/prisma/client"; +import type { WorkoutSportType } from "@/lib/validations/workout"; import { PolarApiError, classifyPolarResponse } from "./response-classifier"; +import { mapPolarSportType } from "./sport-map"; const POLAR_API_BASE = "https://www.polaraccesslink.com"; const POLAR_OAUTH_AUTH_URL = "https://flow.polar.com/oauth2/authorization"; @@ -651,3 +654,272 @@ export function mapSpo2(r: PolarSpo2): MappedMeasurement[] { }, ]; } + +// ─── Exercises (workouts) ────────────────────────────────────── + +/** + * One Polar AccessLink exercise (`GET /v3/exercises`) — the stateless list of + * the last 30 days of uploads. The transaction model is DEPRECATED; this GET + * carries NO userId in the path (the user is identified by the Bearer token), + * exactly the shape the v1.31.2 vitals-endpoint fix established. + * + * Field types are conservative on purpose — the live payload's exact per-field + * nullability and the `id` type are not machine-verified, so `id` accepts + * string OR number (coerced to a stable string externalId) and every optional + * numeric is guarded before use. + */ +export interface PolarExercise { + /** Opaque exercise id. Polar's docs leave the type ambiguous; accept either + * and coerce to a stable string externalId (never parsed). */ + id?: string | number | null; + /** ISO-8601 local start time, e.g. `"2026-06-10T07:00:00"`. May or may not + * carry a zone suffix — handled defensively at map time. */ + start_time?: string | null; + /** Minutes east of UTC for `start_time`. Combined with `start_time` to + * recover the true UTC instant. */ + start_time_utc_offset?: number | null; + /** ISO-8601 duration, e.g. `"PT2H44M30S"`. */ + duration?: string | null; + /** Coarse sport enum, e.g. `"RUNNING"`. */ + sport?: string | null; + /** Granular sport enum, e.g. `"TRAIL_RUNNING"`. */ + detailed_sport_info?: string | null; + calories?: number | null; + /** Distance in METRES. */ + distance?: number | null; + heart_rate?: { + average?: number | null; + maximum?: number | null; + } | null; + training_load?: number | null; + device?: string | null; + device_id?: string | null; +} + +/** + * Candidate envelope keys a paged `/v3/exercises` response might nest the list + * under. Polar's pagination shape on this endpoint is not verified; the fetcher + * tolerates a bare array OR any of these envelope shapes so a paged response + * degrades to "the rows on this page" rather than an empty result. The 30-day + * window is small enough that a single page covers a normal user; if Polar + * paginates, the hourly poll re-reads the whole window every tick so nothing is + * lost between pages. + */ +const EXERCISE_LIST_KEYS = ["exercises", "data", "items", "records"] as const; + +/** + * Fetch the user's exercises (`GET /v3/exercises`). Summary only — the + * `samples` / `zones` / `route` inline params are deliberately omitted (route / + * per-sample import is out of scope). Returns `[]` on 204 No Content, a bare + * array, or a paged envelope whose list key is unrecognised. Throws a + * classified `PolarApiError` on a non-2xx — including a 403, which the workout + * sync classifies as a soft/recoverable integration error so a scope gap on + * exercises never hard-fails the whole Polar sync. + */ +export async function fetchExercises( + accessToken: string, +): Promise { + const start = performance.now(); + const res = await safeFetch(`${POLAR_API_BASE}/v3/exercises`, { + method: "GET", + headers: { + Authorization: `Bearer ${accessToken}`, + Accept: "application/json", + }, + }); + const verdict = classifyPolarResponse(res.status); + getEvent()?.addExternalCall({ + service: "polar", + method: "fetchExercises", + duration_ms: Math.round(performance.now() - start), + status: res.status, + error: verdict.classification === "success" ? undefined : verdict.reason, + }); + if (verdict.classification !== "success") { + throw new PolarApiError({ + verb: "fetchExercises", + classification: verdict.classification, + httpStatus: verdict.httpStatus, + reason: verdict.reason, + }); + } + // 204 No Content — a window with no uploads. Polar returns an empty body. + if (res.status === 204) return []; + const json = (await res.json().catch(() => null)) as unknown; + return normaliseExerciseList(json); +} + +/** Coerce a `/v3/exercises` body into a `PolarExercise[]`: a bare array, a + * paged envelope (list under one of `EXERCISE_LIST_KEYS`), or `[]` otherwise. */ +export function normaliseExerciseList(json: unknown): PolarExercise[] { + if (!json) return []; + if (Array.isArray(json)) return json as PolarExercise[]; + if (typeof json === "object") { + const obj = json as Record; + for (const key of EXERCISE_LIST_KEYS) { + const list = obj[key]; + if (Array.isArray(list)) return list as PolarExercise[]; + } + } + return []; +} + +// ─── Exercise → Workout mapping ──────────────────────────────── + +/** The `Workout`-row payload a mapped Polar exercise produces. Field names + * mirror `prisma.workout` columns; the sync layer stamps `source = POLAR` + + * `externalId` and upserts on `(userId, source, externalId)`. Mirrors + * `StravaWorkoutRow`. */ +export interface PolarWorkoutRow { + externalId: string; + sportType: WorkoutSportType; + startedAt: Date; + endedAt: Date; + durationSec: number; + totalEnergyKcal: number | null; + totalDistanceM: number | null; + avgHeartRate: number | null; + maxHeartRate: number | null; + elevationM: number | null; + metadata: Prisma.InputJsonValue; +} + +function nonNegInt(n: number | null | undefined): number | null { + if (typeof n !== "number" || !Number.isFinite(n) || n < 0) return null; + return Math.round(n); +} + +function nonNegFloat(n: number | null | undefined): number | null { + if (typeof n !== "number" || !Number.isFinite(n) || n < 0) return null; + return n; +} + +/** True when an ISO-8601 datetime string already carries a zone designator + * (`Z` or `±HH:MM` / `±HHMM`). Drives the two branches of start-time + * composition. */ +function hasZoneDesignator(iso: string): boolean { + return /(?:Z|[+-]\d{2}:?\d{2})$/.test(iso.trim()); +} + +/** + * Combine Polar's `start_time` + `start_time_utc_offset` into the true UTC + * instant. + * + * Two cases, because whether `start_time` carries a zone suffix is not verified + * against the live payload: + * - It already has a zone (`…Z` / `…+02:00`): `Date.parse` yields the correct + * instant directly; the offset is NOT applied again. + * - No zone (a naive local wall-clock, the documented shape): interpret the + * wall-clock AS UTC (append `Z`), then subtract the offset minutes (east of + * UTC is positive) to recover the true instant. A missing / non-finite + * offset falls back to 0 (treat the wall-clock as UTC). + * + * Returns null for a missing / unparseable start (the row is skipped, mirroring + * Strava's NaN-start guard). + */ +export function combinePolarStart( + startTime: string | null | undefined, + offsetMinutes: number | null | undefined, +): Date | null { + if (typeof startTime !== "string" || startTime.trim() === "") return null; + const trimmed = startTime.trim(); + if (hasZoneDesignator(trimmed)) { + const ms = Date.parse(trimmed); + return Number.isNaN(ms) ? null : new Date(ms); + } + const asUtcMs = Date.parse(`${trimmed}Z`); + if (Number.isNaN(asUtcMs)) return null; + const offset = + typeof offsetMinutes === "number" && Number.isFinite(offsetMinutes) + ? offsetMinutes + : 0; + return new Date(asUtcMs - offset * 60_000); +} + +const ISO_DURATION_RE = + /^P(?:(\d+(?:\.\d+)?)D)?(?:T(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?)?$/i; + +/** + * Parse an ISO-8601 duration (`PT2H44M30S`, `PT45S`, `P1DT2H`, fractional + * seconds allowed) to whole seconds. Malformed / empty input → 0, mirroring + * Strava's `durationSec ?? 0` fallback so a bad duration never produces a + * negative window. Hand-rolled — no new dependency. + */ +export function parseIsoDuration(raw: string | null | undefined): number { + if (typeof raw !== "string") return 0; + const m = ISO_DURATION_RE.exec(raw.trim()); + if (!m) return 0; + const [, days, hours, minutes, seconds] = m; + const total = + (days ? parseFloat(days) * 86_400 : 0) + + (hours ? parseFloat(hours) * 3_600 : 0) + + (minutes ? parseFloat(minutes) * 60 : 0) + + (seconds ? parseFloat(seconds) : 0); + if (!Number.isFinite(total) || total < 0) return 0; + return Math.round(total); +} + +/** + * Map one Polar exercise into a `Workout` row. `detailed_sport_info` is + * preferred over the coarse `sport`, then mapped through `mapPolarSportType()` + * to a canonical `WorkoutSportType` — the raw Polar labels are never written to + * `sportType` directly (kept in `metadata` for provenance). `startedAt` is the + * UTC instant recovered from `start_time` + `start_time_utc_offset`; `endedAt` + * is `startedAt + durationSec` (Polar exposes no explicit end). `training_load` + * rides `metadata` tied to this row (the WHOOP per-workout-strain precedent), + * never a free-floating Measurement that would survive read-time dedup. + * + * Returns null for an exercise with no id or no parseable start instant + * (nothing to store) — the sync layer skips it, never throws per-row. + */ +export function mapExercise(ex: PolarExercise): PolarWorkoutRow | null { + if (ex.id === null || ex.id === undefined) return null; + const externalId = String(ex.id); + if (externalId.trim() === "") return null; + + const startedAt = combinePolarStart(ex.start_time, ex.start_time_utc_offset); + if (!startedAt) return null; + + const durationSec = parseIsoDuration(ex.duration); + const endedAt = new Date(startedAt.getTime() + durationSec * 1000); + + const sportType = mapPolarSportType(ex.detailed_sport_info, ex.sport); + + const avgHeartRate = nonNegInt(ex.heart_rate?.average); + const maxHeartRate = nonNegInt(ex.heart_rate?.maximum); + + const metadata: Prisma.InputJsonValue = { + // Raw pre-mapping labels, kept for provenance/debugging — never used as the + // canonical `sportType` (see `mapPolarSportType()`). + ...(ex.sport ? { polarSport: ex.sport } : {}), + ...(ex.detailed_sport_info + ? { polarDetailedSportInfo: ex.detailed_sport_info } + : {}), + ...(ex.device ? { polarDevice: ex.device } : {}), + ...(ex.device_id ? { polarDeviceId: ex.device_id } : {}), + ...(typeof ex.training_load === "number" && + Number.isFinite(ex.training_load) + ? { trainingLoad: ex.training_load } + : {}), + ...(typeof ex.start_time_utc_offset === "number" && + Number.isFinite(ex.start_time_utc_offset) + ? { startTimeUtcOffset: ex.start_time_utc_offset } + : {}), + }; + + return { + externalId, + sportType, + startedAt, + endedAt, + durationSec, + totalEnergyKcal: nonNegFloat(ex.calories), + totalDistanceM: nonNegFloat(ex.distance), + avgHeartRate, + maxHeartRate, + // Not on the exercise summary — deriving it would require a GPX fetch + // (out of scope). Left null. + elevationM: null, + metadata, + }; +} diff --git a/src/lib/polar/sport-map.ts b/src/lib/polar/sport-map.ts new file mode 100644 index 000000000..6fccb39e9 --- /dev/null +++ b/src/lib/polar/sport-map.ts @@ -0,0 +1,213 @@ +/** + * Polar exercise sport (`sport` coarse enum, `detailed_sport_info` granular + * enum) → HealthLog canonical `WorkoutSportType`. + * + * Polar is a WORKOUT source that ships two sport fields on every exercise: a + * coarse `sport` (e.g. `RUNNING`, `CYCLING`) and a granular + * `detailed_sport_info` (e.g. `TRAIL_RUNNING`, `INDOOR_CYCLING`). The mapper + * prefers the granular value, falls back to the coarse one, then to `"other"`, + * so a row always lands in a canonical bucket the read-time picker can cluster + * — the raw labels are kept in `Workout.metadata` for provenance, never written + * to `sportType` directly. This mirrors the Strava / WHOOP / Fitbit / Google + * Health mappers; shipping a workout source WITHOUT this normalisation is the + * exact Strava launch bug (`src/lib/strava/sport-map.ts:1-58`) where generic + * rows collapsed same-source back-to-back sessions. + * + * `POLAR_SPORT_TABLE` is the single source of truth — `POLAR_SPORT_MAP` derives + * from it. Keep this list — and only this list — in sync when Polar adds a + * sport. Both the coarse and granular Polar enum values are listed under the + * same normalised key space, so either field resolves through one lookup. + * + * Bucket choices for sports with no clean 1:1 canonical match follow the SAME + * judgment calls the Strava table documents, so a Polar row and a Strava row of + * the same real-world sport land in the same bucket: + * - paddle sports (canoe, kayak, stand-up paddling) → `"rowing"`. + * - racket / paddle-court sports (badminton, padel, squash, table tennis, + * tennis, pickleball, racquetball) → `"tennis"`. + * - functional / mixed-modal + climbing (functional training, crossfit, + * climbing) → `"crossTraining"`. + * - recovery / mobility work (pilates, stretching, mobility, physiotherapy) + * → `"mindAndBody"`. + * - e-bike / mountain-bike / indoor cycling with no dedicated bucket → + * `"cycling"`. + * - snow-sliding sports (alpine / cross-country / backcountry ski, snowboard, + * roller ski, skating) → `"other"`, same as Strava/WHOOP. + * - team / niche sports with no matching bucket (ice hockey, floorball, + * handball, volleyball, martial arts, boxing, water sports, surfing, + * sailing, skateboarding, triathlon, group exercise, generic + * indoor/outdoor) → `"other"` — the row still persists, just outside a + * canonical sport bucket, matching an unmapped Strava/Fitbit activity. + * + * The Polar sport enum is broad and not published as a single machine-readable + * list, so this table covers the documented profiles; any value it hasn't + * caught up with lands on `"other"` (the row persists), which is the defensive + * default the design mandates. + */ +import type { WorkoutSportType } from "@/lib/validations/workout"; + +interface PolarSportTableRow { + /** A Polar `sport` or `detailed_sport_info` enum value (UPPER_SNAKE_CASE). */ + name: string; + canonical: WorkoutSportType; +} + +/** + * Polar sport value → canonical bucket. Grouped by canonical bucket for + * readability; both the coarse `sport` values and the common + * `detailed_sport_info` values share this one key space (the normaliser folds + * case + strips separators so `"TRAIL_RUNNING"` and `"trailrunning"` collide). + */ +export const POLAR_SPORT_TABLE: readonly PolarSportTableRow[] = [ + // ── running ── + { name: "RUNNING", canonical: "running" }, + { name: "JOGGING", canonical: "running" }, + { name: "ROAD_RUNNING", canonical: "running" }, + { name: "TRACK_AND_FIELD_RUNNING", canonical: "running" }, + { name: "TRAIL_RUNNING", canonical: "running" }, + { name: "TREADMILL_RUNNING", canonical: "running" }, + { name: "ULTRA_RUNNING", canonical: "running" }, + // ── cycling ── + { name: "CYCLING", canonical: "cycling" }, + { name: "ROAD_BIKING", canonical: "cycling" }, + { name: "INDOOR_CYCLING", canonical: "cycling" }, + { name: "MOUNTAIN_BIKING", canonical: "cycling" }, + { name: "GRAVEL_CYCLING", canonical: "cycling" }, + { name: "E_BIKE", canonical: "cycling" }, + { name: "EBIKE", canonical: "cycling" }, + { name: "HANDCYCLING", canonical: "cycling" }, + // ── walking ── + { name: "WALKING", canonical: "walking" }, + { name: "NORDIC_WALKING", canonical: "walking" }, + // ── hiking ── + { name: "HIKING", canonical: "hiking" }, + { name: "TREKKING", canonical: "hiking" }, + { name: "MOUNTAIN_HIKING", canonical: "hiking" }, + { name: "SNOWSHOE_TREKKING", canonical: "hiking" }, + // ── swimming ── + { name: "SWIMMING", canonical: "swimming" }, + { name: "POOL_SWIMMING", canonical: "swimming" }, + { name: "OPEN_WATER_SWIMMING", canonical: "swimming" }, + // ── rowing / paddle ── + { name: "ROWING", canonical: "rowing" }, + { name: "INDOOR_ROWING", canonical: "rowing" }, + { name: "KAYAKING", canonical: "rowing" }, + { name: "CANOEING", canonical: "rowing" }, + { name: "STAND_UP_PADDLING", canonical: "rowing" }, + { name: "PADDLING", canonical: "rowing" }, + // ── elliptical / stair ── + { name: "ELLIPTICAL", canonical: "elliptical" }, + { name: "CROSS_TRAINER", canonical: "elliptical" }, + { name: "STAIR_CLIMBING", canonical: "stairClimber" }, + { name: "STEP_MACHINE", canonical: "stairClimber" }, + // ── strength ── + { name: "STRENGTH_TRAINING", canonical: "strength" }, + { name: "CORE", canonical: "strength" }, + // ── HIIT ── + { name: "HIIT", canonical: "hiit" }, + { name: "HIGH_INTENSITY_INTERVAL_TRAINING", canonical: "hiit" }, + { name: "CIRCUIT_TRAINING", canonical: "hiit" }, + // ── functional / cross-training + climbing ── + { name: "FUNCTIONAL_TRAINING", canonical: "crossTraining" }, + { name: "CROSSFIT", canonical: "crossTraining" }, + { name: "CLIMBING", canonical: "crossTraining" }, + { name: "INDOOR_CLIMBING", canonical: "crossTraining" }, + { name: "ROCK_CLIMBING", canonical: "crossTraining" }, + // ── yoga / mind & body ── + { name: "YOGA", canonical: "yoga" }, + { name: "PILATES", canonical: "mindAndBody" }, + { name: "STRETCHING", canonical: "mindAndBody" }, + { name: "MOBILITY_STATIC", canonical: "mindAndBody" }, + { name: "MOBILITY_DYNAMIC", canonical: "mindAndBody" }, + { name: "PHYSICAL_THERAPY", canonical: "mindAndBody" }, + // ── dance ── + { name: "DANCE", canonical: "dance" }, + { name: "DANCING", canonical: "dance" }, + { name: "ZUMBA", canonical: "dance" }, + { name: "AEROBICS", canonical: "dance" }, + // ── golf ── + { name: "GOLF", canonical: "golf" }, + // ── racket / paddle-court ── + { name: "TENNIS", canonical: "tennis" }, + { name: "TABLE_TENNIS", canonical: "tennis" }, + { name: "BADMINTON", canonical: "tennis" }, + { name: "SQUASH", canonical: "tennis" }, + { name: "PADEL", canonical: "tennis" }, + { name: "PICKLEBALL", canonical: "tennis" }, + { name: "RACQUETBALL", canonical: "tennis" }, + // ── basketball / soccer ── + { name: "BASKETBALL", canonical: "basketball" }, + { name: "SOCCER", canonical: "soccer" }, + { name: "FOOTBALL", canonical: "soccer" }, + // ── other: snow-sliding ── + { name: "ALPINE_SKIING", canonical: "other" }, + { name: "CROSS_COUNTRY_SKIING_CLASSIC", canonical: "other" }, + { name: "CROSS_COUNTRY_SKIING_FREESTYLE", canonical: "other" }, + { name: "BACKCOUNTRY_SKIING", canonical: "other" }, + { name: "SNOWBOARDING", canonical: "other" }, + { name: "ROLLER_SKIING_CLASSIC", canonical: "other" }, + { name: "ROLLER_SKIING_FREESTYLE", canonical: "other" }, + { name: "SKATING", canonical: "other" }, + { name: "ICE_SKATING", canonical: "other" }, + // ── other: team / niche / catch-all ── + { name: "VOLLEYBALL", canonical: "other" }, + { name: "ICE_HOCKEY", canonical: "other" }, + { name: "FLOORBALL", canonical: "other" }, + { name: "HANDBALL", canonical: "other" }, + { name: "MARTIAL_ARTS", canonical: "other" }, + { name: "BOXING", canonical: "other" }, + { name: "KICKBOXING", canonical: "other" }, + { name: "WATER_SPORTS", canonical: "other" }, + { name: "SURFING", canonical: "other" }, + { name: "WINDSURFING", canonical: "other" }, + { name: "KITESURFING", canonical: "other" }, + { name: "SAILING", canonical: "other" }, + { name: "SKATEBOARDING", canonical: "other" }, + { name: "TRIATHLON", canonical: "other" }, + { name: "GROUP_EXERCISE", canonical: "other" }, + { name: "OTHER_INDOOR", canonical: "other" }, + { name: "OTHER_OUTDOOR", canonical: "other" }, +] as const; + +/** + * Lowercase and strip every character outside `[a-z0-9]`. Polar's sport values + * are UPPER_SNAKE_CASE with underscores (`"TRAIL_RUNNING"`), so this folds case + * and drops the separators; applied to BOTH the table names (at build time) and + * the incoming raw value (at lookup time), so a stray space / hyphen / casing + * variant still resolves to the same key. + */ +export function normalisePolarSportKey(raw: string): string { + return raw + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, ""); +} + +export const POLAR_SPORT_MAP: ReadonlyMap = new Map( + POLAR_SPORT_TABLE.map((row) => [ + normalisePolarSportKey(row.name), + row.canonical, + ]), +); + +/** + * Resolve a Polar exercise's sport to a canonical `WorkoutSportType`. Prefers + * the granular `detailed_sport_info`; when that is absent, blank, or + * unrecognised, falls back to the coarse `sport`; defaults to `"other"` for + * anything absent, blank, or unrecognised (a Polar-added sport this table + * hasn't caught up with yet). NEVER returns a raw Polar label. + */ +export function mapPolarSportType( + detailed: string | null | undefined, + coarse: string | null | undefined, +): WorkoutSportType { + const fromDetailed = lookup(detailed); + if (fromDetailed) return fromDetailed; + const fromCoarse = lookup(coarse); + if (fromCoarse) return fromCoarse; + return "other"; +} + +function lookup(raw: string | null | undefined): WorkoutSportType | undefined { + if (typeof raw !== "string" || raw.trim() === "") return undefined; + return POLAR_SPORT_MAP.get(normalisePolarSportKey(raw)); +} diff --git a/src/lib/polar/sync-workouts.ts b/src/lib/polar/sync-workouts.ts new file mode 100644 index 000000000..5e6b6a887 --- /dev/null +++ b/src/lib/polar/sync-workouts.ts @@ -0,0 +1,170 @@ +/** + * v1.32.15 — Polar AccessLink exercise (workout) sync. + * + * Pulls the user's exercises from the stateless `GET /v3/exercises` list (last + * 30 days of uploads, no transaction / no commit / no userId in the path) and + * upserts each into the `Workout` table as `source = POLAR`, keyed on + * `(userId, source, externalId)` so a re-fetch / Polar-side re-analysis + * overwrites in place. Polar exercises are WORKOUT rows, not `Measurement` + * rows, so this file is deliberately SEPARATE from the vitals sync + * (`./sync.ts`) — isolation for a sensitive cohort, mirroring WHOOP's split + * `sync.ts` / `sync-workout.ts`. + * + * Cross-source dedup is NOT done here: a Polar run and the same run via Apple + * Health remain two distinct `Workout` rows (different `source`); the read-time + * `pickCanonicalWorkoutRows` picker collapses the cross-source twin via the + * user's source-priority ladder. One engine, no parallel path. + * + * Idempotency: every tick re-reads the whole 30-day window; the unique index + * makes a re-ingest a no-op-shaped overwrite. There is no commit / acknowledge + * step to fail (the deprecated transaction model had one), so ingest is the + * only write and it is idempotent — no cursor, no backfill queue (the API caps + * history at 30 days, so first-connect backfill IS the first regular tick). + * + * Ledger: workouts and vitals share the single `polar` integration ledger. This + * leg records only its OWN FAILURE (and rethrows so the cohort handler can + * attribute it); the single success write stays the vitals leg's job so a fully + * successful pass records success exactly once. A workouts-leg failure records a + * transient/reauth failure on the shared ledger but never touches the vitals + * success timestamp (`recordSyncFailure` leaves `lastSuccessAt` intact). + */ +import { prisma } from "@/lib/db"; +import { emitInsertedWorkoutArrival } from "@/lib/arrivals/workout-emit"; +import { annotate, getEvent } from "@/lib/logging/context"; +import { recordSyncFailure } from "@/lib/integrations/status"; +import { fetchExercises, mapExercise, type PolarWorkoutRow } from "./client"; +import { getPolarConnection } from "./credentials"; +import { PolarApiError } from "./response-classifier"; +import { classifyPolarFailure } from "./sync"; + +async function recordPolarWorkoutFailure( + userId: string, + err: unknown, +): Promise { + await recordSyncFailure({ + userId, + integration: "polar", + kind: classifyPolarFailure(err), + message: err instanceof Error ? err.message : String(err), + errorCode: + err instanceof PolarApiError && err.httpStatus != null + ? String(err.httpStatus) + : undefined, + }); +} + +/** + * Sync one user's Polar exercises into `Workout`. Returns the count of rows + * written. A user with no Polar connection is a clean no-op (returns 0, touches + * no status row). + * + * A 403 on the exercises read (a scope gap under `accesslink.read_all`) is + * classified through the shared response classifier as `reauth_required` — a + * SOFT/recoverable integration error surfaced on the status ledger, NOT a hard + * crash: it is recorded and rethrown so the composite cohort pass isolates this + * user and the vitals leg's own result is untouched. + */ +export async function syncUserPolarWorkouts(userId: string): Promise { + const conn = await getPolarConnection(userId); + if (!conn) return 0; + + let rows: PolarWorkoutRow[]; + try { + const exercises = await fetchExercises(conn.accessToken); + rows = []; + for (const ex of exercises) { + const row = mapExercise(ex); + // Skip an unmappable exercise (no id / unparseable start); never throw + // per-row — one bad record must not fail the whole leg. + if (row) rows.push(row); + } + } catch (err) { + await recordPolarWorkoutFailure(userId, err); + throw err; + } + + let imported: number; + try { + imported = await upsertPolarWorkouts(userId, rows); + } catch (err) { + await recordPolarWorkoutFailure(userId, err); + throw err; + } + + return imported; +} + +/** + * Upsert a batch of mapped Polar exercises into `Workout`, keyed on + * `(userId, source = POLAR, externalId)` so a re-fetch overwrites in place. A + * line-for-line mirror of `upsertStravaWorkouts`: `createManyAndReturn` + + * `skipDuplicates`, update-in-place on conflict, arrival emit on fresh inserts + * only. Failed rows are logged while the rest of the batch is attempted, then + * the FIRST error is rethrown so the caller cannot treat a partially persisted + * batch as a clean pass. + */ +export async function upsertPolarWorkouts( + userId: string, + rows: readonly PolarWorkoutRow[], +): Promise { + if (rows.length === 0) return 0; + + let imported = 0; + let firstError: unknown; + let hadError = false; + for (const r of rows) { + const data = { + sportType: r.sportType, + startedAt: r.startedAt, + endedAt: r.endedAt, + durationSec: r.durationSec, + totalEnergyKcal: r.totalEnergyKcal, + totalDistanceM: r.totalDistanceM, + avgHeartRate: r.avgHeartRate, + maxHeartRate: r.maxHeartRate, + elevationM: r.elevationM, + metadata: r.metadata, + }; + try { + const [inserted] = await prisma.workout.createManyAndReturn({ + data: { + userId, + source: "POLAR", + externalId: r.externalId, + ...data, + }, + skipDuplicates: true, + select: { id: true, startedAt: true }, + }); + if (inserted) { + void emitInsertedWorkoutArrival(userId, inserted, "polar").catch( + () => {}, + ); + } else { + await prisma.workout.update({ + where: { + userId_source_externalId: { + userId, + source: "POLAR", + externalId: r.externalId, + }, + }, + data, + }); + } + imported += 1; + } catch (err) { + getEvent()?.addWarning(`polar: failed to upsert workout: ${err}`); + if (!hadError) { + firstError = err; + hadError = true; + } + } + } + if (hadError) throw firstError; + + annotate({ + action: { name: "polar.workout.ingest", details: { imported } }, + }); + return imported; +} diff --git a/src/lib/sources/pick-canonical-workout.ts b/src/lib/sources/pick-canonical-workout.ts index f7b13f399..9f1da7274 100644 --- a/src/lib/sources/pick-canonical-workout.ts +++ b/src/lib/sources/pick-canonical-workout.ts @@ -263,6 +263,12 @@ export const DEFAULT_WORKOUT_SOURCE_PRIORITY: readonly MeasurementSource[] = [ // session. "FITBIT", "WITHINGS", + // v1.32.15 — Polar ranks below Withings and above Strava: a Polar watch is a + // device-native HR capture (unlike a Strava re-upload with degraded/absent + // HR), so a Polar exercise outranks a Strava twin of the same session but + // sits below the primary on-wrist wearables. Matches Polar's slot in the + // read-time `steps` ladder (`DEFAULT_SOURCE_PRIORITY.steps`). + "POLAR", // v1.28.x — Strava ranks below the device-native captures (Apple/WHOOP/ // Fitbit/Withings on-wrist HR) but above MANUAL/IMPORT: a Strava activity is // often itself a re-upload of an Apple/Garmin recording, so its HR/calories