Commit Graph
832 Commits
Author SHA1 Message Date
Marc-André Bombeck c50931b4e7 feat(schema): MeasurementType enum additions for Withings full coverage
Seven new enum values for v1.4.25 W5d. Source: Withings developer
guide — Data API → All Available Health Data — cross-referenced
against `.planning/research/withings-api-coverage.md` §3.

  - FAT_FREE_MASS (meastype 5) — Body+, Body Cardio, Body Comp, Body Scan
  - FAT_MASS (meastype 8) — same devices; mass form of BODY_FAT
  - MUSCLE_MASS (meastype 76) — Body+ family
  - SKIN_TEMPERATURE (meastype 73) — ScanWatch dermal reading. DISTINCT
    from BODY_TEMPERATURE: surface temps run ~32 °C, core ~37 °C, so
    they cannot share a bucket without corrupting analytics.
  - PULSE_WAVE_VELOCITY (meastype 91) — Body Cardio / Body Scan;
    indicator of arterial stiffness
  - VASCULAR_AGE (meastype 155) — Body Scan; composite of PWV + age
  - VISCERAL_FAT (meastype 170) — Body Comp / Body Scan; Withings'
    1–12 rating scale (not a percent)

Migration 0049 is additive only — every value is unconditional, no
backfill needed. The Withings client picks these values up once the
meastype → enum mapping lands (separate commit in this phase).

Unit map + plausibility ranges updated in `src/lib/validations/
measurement.ts` so the create-measurement validator accepts the new
types end-to-end.
2026-05-14 14:07:16 +02:00
Marc-André Bombeck 03f58c75b8 docs(planning): W4d v1.4.25 GLP-1 full integration phase report 2026-05-14 14:04:53 +02:00
Marc-André Bombeck d74aa2066b style(glp1): prettier formatting across W4d surfaces 2026-05-14 14:03:43 +02:00
Marc-André Bombeck a68dbdc22c chore(glp1): test-environment tolerance + i18n parity + OpenAPI regen
Final-pass hygiene for the W4d GLP-1 integration:

- `buildGlp1SnapshotBlock()` and `detectGlp1Plateau()` short-circuit
  to `null` when the test environment mocks prisma partially (only
  `measurement` / `moodEntry` mocked, `medication` undefined). Matches
  the production behaviour for accounts without an active GLP-1 row.
- DE locale parity: adds the matching German string for
  `insights.subPage.therapyTimelineDescription` that landed without
  its de.json counterpart.
- Drops unused `locale` destructure on the GLP-1 medication card and
  the dead `DailyValueRow` interface in the snapshot helper.
- Regenerated `docs/api/openapi.yaml` so the new GLP-1 endpoints
  (/api/medications/[id]/glp1, /api/insights/glp1-timeline) appear
  in the spec.
2026-05-14 14:01:42 +02:00
Marc-André Bombeck f45adb29f0 feat(doctor-report): GLP1 therapy section with titration + weight curve + side-effects
Phase 10 of W4d GLP-1 full integration. The doctor-report PDF gains a
dedicated "GLP-1 therapy" section when the patient has at least one
active GLP-1 medication and the existing compliance toggle is on. The
section lists what a prescribing clinician needs at every follow-up:

- Weight delta over the report window (start → end → delta)
- Per-medication block: drug name, current dose + start date,
  compliance count and rate, full titration history table
  (date | dose | note)
- Side-effect frequency table (last N days, counts per tag) when the
  mood section is also enabled (mood is the data source)

Generic accounts (no GLP-1 medication) get `glp1: null` from the
aggregator and the PDF skips the entire section, so existing reports
stay byte-identical.

Aggregator extension lives in `doctor-report-data.ts` — eager-loads
`doseChanges` + the most recent intake event on every active
medication (cheap, indexed); GLP-1 specifics only assemble when at
least one GLP-1 row exists. The field is optional on the type to
preserve compatibility with existing test fixtures.

DE + EN copy for the report section lives under `doctorReport.glp1*`.
2026-05-14 13:56:08 +02:00
Marc-André Bombeck 7b6b9161c3 style(charts): grey out comparison-overlay toggle when no prior-period data exists
Marc directive 2026-05-14 — when a chart has a comparisonBaseline
selected but the prior period (lastMonth / lastYear) carries zero
overlay-able rows, the chart settings cog now shows the comparison
buttons in a visibly disabled state (opacity-50, aria-disabled, native
title tooltip, and a sub-label hint) instead of silently rendering
nothing. The 'none' button always stays enabled — it's the escape
hatch.

Plumbing:
- chart-overlay-controls.tsx: new `hasComparisonData` prop (defaults
  to true so legacy callers keep their behaviour). The popover body is
  extracted as `<ChartOverlayControlsBody>` so unit tests can render
  it without Radix's portalled popover stripping it out of the SSR
  output.
- health-chart.tsx + mood-chart.tsx: thread the already-computed
  `hasComparisonData` memo (line 768 / 457) into the controls.
- medication-compliance-chart.tsx: passes `hasComparisonData={false}`
  unconditionally because the compliance heatmap never paints a
  prior-period overlay (already documented in the existing N/A
  caption block).

Tests: 5 new cases under chart-overlay-controls.test.tsx cover the
normal / greyed / none-baseline / locale / default-prop branches.
The pre-W3f assertion suite (3 tests) keeps passing unchanged.

i18n: appended chart.overlay.controls.comparisonUnavailable to both
locales — no key restructure.
2026-05-14 13:53:42 +02:00
Marc-André Bombeck 6148a179ca feat(briefing): GLP1 plateau detection rule with clinical referral framing
Phase 9 of W4d GLP-1 full integration. New `detectGlp1Plateau()`
helper flags the clinical plateau pattern for GLP-1 receptor agonists:
≥21 days on a stable dose AND weight delta within ±0.5 kg over that
same window. When the rule fires, a SYSTEM CONTEXT block is appended
to the insight-generation user prompt with the named drug, current
dose, days-on-dose, and weight delta — and instructs the model to
emit a glp1_plateau keyFinding framed observationally.

GROUND RULE 14 (insight prompt) keeps the safety contract: the
finding NAMES the plateau and the conversation it should prompt
("worth mentioning at the next visit"), but NEVER recommends a dose
change. The plateau is detection, not prescription.

Detector returns `null` when no GLP-1 medication is active OR no
plateau condition is met, so 99% of users pay zero token cost and
never see a plateau-shaped section in their briefing.

The schema gains "glp1_plateau" in the keyFinding.sourceMetric enum
(landed earlier this phase) and the daily-briefing icon mapping
inherits the Pill icon for visual consistency with other
medication findings.
2026-05-14 13:52:31 +02:00
Marc-André Bombeck 8b79ed89c8 chore(schema): medication_schedules @map to snake_case (cosmetic + convention)
The `windowStart` / `windowEnd` columns on `medication_schedules` were
the last hold-outs using the camelCase identifier from 0001_init.sql;
every other column on the table already follows the snake_case
convention. Adding `@map("window_start")` / `@map("window_end")` aligns
the SQL identifier without changing the Prisma client surface — every
read/write site continues to use the TypeScript-side `windowStart` /
`windowEnd` names verbatim.

Migration 0047 renames the columns in place — no data movement, no
index churn, no FK changes. Forward-only.
2026-05-14 13:50:38 +02:00
Marc-André Bombeck 044f971133 docs(planning): v1.4.25 W9 repo polish phase report 2026-05-14 13:50:29 +02:00
Marc-André Bombeck 2c7c3cc9f3 feat(insights): GLP1 therapy timeline on /insights/medikamente
Phase 8 of W4d GLP-1 full integration. New TherapyTimeline component
mounts on /insights/medikamente below the compliance grid. Renders a
chronological merge of every GLP-1-relevant event the user has logged:
dose changes (with up/down arrow against the previous step),
injections (with optional site), inventory events, and side-effect
days collapsed from MoodEntry tags.

Self-hides for users without a GLP-1 medication (the API returns
`hasGlp1: false`), so /insights/medikamente keeps its v1.4.24 look
for everyone else.

New GET /api/insights/glp1-timeline aggregates the data. Caps at 60
entries by default (configurable to 200 via ?limit) to keep the list
readable; older events surface via the existing intake-history page.

DE + EN copy for the surface lives under insights.therapyTimeline.
The medikamente sub-page description gains a one-liner explaining
when the timeline appears.
2026-05-14 13:49:35 +02:00
Marc-André Bombeck edae56969f chore(insights): drop orphaned /api/insights/general-status — superseded by InsightAdvisorCard since v1.4.16
The HTTP route had no remaining UI callers — the v1.4.16 polish replaced
the <InsightStatusCard> on the /insights overview with the polished
<InsightAdvisorCard>, and the per-metric sub-pages each consume their
own dedicated endpoint (/api/insights/{weight,bmi,pulse,blood-pressure,
medication-compliance}-status). The lib helper generateGeneralStatusForUser
remains in src/lib/insights/general-status.ts because the reminder
worker still pre-warms the daily cache for users opted in to the
briefing notification (src/lib/jobs/reminder-worker.ts).

Verification:
- grep confirms zero callers under src/ outside the route file itself
- the route was not registered in src/lib/openapi/routes.ts and
  docs/api/openapi.yaml carries no general-status path
- pnpm typecheck remains clean
2026-05-14 13:49:06 +02:00
Marc-André Bombeck ef03705e51 docs: rewrite README hero — what / who / try the demo (30-second read)
Adds a 'What it is' section between the badges and the existing 'Why
HealthLog?' paragraph so a stranger landing on the repo sees the
product proposition in under 30 seconds without scrolling. The section
gives a two-paragraph product description and a direct CTA to the
live demo, addressing the marketing-checklist gap.

Also reframes the Quick Start lead from 'Plan ~5 minutes' to
'3 minutes from git clone to a working install' so the install-time
promise lives next to the install instructions.
2026-05-14 13:48:38 +02:00
Marc-André Bombeck 6750d091b9 feat(medications): injection-site body-map picker + rotation recommender
Phase 5 of W4d GLP-1 full integration. The body-map picker is the
visual surface for the 8-zone InjectionSite enum that landed with
migration 0046. Stylized front-of-body SVG outline with 8 click-target
dots — head/neck/torso/arms/thighs for orientation, abdomen
quadrants centred on the navel reference per Eli Lilly's IFU rotation
zones, plus thighs and upper arms.

UI behaviour:
- Active site fills with the primary colour
- Recommended next site shows a dashed primary-coloured ring
- Each <button> hit area is 22px radius so the target meets WCAG 2.5.5
  even though the visible dot is 12px

`nextInjectionSite()` is a pure function that maximises the average
Euclidean distance from the candidate to the last N=4 picks, with a
recency penalty for sites used most recently. Untouched sites beat
stale ones via the recency-bonus tie-break. Empty history returns
ABDOMEN_LEFT as a sensible first-time default (the card always has
something to point to).

Unit tests cover: never-recommends-most-recent invariant, sensible
choice after a left-cluster sequence, rotation through unused sites,
i18n key shape, coordinate-table completeness.
2026-05-14 13:39:01 +02:00
Marc-André Bombeck d6315026b4 docs(planning): record W5 v1.4.25 Coach drawer polish phase report 2026-05-14 13:38:54 +02:00
Marc-André Bombeck 36bf96059e style(coach): prettier formatting on W5 surfaces 2026-05-14 13:37:41 +02:00
Marc-André Bombeck 88efd42755 feat(dashboard): GLP-1 status tile with next-injection + weight-delta caption
Renders a dedicated tile for users on a GLP-1 receptor agonist
(Mounjaro, Ozempic, Wegovy, Zepbound, …) — the new W4d schema enum
`Medication.treatmentClass = GLP1` is the discriminator. Tile self-
hides when no active GLP-1 med exists so accounts without one see no
visual change.

The tile surfaces:
  - Drug name + current dose ("Mounjaro 7.5mg") — sourced from the
    `MedicationDoseChange` titration history (latest row wins), so a
    Mounjaro user titrating up 2.5 → 5 → 7.5 → 10 mg sees their
    current step, not the starting dose.
  - Last injection date + weekday ("Sun, 05/10")
  - Next injection date + weekday + countdown
    ("Sun, 05/17 (in 3 days)") — predicted from the existing schedule
    cadence
  - Weight delta since starting the therapy ("−4.2 kg since start"
    / "−4,2 kg seit Beginn") — green chip on loss, orange on gain,
    muted minus on flat (within ±0.1 kg)
  - A compact weight chart with vertical injection-day markers via
    the new `<HealthChart verticalMarkers={…} />` prop

New server endpoint `GET /api/dashboard/glp1` aggregates the data:
the heavy lifting (current dose / last + next injection / titration
history / inventory math) is delegated to the existing
`buildGlp1SnapshotBlock` so the Coach's GLP-1-aware reply path and
the dashboard tile read from the same shape. The route adds the UI-
facing extras (weight series since first dose-change, current vs
start, injection date keys for the markers) on top.

Mount: dashboard mother page (`src/app/page.tsx`) mounts the tile
below the AI insights preview and above the chart row — high enough
that a Mounjaro user sees their dose-response without scrolling past
BP / pulse, but below the AI preview which stays the scroll-stop
hero anchor.

Constraint respected (Marc directive 2026-05-14): the chart lives on
the Dashboard tile and the Insights /medikamente sub-page only; the
Medications page itself stays chart-free.

i18n keys: dashboard.glp1.{title, lastInjection, nextInjection,
weightDelta, inDays, empty.title, empty.description} in EN + DE.

Tests pin 7 scenarios: hidden when no active GLP-1, hidden when meds
array is empty, skeleton during fetch, full render for a Mounjaro 7.5
mg weekly profile, latest titration step wins (10 mg, not 2.5 mg),
fallback to name-only when no dose history exists, German copy under
the de locale.
2026-05-14 13:37:29 +02:00
Marc-André Bombeck b8a1c1833b feat(medications): GLP1 medication-card variant — text-rich, no chart per Marc directive
Phase 4 of W4d GLP-1 full integration. New `Glp1MedicationCard`
variant renders inside the existing medications grid alongside generic
cards — same Card shell, same compliance bars, same primary intake
actions. The GLP-1-specific rows sit between the dose line and the
compliance bars so the user reads top-down: drug → injection state →
adherence.

Marc directive 2026-05-14: NO chart on the medication card. The card
stays text-rich:
- Headline: drug name + current dose ("Mounjaro · 7.5 mg")
- Last injection line with optional site ("Last: Mo May 12 · Abdomen,
  lower left")
- Next injection line with day count ("Next: Mon, May 19 (in 5 days)")
- Rotation hint ("Last site: Abdomen left · Recommended:
  Abdomen right") — only when the last site differs from the
  recommended next site
- Pen-inventory line with low-stock badge when dosesPerUnit is set
- Collapsible "Dose history" details block listing every
  MedicationDoseChange row
- "Log side effect" quick-button alongside Taken / Skipped

Routing: the medications page reads `treatmentClass === "GLP1"` and
dispatches to the variant. Existing meds (treatmentClass = "GENERIC",
the migration 0046 default) render the unchanged generic card.

Companion pieces:
- `injection-sites.ts` — the 8-site enum + `nextInjectionSite()`
  recommender that maximises Euclidean distance to recent picks and
  beats stale sites in the tie-break.
- `/api/medications/[id]/glp1` — GLP-1 details endpoint feeding the
  card (dose changes + recent intakes + running inventory math).
  POST creates a dose-change or inventory event.
2026-05-14 13:36:30 +02:00
Marc-André Bombeck b50ebccf0b feat(coach): distinct daily-limit vs provider-rate-limit error UX
`coach.budget.exceeded` (per-user daily token cap, returned as JSON
429) now surfaces the dedicated "Daily limit reached; resets at 00:00
UTC." copy. `coach.provider.rate_limited` (every provider in the
fallback chain landed on 429, streamed as an SSE error frame) surfaces
"Provider temporarily rate-limited; retry in ~5 min." Other provider
failures keep the generic copy. The chat route emits the new
rate-limited code; the send hook decodes the JSON 429 envelope's
structured `error` field so the drawer can route the bubble copy.
2026-05-14 13:35:57 +02:00
Marc-André Bombeck d51e488739 docs(planning): W6c v1.4.25 doctor-report toggles phase report 2026-05-14 13:34:09 +02:00
Marc-André Bombeck 94cc7f571d feat(medications): once-weekly cadence preset for GLP1 category
Phase 3 of W4d GLP-1 full integration. The form gains a small
"Treatment class" selector (GENERIC | GLP-1 injection) sitting under
the existing clinical-category dropdown. Picking GLP-1 reveals two
helpers that stay hidden for every other medication:

- "Once weekly on …" preset — a single-tap weekday row that writes
  daysOfWeek=[N] + intervalWeeks=1 into the first schedule and reveals
  the advanced block so the user can still tune the window. The last
  weekday picked persists in localStorage so a follow-up med starts on
  the same day.
- "Doses per pen / vial" optional input that powers the inventory math
  (Mounjaro KwikPen = 4, Ozempic 0.25/0.5 mg = 4, Wegovy single-dose
  pen = 1). Leaving it blank keeps inventory tracking off.

The wire schema gains optional `treatmentClass` and `dosesPerUnit`
fields. Both default sensibly (GENERIC + null) so the v1.4.24 client
keeps working untouched.

Marc directive 2026-05-14: GLP-1 must integrate "harmonisch", not
crowd the form. The new affordances live behind the treatment-class
toggle — for every other med the form is byte-identical to v1.4.24.
2026-05-14 13:33:18 +02:00
Marc-André Bombeck c7eb226969 feat(coach): composer textarea auto-grows from 1 to 6 lines, Claude-web pattern
The composer starts at a single-line height (matching the disclaimer
text on the left of the row) and grows with content up to six lines.
Past that point the textarea scrolls internally so the rest of the
drawer never moves. Implementation is the standard scrollHeight
measurement — reset to "auto", read scrollHeight, clamp to
[lineHeight + padding, 6 × lineHeight + padding]. The pure
`computeAutoGrowHeight` helper backs the effect for unit testing.
2026-05-14 13:32:28 +02:00
Marc-André Bombeck 1332342c59 feat(charts): weight chart accepts vertical injection-day markers
Adds an optional `verticalMarkers` prop to `<HealthChart>` so the
v1.4.25 GLP-1 dashboard tile + the Insights /medikamente sub-page can
paint dashed vertical reference lines at each recorded injection day.
Each marker = `{ date: 'YYYY-MM-DD', label?, color? }`. Defaults to
the strip-tile green (`#50fa7b`) so a row of markers reads as
"injection cadence" at a glance; callers can override per marker.

Rendering:
  - Recharts `<ReferenceLine>` with `strokeDasharray='3 3'`,
    `strokeOpacity=0.55`, no label by default (inline labels would
    crowd a once-weekly cadence over a 90-day window).
  - A small filled `<ReferenceDot>` (r=3) at the y-axis minimum so
    the markers also read along the x-axis baseline.
  - Off-window markers silently drop via `ifOverflow='discard'`,
    matching the existing storyboard-annotation contract.

The marker math is factored into a pure helper
`resolveVerticalMarkerPositions` so the unit suite can pin behaviour
without mounting Recharts. Day-keys are matched by EXACT string
comparison against `chartData[i].date` (no ±7-day snap like the
storyboard annotations) — drawing a marker on a day the chart has no
data point reads as a rendering bug rather than as orientation.

Tests pin: empty input, undefined input, single in-window match,
multi-marker order, caller-supplied color/label overrides, off-window
drop, sparse weekly-bucket exact-day matching.
2026-05-14 13:31:41 +02:00
Marc-André Bombeck 70fe5a55c2 refactor(coach): drop non-functional mic icon from composer
The mic was rendered + disabled with a "voice arrives with iOS"
tooltip, drawing taps that did nothing. Voice input remains scheduled
for the iOS client (v1.5); the web composer no longer surfaces a
placeholder. Frees the row for the Enter-to-send hint to breathe.
2026-05-14 13:31:12 +02:00
Marc-André Bombeck 64d50fd32e i18n(doctor-report): EN + DE strings for section toggles 2026-05-14 13:30:39 +02:00
Marc-André Bombeck 81b1d79232 style(coach): unify X / cog / new-chat header buttons — same size + alignment
All three header actions (new chat, settings, close) now share the
same ghost / size-icon / 36-px hit-target shape with a 16-px icon and
identical color treatment. The Sheet's default absolute-positioned
close X is gone; the inline close button sits on the same baseline as
the others so the cluster reads as a single set.
2026-05-14 13:30:12 +02:00
Marc-André Bombeck 759fdaefcd feat(doctor-report): server filter respects per-section toggles + PDF skips disabled sections 2026-05-14 13:29:53 +02:00
Marc-André Bombeck 330be965ac feat(coach): default analysis window as user preference + per-conversation override
`coachPrefs.defaultWindow` joins the existing prefs blob (tone,
verbosity, excludeMetrics, showEvidenceByDefault). The picker lives in
the Coach settings sheet; the drawer header carries a small pill that
overrides the saved default for the current chat only. Closing the
drawer drops the override so the next session starts on the saved
preference. Backwards-compatible: legacy rows missing the key resolve
to "allTime", matching the v1.4.24 behaviour. The chat route folds the
saved window into snapshot scope when the client doesn't supply one.
2026-05-14 13:28:10 +02:00
Marc-André Bombeck 2bd29022b1 feat(coach): snapshot weeklyContext.glp1 names the drug + dose + schedule
Phase 2a of W4d GLP-1 full integration. New `buildGlp1SnapshotBlock()`
helper reads every active medication classified as GLP1 (treatmentClass
column from migration 0046) and assembles a compact block the snapshot
ships under `weeklyContext.glp1` — drug display name + generic active
ingredient, current dose + weeks-on-dose, chronological titration
history, weekly cadence (parsed from MedicationSchedule.daysOfWeek),
last + next injection date, last injection site, pen inventory math,
and side-effect tag counts from the last 14 days of MoodEntry rows.

The block is omitted entirely for users with no GLP-1 medications (the
helper short-circuits to null after one indexed Prisma lookup), so
web-only generic accounts pay zero token cost.

Marc directive 2026-05-14: the Coach must say "your Mounjaro 7.5 mg"
instead of "your medication" when the user has named the drug. The
snapshot is the load-bearing surface for that — the system-prompt
guardrail (GROUND RULE 9) lands in the follow-up commit and forbids
any dose-prescriptive use of this data.
2026-05-14 13:28:00 +02:00
Marc-André Bombeck a732b1926e feat(withings): subscribe to BP + temperature webhooks alongside weight
setupWebhook now subscribes to appli=1 (weight + composition),
appli=2 (temperature), and appli=4 (pressure family: BP, pulse, SpO2)
in one pass. The previous implementation only registered appli=1, so a
new BP reading from a BPM cuff sat for up to an hour waiting for the
hourly poll fallback instead of arriving via push within seconds.

A failure on one category is logged and we proceed with the rest —
losing one webhook is strictly better than rolling back all three.
The disconnect path mirrors the same iteration so cleanup unsubscribes
every category we ever subscribed to. Webhook handler already
dispatches `syncUserMeasurements` regardless of appli, so no change
needed on the receiver side.

Exports `WITHINGS_NOTIFY_APPLIS` as the single source of truth so the
unit test and the disconnect route stay in lockstep with setupWebhook.
2026-05-14 13:27:37 +02:00
Marc-André Bombeck 5cb4a1dde1 feat(doctor-report): per-section toggle UI + persistence 2026-05-14 13:24:35 +02:00
Marc-André Bombeck b1a3d59918 feat(withings): ingest meastype 123 (VO2 max) into VO2_MAX
The ScanWatch family reports VO2 max under meastype 123 in
mL/(kg·min), which matches HealthLog's canonical DB unit verbatim
(no conversion needed beyond the standard value × 10^unit exponent
decode). Targets the VO2_MAX enum slot added in v1.4.23 for the
Apple Health passthrough.
2026-05-14 13:24:25 +02:00
Marc-André Bombeck 4158a02966 feat(withings): ingest meastype 35 (legacy SpO2) into OXYGEN_SATURATION
Older Withings firmware and some partner SDK examples report SpO2
under meastype 35 instead of 54. Mapping both into OXYGEN_SATURATION
prevents a quiet drop on legacy devices and is compatible with mixed
fleets (the existing meastype 54 path stays in place).
2026-05-14 13:24:01 +02:00
Marc-André Bombeck fb23796d72 feat(withings): ingest meastype 71 (current-gen Thermo) into BODY_TEMPERATURE
Current-gen Withings Thermo and ScanWatch series report core body
temperature under meastype 71 (the legacy meastype 12 stays in place
for first-gen Thermo). Both decode through the same value × 10^unit
path and target the BODY_TEMPERATURE enum slot.

Skin temperature (meastype 73) stays out until v1.4.26 ships a
SKIN_TEMPERATURE enum — surface temps (~32 °C) and core temps (~37 °C)
must not share a rollup or correlation analytics will collapse.
2026-05-14 13:23:33 +02:00
Marc-André Bombeck 861fe7ad0d test(charts): comparisonBaseline data correctness end-to-end
Pins the comparison-overlay shift across the edges Marc flagged worry
about. The existing `shiftDailySeriesForward` implementation is correct
— integer-day forward addition, no DST surprises because every input
timestamp is anchored at UTC-noon (well clear of the 02:00-03:00 wall-
clock jump). No production fix needed; this is a regression-floor
suite so a future refactor cannot silently change the contract.

Pinned scenarios:
  - DST forward shift (Mar 31 2024 Berlin spring-forward) — calendar
    day preserved
  - DST backward shift (Oct 27 2024 Berlin fall-back) — calendar day
    preserved
  - Leap-year alignment — Feb 29 2024 + 365 days lands on Feb 28 2025
    (the contract is "365 days ago", not "same calendar date last
    year")
  - Insufficient prior data (60 days history + `lastYear` request) →
    overlay renders empty so the chart drops the comparison cleanly
    without rendering a "kein Vergleich" placeholder (per Marc directive
    2026-05-14)
  - Partial prior-period coverage flags `hasComparisonData = true`
  - Tile-caption math (`averageValue` + `computeComparisonDelta`)
    returns null cleanly when the prior window is empty
2026-05-14 13:23:13 +02:00
Marc-André Bombeck ae8e2d77aa feat(withings): ingest meastype 12 (legacy Thermo temperature) into BODY_TEMPERATURE
First-gen Withings Thermo (WBT01) reports body temperature under
meastype 12. The current-gen Thermo ships meastype 71 (next commit).
Both decode through the same `value * 10^unit` path the client already
applies, and target the `BODY_TEMPERATURE` enum slot we added in v1.4.23
for the Apple Health passthrough.

Adds `src/lib/withings/__tests__/client.test.ts` with a synthetic
`getmeas` payload covering the exponent decode, unknown-meastype skip,
and two-decimal rounding. Re-exports MEASURE_TYPE_MAP so the test can
assert the mapping directly without importing internals.
2026-05-14 13:23:01 +02:00
Marc-André Bombeck cbcc0598b2 feat(schema): MedicationCategory + MedicationDoseChange + InjectionSite (migration 0046)
Phase 1 of W4d GLP-1 full integration. Forward-only additive migration: a
new `medication_category` enum (GENERIC | GLP1) lands as
`medications.treatment_class` (defaults to GENERIC so existing rows render
exactly as before). `medications.doses_per_unit` lets pen/vial-tracked
meds carry their dose count. `medication_intake_events.injection_site`
captures the 8-zone body-map pick — nullable; non-GLP-1 meds never set
it. `medication_dose_changes` holds titration history (Mounjaro 2.5 → 5
→ 7.5 → 10 → 12.5 → 15 mg per Eli Lilly's PI). `medication_inventory_events`
is the append-only ledger backing the low-stock dashboard caption.

Naming nuance: the new column is `treatmentClass`, not `category`, because
the existing `medication_categories` side-table already owns the
`category` slot in the API response (clinical taxonomy:
BLOOD_PRESSURE / VITAMIN / ...). Two orthogonal concepts, two columns.
2026-05-14 13:22:47 +02:00
Marc-André Bombeck c2fc95f815 fix(settings): dashboard section save actually persists
The Settings → Dashboard sub-section's Save button silently 422'd once
the user had touched any per-chart overlay popover. Root cause was a
Zod v4 semantics change: `z.record(z.enum(KEYS), ...)` now requires
every enum key to be present in the input, where Zod v3 treated the
same shape as a partial record. Real-world Save payloads only carry
the chart keys the user actually toggled, so every Settings → Dashboard
Save attempt with one or two `chartOverlayPrefs` entries failed with
`expected: object, path: ["chartOverlayPrefs", "<missing-key>"]` and
the toast surfaced "Layout konnte nicht gespeichert werden".

Fix uses `z.partialRecord(z.enum(KEYS), ...)` which preserves the
original v1.4.18 intent — per-chart opt-in overlay prefs, missing keys
filled by the resolver. The inner object now also accepts the
`comparisonBaseline` field so a Settings save preserves the per-chart
comparison toggle the user set via the chart-card popover (otherwise
Zod's default strip behaviour wiped it on every save).

New integration suite pins:
  - partial chartOverlayPrefs round-trips
  - per-chart comparisonBaseline survives a Settings save
  - empty chartOverlayPrefs still persists (fresh accounts)
  - widget toggle changes land in the DB
2026-05-14 13:22:07 +02:00
Marc-André Bombeck d94981e010 chore(withings): document full meastype mapping + API coverage audit
Adds src/lib/withings/mapping.md as the single source of truth for the
meastype → MeasurementType table that the client.ts MEASURE_TYPE_MAP
mirrors, and .planning/research/withings-api-coverage.md as the full
audit of the Withings public API surface (Measure, Sleep, Heart,
Activity, Workouts, User, Notify) against HealthLog's ingestion.

The audit scores each gap on user-value / effort / schema-impact and
slots additions into v1.4.25 (cheap mappings), v1.4.26 (sleep + activity
sync, body composition expansion) and v1.5 (ECG, AFib, workouts).
2026-05-14 13:21:28 +02:00
Marc-André Bombeck 4c9c0687b5 style(coach): drop redundant per-row source labels in evidence disclosure
Each row in "What I'm looking at" / "Worauf bezieht sich das?" was
prefixed with `kv.label` — the same framing the disclosure heading
already supplies. The label is gone; rows lead with the value + unit
and keep the window as a parenthetical tail.
2026-05-14 13:19:49 +02:00
Marc-André Bombeck 1895fd3cd8 fix(coach): suggested-prompt chips show user message before thinking placeholder
The send hook now surfaces the user's message as an optimistic bubble
the moment send fires, so the chronological render order matches the
user's mental model: user message → "Thinking…" placeholder →
assistant reply. The optimistic copy drops as soon as the persisted
twin lands via the invalidate-refetch the SSE `done` frame triggers.
2026-05-14 13:19:17 +02:00
Marc-André Bombeck 7c06b89717 feat(schema): User.doctorReportPrefsJson + migration 0045 2026-05-14 13:19:17 +02:00
Marc-André Bombeck 58bbb4ec78 docs(planning): record W7b timezone follow-up report 2026-05-14 13:19:17 +02:00
Marc-André Bombeck 16fbdbcb87 style: prettier across W7b surfaces 2026-05-14 13:19:17 +02:00
Marc-André Bombeck 85c3def94f feat(coach): snapshot anchors yesterday/this-week to user displayTimezone
Up to v1.4.24 the snapshot's day-key and weekday labels ran through
utcDayKey() / utcWeekday() / isoWeekKey(), so a 23:50 Pacific/Auckland
reading was filed under the next UTC day and the Coach replied with
the wrong calendar. The pipeline now reads User.timezone (alongside
the existing coachPrefsJson read so the read budget is unchanged) and
threads it through every bucketing helper (dailyMeans, bucketWeekly,
buildDailyValueRows, buildDailyBpRows) plus the medication-compliance
day-roll-up and the Apple Health additive blocks.

The prompt-budget calculator (src/lib/ai/coach/budget.ts) is unaffected.
The ledger still uses UTC midnight for spend roll-over because the
operator's LLM bill cycles on UTC; only the SNAPSHOT itself shifts to
the user's calendar. The provenance counts are row counts, not day
counts, so no provenance drift either.

Integration test pins the boundary: a 13:00 UTC May 14 reading (=
01:00 NZST May 15) appears under "2026-05-15" in the Coach snapshot
for a Pacific/Auckland user. The same instant in Berlin would land on
May 14; the test asserts the snapshot does NOT bucket there.

Existing 88-test coach unit suite stays green (the mocked user row
returns no timezone, so the snapshot falls back to Europe/Berlin and
the v1.4.24 byte-shape holds).
2026-05-14 13:19:17 +02:00
Marc-André Bombeck ca7673358e docs(planning): W4 v1.4.25 insights sub-pages phase report 2026-05-14 13:19:17 +02:00
Marc-André Bombeck 9af94d827f chore(openapi): regenerate docs/api/openapi.yaml
The W7 timezone agent committed an openapi/routes.ts change without
running pnpm openapi:generate. This regeneration brings the committed
yaml back in sync (cosmetic whitespace normalisation on multi-line
descriptions — no schema changes from this run).
2026-05-14 13:19:17 +02:00
Marc-André Bombeck 1de3619fa4 i18n(insights): EN + DE strings for the 7 insights sub-pages
Adds the labels the v1.4.25 W4 sub-pages reference:

  - insights.navOverview / insights.navSleep — two new tab pills on
    the strip ("Overview" + "Sleep" / "Übersicht" + "Schlaf").
  - insights.subPage.{blutdruck,gewicht,puls,stimmung,medikamente,bmi}
    Description — one-line scaffold under each sub-page heading,
    matching the Apple Health metric-page convention.
  - insights.subPage.stimmungEmpty{Title,Description,Action} +
    medikamenteEmpty{Title,Description,Action} — CTAs into /mood and
    /medications when the corresponding sub-page has zero data.
  - insights.sleep.* — title, description, headline caption, stage
    labels (deep/REM/core/asleep/awake/inBed), composition title +
    subtitle + ARIA label, plus an empty-state group pointing at
    /settings/devices for the v1.5 Apple Health sync teaser.

i18n-locale-integrity.test.ts keeps the EN + DE key set in lock-step;
no changes there because the new keys land identically in both files.
2026-05-14 13:19:17 +02:00
Marc-André Bombeck 84b54d9f11 refactor(insights): mother page hosts overview only; metric depth moves to sub-pages
After W4a scaffolded the routed sub-pages and lifted the sticky tab
strip into src/app/insights/layout.tsx, the mother page becomes the
overview-only surface it always wanted to be: Hero + DailyBriefing +
CorrelationRow + TrendsRow + InsightAdvisorCard + CoachDrawer.

What's gone from the page (now lives on the matching sub-page):
  - Six per-section <HealthChart> / <MoodChart> mounts (bp/weight/
    pulse/mood/meds/bmi) with their target-zone + value-band wiring.
  - Per-metric status-card queries (blood-pressure-status,
    weight-status, pulse-status, bmi-status, mood-status,
    medication-compliance-status).
  - All the per-section <InsightStatusCard> + scatter-correlation
    cards (BP × continuity, weight × BP, mood × BP, mood × weight).
  - The bulky helper functions (getBloodPressureSectionStatus,
    getWeightSectionStatus, …, classifyRangeValue) and their imports
    (getBpTargets, buildWeightBandsFromHeight, pulse-targets, etc.).
  - The inline <InsightsSectionNav> mount — superseded by the strip
    that <InsightsLayoutShell> now mounts.

What stays here:
  - HeroStrip (greeting, weekly-report banner, Health Score panel).
  - DailyBriefing (the AI morning paragraph).
  - CorrelationRow (cross-metric hypotheses).
  - TrendsRow (BP / weight / mood mini-charts above each annotation).
  - InsightAdvisorCard (the rich recommendations grid).
  - CoachDrawer — mother-page-only, per Marc's directive.

The two insights-polish guard tests are re-pointed at the new homes
of their assertions: the tab-strip refresh affordance now lives on
the layout shell (src/components/insights/insights-layout-shell.tsx),
and the comparisonBaseline plumbing migrated into the shared
useInsightsLayoutPrefs() hook.

trends-row.test.tsx wraps every render in a QueryClientProvider —
the v1.4.25 W7 timezone change added a useAuth() call inside
<TrendsRow> for chart-side userTimezone plumbing, which needs a
TanStack-Query client at mount time.
2026-05-14 13:07:33 +02:00
Marc-André Bombeck cb825ec67a feat(insights): new /insights/schlaf sub-page with sleep-stage chart
The v1.4.23 schema added the SleepStage enum + Measurement.sleepStage
column for HealthKit per-stage rows, but the UI never surfaced them.
This commit adds the missing surface.

Components:
  - <SleepDurationChart>: thin wrapper around <HealthChart> with
    chartKey="sleep" so the per-chart cog (trend / target / compare)
    works the same way as the dashboard charts.
  - <SleepStageStackedBar>: horizontal Recharts stacked bar covering
    the trailing-30-day stage distribution (DEEP / REM / CORE /
    ASLEEP / AWAKE / IN_BED). Uses the /api/analytics sleepStages
    payload that v1.4.23 W2 already exposes; no new endpoint.
  - <SleepOverview>: composition that arranges the headline
    "X h Y min per night" card, the stage-composition stacked bar,
    and the duration trend chart. Empty state when the user has zero
    sleep rows points at /settings/devices with a v1.5 Apple Health
    sync teaser.

The sub-page itself (src/app/insights/schlaf/page.tsx) is trivial —
<SubPageShell> + <SleepOverview>. All data-fetching + empty-state
handling stays inside the components so a future v1.4.26 refinement
can iterate without touching the route.

Tests: <SleepStageStackedBar> covers the i18n titles (EN + DE), the
ARIA label that announces the nights count, and resilience against
unknown stage keys.
2026-05-14 13:07:17 +02:00
Marc-André Bombeck 959adec899 feat(api): DELETE /api/measurements/by-external-ids for iOS deletion-sync
HealthKit's API does not surface a stream of deleted UUIDs, so the iOS
HealthLog client performs a periodic 30-day reconciliation: it diffs
HealthKit's current UUID set against the server's externalIds and
posts the surplus here. This endpoint deletes the user's matching
rows and never touches another user's data (Prisma's deleteMany with
the userId predicate is the cross-user 404 guard).

Contract:
  - Body: { externalIds: string[] } with min 0, max 500 entries.
  - Auth: requireAuth() — session cookie or bearer.
  - Empty array: returns { deletedCount: 0 } with 200 (no-op, not a
    failure — matches the ingest path's symmetric tolerance).
  - Over-cap: 422 with errorCode "measurement.delete.too_large" so
    the iOS client can surface a specific diagnostic.

Integration coverage: happy path, cross-user 404 guard, empty array,
and batch-cap rejection. The cap (500) mirrors POST /measurements/batch
so the two surfaces share one operational ceiling.

OpenAPI: registered as DELETE on /api/measurements/by-external-ids
with the Measurements tag; req/res schemas reuse the same z.array cap
the runtime validator enforces. openapi.yaml regenerated.
2026-05-14 13:07:05 +02:00