Compare commits

..
49 Commits
Author SHA1 Message Date
Marc-André Bombeck 16fdc75513 chore(release): v1.8.4 — medication card accuracy + Insights polish
The medication card reads the schedule engine's next-due (fixes
interval/one-time schedules that never advanced after a dose), logging a
dose confirms itself, Insights status polling is bounded, each Insights
category explains itself inline, medication history shows each dose's
origin, and an idempotent migration adds the app_settings columns that
were only ever applied ad-hoc.
2026-06-01 17:37:11 +02:00
Marc-André Bombeck 65bbedd83d fix(seed): repair demo seed against the current schema
Two gaps stopped a fresh demo seed:

- medication_intake_events gained a NOT NULL updated_at column in the
  v1.7.0 sync keyset work. The raw INSERTs omitted it; set it alongside
  created_at on every intake row so the seed does not lean on the
  column's migration-only default.

- app_settings carried four columns on the schema (default_locale plus
  the telegram/ntfy/web-push global toggles) that never landed in the
  migration history — applied via db push to existing environments but
  never committed. A database built from migrations alone is missing
  them, and the admin settings read path selects default_locale, so a
  fresh deploy reports "column default_locale does not exist" on first
  read. Add an idempotent ADD COLUMN IF NOT EXISTS drift-fix migration
  mirroring 0025_user_locale_drift_fix: a no-op where the columns exist,
  a clean add on a migrations-only build.

Verified end to end against a fresh Postgres 16 built from the full
migration set: the seed completes and re-runs cleanly.
2026-06-01 17:31:45 +02:00
Marc-André Bombeck 65cfa2b83a fix(insights): bound the status preparing-poll to a fixed ceiling
The per-metric status cards and the inline medication-compliance query
poll the read-only status route every 4 s while the payload reports
preparing:true. A configured provider whose generation persistently
fails leaves preparing pinned true, so an open Insights page would poll
indefinitely — steady battery and network draw on a screen the user has
walked away from.

Cap the poll at 12 attempts (~48 s) through a shared
nextStatusPollInterval helper both call sites route through. Past the
ceiling the card settles on its existing static / empty state. The happy
path is unchanged: a generation that lands within a couple of intervals
clears preparing and stops the timer exactly as before, and a terminal
no-provider payload never carried preparing so it stays terminal.
2026-06-01 17:31:45 +02:00
Marc-André Bombeck 8dced00188 feat(medications): label each intake history row with its logging origin
The intake history surfaced the coarse IntakeSource enum directly, so a
dose logged from the iOS app showed nothing meaningful. Map the enum to
the practical client it represents — WEB to Web, API to iOS App,
REMINDER to Reminder, IMPORT to Import — and render it as a muted
"via {origin}" caption on each intake row next to the status. No schema
or API change; the source value already rides the existing intake
response. Tighten the en/de labels that read "External API" and
"Telegram / Reminder" into the same origin vocabulary across all six
locales.
2026-06-01 17:31:02 +02:00
Marc-André Bombeck c2808a9c70 feat(insights): show the metric explainer inline under each category heading
The per-category explainer text only lived behind the "?" popover next to
the heading. Render the same localised definition inline as a muted caption
directly beneath the title, where the short scaffold line already sits, so
the one- to two-sentence definition is discoverable without a tap.

Both surfaces read the identical insights.subPage.explainer.<metric>Body
key, so there is no duplicated copy and all six locales stay covered. The
"?" glyph stays in place as the always-available pointer to the same text.
HealthkitMetricPage already forwards explainerMetric to the shell, so every
routed metric sub-page picks up the inline caption from this one change.
2026-06-01 17:31:02 +02:00
Marc-André BombeckandClaude Opus 4.8 0e3a8f9cd3 fix(medications): read next-due from the server and confirm intake actions
Two fixes on the medication cards.

Next-due: the card recomputed "next intake" client-side from
`daysOfWeek` + `windowStart` alone, ignoring rolling intervals, RRULE,
one-shot doses, and the last-intake anchor. A rolling medication (e.g. a
35-day interval) showed "tomorrow" and never re-anchored after a dose.
`GET /api/medications` already returns `nextDueAt` per medication,
computed by the canonical recurrence engine anchored on the last intake.
Both card variants now render that value directly: the generic card
drops its `getNextOccurrenceTimestamp` walker, and the GLP-1 card drops
its weekly-only predictor that hardcoded a 7-day step. The day-label and
window-range rendering are unchanged; only the timestamp source moves to
the server. `nextDueAt` is threaded through the list page's medication
type into both cards.

Intake confirmation: tapping Taken / Skipped now raises a toast naming
the medication ("… recorded as taken" / "… skipped"), so the action has
clear feedback. The next-intake line refreshes on the invalidated list
query, which the next-due fix above makes accurate.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 17:31:02 +02:00
Marc-André Bombeck 96f0b225fd chore(release): v1.8.3 — Insights no longer block the interface
Per-category Insights assessments are served read-only from cache and
generated out of band, the client request is capped, the overnight warm
pass keys on the shown language, a stalled model is briefly remembered,
and Insights/dashboard stream a loading skeleton — so opening and
switching Insights categories stays responsive instead of freezing.
2026-06-01 09:11:36 +02:00
Marc-André Bombeck 35800becbb fix(insights): make per-category status cards read-only so navigation never blocks on the LLM
Opening an Insights category page froze the whole UI: the per-metric
status card fired a cold, uncapped LLM fetch on mount with no client
abort, so the request hung up to the server's 60s ceiling and the
pending/resolve re-renders thrashed the tab strip and ate touch events.
Timeouts were never negatively cached, so every visit re-blocked.

Fix the class holistically:

- Bound every status GET on the client. The shared use-insight-status
  hook and the inline medication-compliance query now wrap fetch in an
  8s AbortController and stop retrying inline; navigation can no longer
  await an uncapped round-trip.

- Make the status routes read-only. On a cache miss the generator
  enqueues an out-of-band pg-boss job (insight-status-generate) and
  returns a preparing envelope; the client polls a bounded interval
  until the worker warms the cache. Models the dashboard snapshot's
  ready/preparing pattern. The queue is registered in the worker
  allQueues loop + a boss.work handler, with a guard test.

- Fix the nightly warm-pass regression: warm every supported locale
  (the client reads against the active UI locale, not the persisted
  User.locale) and warm on a cached comprehensive outcome too (its
  write still evicts the per-status caches). Add a short-TTL negative
  cache on the timeout path so a transient provider stall no longer
  makes every subsequent visit re-block or re-enqueue.

- Add loading.tsx for the insights segment + the root so any future
  RSC await streams a skeleton instead of blocking the transition.

- Stabilise the advisor regenerate callback so a status-query flip
  can't re-render the memoised tab strip mid-gesture.

New i18n key insights.assessmentPreparing across all six locales.
2026-06-01 08:59:59 +02:00
Marc-André Bombeck 6a603ad587 chore(release): v1.8.2 — one intake row per dose slot
Guarantees a single intake entry per scheduled dose: intake writes snap
to the canonical slot instant and update in place rather than inserting a
sibling row, a re-sync can no longer clear a recorded dose, concurrent
logs converge, and a one-time startup pass collapses existing duplicates.
2026-06-01 08:33:20 +02:00
Marc-André Bombeck 710902a43c fix(medications): harden the slot upsert against races, downgrades, and double-decrements
Review of the slot-convergence change surfaced gaps that could mis-record
a dose. Fold the write logic into one shared `applyCanonicalSlotWrite`
used by both intake routes and close them:

- Concurrency: catch the unique-key race on insert and converge by
  re-finding the slot row and updating it, instead of returning 500 (and
  dropping the tap) or leaving a duplicate.
- No downgrade: a pending projection echo replayed onto a slot already
  marked taken or skipped is a no-op — it never clears `takenAt`. A
  recorded dose is immutable, so an offline re-sync cannot flip a taken
  dose back to missed.
- Inventory: decrement a medication's remaining count only on a genuine
  pending→taken transition, not on an idempotent re-post.
- Deterministic slot-row selection: prefer an existing actioned row, then
  the pending row, ordered by createdAt then id.
- Snap instant: derive the canonical instant via the same `localHmAsUtc`
  the projector and reminder worker mint with, so the value is identical
  by construction across a DST transition rather than only test-pinned.
- Cleanup job: isolate each slot's collapse in its own try/catch and
  guard the instant-normalisation against a tombstone collision, so one
  slot can no longer dead-letter a user's whole dedup pass.
2026-06-01 08:32:42 +02:00
Marc-André Bombeck 5047eb7a20 fix(medications): collapse pre-existing duplicate dose-slot rows at boot
The write-path convergence stops new duplicate slot rows, but accounts
that already accrued a pending + taken pair for one dose keep an inflated
expected count, a phantom taken marker, and a suppressed "due now" prompt
until the bad rows are cleared.

Add a boot-time, idempotent cleanup queue (mirroring the existing
backfill queues): discover only the users holding a same-slot duplicate,
then per medication snap every live intake to its canonical slot, keep
the most-actioned row per slot (taken over skipped over pending),
normalise its instant, soft-delete the losers, and recompute the
affected compliance rollups. Rows that resolve to no scheduled slot
(PRN / as-needed) are never collapsed. A second pass is a no-op.

Registered in the worker's queue list with a static guard test, after a
prior incident where a queue was built but never registered and silently
never ran.
2026-06-01 08:12:48 +02:00
Marc-André Bombeck 0d7d08f616 fix(medications): converge intake writes onto one row per scheduled slot
A twice-daily medication ended up with two rows for one dose slot: the
projector / reminder worker mints a pending row (source REMINDER) at the
slot's `localHmAsUtc` instant, while a "taken" write from the per-med or
bulk intake route inserted a fresh row (source WEB / API). Because
`source` is part of the `(userId, medicationId, scheduledFor, source)`
unique key — and the written instant could drift by a minute from the
projected one — the two rows coexisted: one taken, one still pending and
overdue. The card then read the slot as taken, counted 100%, and
suppressed the "due now" prompt for a dose the user had not taken.

Resolve every scheduled intake write to the slot's canonical instant
before writing and upsert in place, source-agnostic:

- `resolve-slot-instant.ts` snaps an incoming instant to the nearest
  scheduled slot for that day (enumerated through the canonical
  recurrence engine, so PRN and cyclic off-weeks resolve to no slot) and
  anchors it on the same `localHmAsUtc` the projector and worker use.
  Off-slot and as-needed writes resolve to null and keep insert semantics.
- The per-med and bulk routes look up the existing row at the canonical
  `(userId, medicationId, scheduledFor)` ignoring source and update it in
  place — mirroring the status-toggle route — instead of inserting a
  sibling. The bulk per-entry response gains an additive `updated` status.
- The reminder worker's missed-dose mint now skips a slot that already
  carries an actioned row (taken or skipped) from any source, not only an
  existing pending REMINDER row.

PRN / as-needed writes are unaffected. Regression tests pin the collapse
(exact and one-minute drift), the PRN exemption, and the worker guard.
2026-06-01 08:06:37 +02:00
Marc-André Bombeck 4578078cc1 chore(release): v1.8.1 — multi-time medication compliance
Closes the two surfaces the 1.7.3 multi-time compliance fix did not
reach: the today-tile projection now mints one pending dose per
scheduled time, and the compliance heatmap classifies each dose against
its nearest scheduled time instead of the first window.
2026-06-01 07:27:50 +02:00
Marc-André Bombeck 7f7bf75e34 fix(medications): classify each time-of-day slot in the compliance heatmap
The History compliance heatmap matched each taken intake event to the
closest schedule by `windowStart` alone, ignoring `timesOfDay`. For a
twice-daily medication stored as one schedule row with
`timesOfDay = ["07:00","19:00"]` and `windowStart = "07:00"`, the evening
dose matched the lone 07:00 window and classified as very-late (~12h),
painting the day's cell orange even when both doses were taken on time —
so the heatmap never recovered to green for single-row multi-time
schedules.

Expand every schedule into its effective dose slots (its `timesOfDay`,
else `[windowStart]`) and classify each event against the nearest slot's
window — the slot time anchoring a window that spans the schedule's
`windowEnd − windowStart` duration, overnight spans included. Single-time
schedules collapse to one slot at `windowStart` and stay byte-identical.
The denominator already routed through the canonical engine; only the
numerator's timing classification is corrected.
2026-06-01 07:26:47 +02:00
Marc-André Bombeck fcb517df87 fix(medications): fan out the today-tile projector over every time-of-day
The today-window projector minted a single pending intake row per
schedule, anchored at `windowStart`, dropping a schedule's first-class
`timesOfDay`. A twice-daily medication stored as one schedule row with
`timesOfDay = ["07:00","19:00"]` therefore surfaced only its morning
dose in the today tile and the "Erfassen" sheet, and the event-count
compliance rollup recorded one expected dose per day instead of two — a
perfectly adherent user read 50% the moment the second dose was logged,
and deleting then re-adding one dose left the rate stuck at 50%.

Fan the projection out over every `timesOfDay` entry, mirroring the
reminder worker's per-slot mint and dedup against the
`(userId, medicationId, scheduledFor, source)` unique index. Absent
first-class `timesOfDay` the projector still emits one slot at
`windowStart`, byte-stable against the worker's legacy single-window row.

Adds regression coverage across the projector (dashboard summary), the
legacy compliance walker, and the cadence expansion pinning the
single-row twice-daily case at the correct two-dose-per-day shape.
2026-06-01 07:26:26 +02:00
Marc-André Bombeck 869f13612a Merge v1.8.0 Insights release into main
# Conflicts:
#	CHANGELOG.md
#	docs/api/openapi.yaml
#	package.json
2026-05-31 23:00:08 +02:00
Marc-André Bombeck 3743f91bce chore(release): v1.7.3 — health-record pdf fixes + multi-time compliance 2026-05-31 22:49:16 +02:00
Marc-André Bombeck 013ad5d967 fix(compliance): expand multi-time legacy schedules through the canonical engine
A medication whose schedule row carried multiple timesOfDay plus a legacy
daysOfWeek (and no rrule / rollingIntervalDays) reported 50% compliance for a
fully-adherent 2x/day dose. The expected-slot denominator always ran the
canonical recurrence engine and counted both daily slots, but the numerator
only delegated to the engine for rrule / rolling / one-shot / non-SCHEDULED
rows; a plain-legacy row fell to the local cadence walker, which emitted a
single windowStart slot per day and ignored timesOfDay. 1 taken / 2 expected
read as 50 percent.

Route expandScheduleSlots through the engine for every schedule shape whenever
a medication context is supplied, so the numerator and denominator read the
same source of truth. Harden the context-less legacy walker to iterate
timesOfDay as well, mirroring the engine's legacy branch, so the single
remaining non-engine path stays correct for multi-time rows. Drop the now-dead
expander gate helper.

Add regression guards: a 2x/day legacy row reports 2/2 through
calculateCompliance, and expectedSlotCountForDay agrees with
buildCadenceTimeline on the slot count for an identical schedule.
2026-05-31 22:47:44 +02:00
Marc-André Bombeck aed83b7747 fix(report): keep modules together, label the chart time axis, fix glyph stretch
Four layout defects in the clinical PDF renderer:

- Stretched lines: the built-in Helvetica is WinAnsi-encoded, so glyphs
  outside it (the trend arrows the summary injects, the superscript-two in
  kg/m2) resolved to the .notdef box at a fallback advance width and stretched
  the surrounding words. Route every drawn string (direct text, wrapped
  paragraphs, and autoTable cells) through a central WinAnsi sanitiser that
  maps the offenders onto safe equivalents. Embedding a Unicode TTF so the
  arrows render as true glyphs is a documented follow-up.

- The sparkline dropped each reading's timestamp and plotted on an index
  axis, so a trend gave no sense of its time span. Plot points by their real
  timestamp and print the first/last dates under the baseline.

- No consistent bottom safe area: scattered y > 240 magic numbers and tables
  with no bottom margin let content run into the footer. Introduce a single
  contentMaxY derived from the page height, footer band, and bottom margin;
  every break check and every autoTable bottom margin refers to it.

- Modules tore mid-block. Add an ensureSpace guard called before each module
  heading and a per-line guard in every free-text loop; give the short
  titration and side-effect tables rowPageBreak: avoid.
2026-05-31 22:47:44 +02:00
Marc-André Bombeck c6e782cdb8 fix(report): pass the in-app locale through to the pdf export
The health-record export panel sent no locale, so the server resolved the
report language from the browser's Accept-Language header. A German user on
an English-default browser got an English doctor report.

Send the active in-app locale from the panel, and on the server resolve
most-specific-first: explicit selection, then the healthlog-locale cookie
(what the user actually chose in the UI), then Accept-Language as the
weakest fallback.
2026-05-31 22:47:44 +02:00
Marc-André Bombeck 6842b52346 chore(release): v1.8.0 — insights data-driven assessments, embedded targets, explainers 2026-05-31 22:46:18 +02:00
Marc-André Bombeck 67a72b1023 perf(insights): parallelise the nightly per-user assessment warm pass
The warm pass forced the seven per-metric status generators strictly
back to back per user, so a fully configured account paid ~7× one LLM
round-trip serially. Bound the inner pass with a small `p-limit(3)` so
the cards warm a few at a time without saturating the Prisma pool or
fanning out an unbounded number of provider calls. The per-user budget
gate still bounds total cost per night.
2026-05-31 22:43:24 +02:00
Marc-André Bombeck c775861d8c fix(insights): invalidate per-metric assessment caches on measurement edit and delete
The targeted status-insight invalidator only fired on insert and batch
ingest, so editing or deleting a reading left the affected per-metric
assessment cards serving their pre-mutation text for the rest of the day.
Add the fire-and-forget invalidation to the single-measurement PUT
(covering both the old and the new type when an edit re-types a row),
the single-measurement DELETE, and the iOS by-external-ids
reconciliation DELETE (keyed off the distinct types it tombstoned).
2026-05-31 22:43:24 +02:00
Marc-André Bombeck eee6ab2e7e refactor(insights): wire the WMY rollup tier into status snapshots and share generator helpers
Read the MONTH / YEAR rollup tier for the monthly / yearly slices of the
focused single-metric status snapshots (weight, pulse, bmi,
blood-pressure) via `buildGradedSeriesWithRollups`, so the coarse tiers
finally earn their write amplification. BMI has no tier of its own, so it
scales the WEIGHT tier by 1 / heightCm² (`scaleGradedSeries`) — an exact
linear transform. The multi-metric general overview and the tier-less
mood / adherence series keep their bounded in-memory fold.

Fix the coverage-miss path that returned an always-empty monthly / yearly
slice: the bounded ~90-day recent read can never supply those slices, so
on a cold-tier miss the builder now folds the full history in memory
rather than shipping empty coarse arrays when years of raw history exist.
Excludes tombstoned rows from both reads.

Lift the byte-identical `round`, `normalizeSummaryText`,
`normalizeLocale`, `summarizeSeries`, the `{summary}`-envelope parse, and
the cache-row persist block out of the seven generators into
`status-shared.ts`. Drop the per-medication expectation in the compliance
generator: the prompt returns only `{summary}`, so the per-med cards are
server-side placeholders rather than a dead model-authored branch. Remove
the unused `summarizeGradedSeries` export.

Behaviour is unchanged on the in-memory path; the rollup path is exact
where the tier composes (count / min / max / mean) and the payload stays
under the snapshot char cap.
2026-05-31 22:43:24 +02:00
Marc-André Bombeck 75380d5f39 fix(insights): lift explainer popover body to 12px + correct target-summary doc
Two small polish items on the insights category surface.

The desktop explainer popover body rendered at 11px while the mobile
sheet used the larger `text-sm`, an uncomfortable and asymmetric read.
Lift the popover body to `text-xs` (12px) so both surfaces sit on the
type scale.

The `MetricTargetSummary` docstring claimed both the range and the
in-target share are hidden when the route flags `insufficientData`. The
range stays visible — only the share is suppressed. Correct the comment
to match the code.
2026-05-31 22:35:02 +02:00
Marc-André Bombeck 36d5c79526 test(insights): pin explainerMetric props against the en.json explainer keys
`<MetricExplainer>` resolves its copy through a template literal
(`insights.subPage.explainer.${metric}{Title,Body}`), so the static
call-site coverage guard never sees these keys — a typo in an
`explainerMetric` prop would paint the raw key path with no CI signal.

Walk every `explainerMetric="…"` value under `src/app/insights/**` plus
the shared healthkit-metric-page scaffold and assert each resolves a
Title and Body leaf in messages/en.json. Also pin the literal-only prop
contract and a non-empty match count so a future rename can't silently
disable the guard. The locale-integrity test then carries the EN
guarantee to the other five bundles.
2026-05-31 22:35:02 +02:00
Marc-André Bombeck 05097df1ee feat(insights): give every category page a metric explainer + normalise keys to english
Two parts to the explainer surface, landed together because they share
the same i18n block and page props.

Coverage: every routed insights category page now passes an
`explainerMetric` prop, so the heading-side `?` glyph is present on all
37 pages instead of 13. The 24 newly covered metrics — body
composition (body water, bone/fat/muscle/lean mass, fat-free mass,
visceral fat), mobility (flights, walking distance/speed/steadiness,
asymmetry, double-support, step length, walking heart rate),
cardiovascular (pulse-wave velocity, vascular age), hearing
(environmental + headphone levels, loud-sound events), respiratory
rate, daylight, blood glucose, and skin temperature — each gain a one
to two sentence layperson definition grounded in standard clinical
references, shipped in all six locales.

Keys: the explainer key segments were a German/English mix
(`blutdruck`, `puls`, `gewicht`, `schlaf`, `stimmung`, `medikamente`
alongside English ones). Rename them to English to match the
naming-convention ADR — `bloodPressure`, `pulse`, `weight`, `sleep`,
`mood`, `medications` — across every locale, and update the
`explainerMetric` prop values that reference them. These are i18n key
segments, not route slugs, so the slug contract is untouched.
2026-05-31 22:35:02 +02:00
Marc-André Bombeck 8f120cfdef fix(insights): generalise the data-gating threshold across metric kinds
The hard '~5 measurement points' floor did not fit mood (counted in
entries) or medication adherence (counted in scheduled doses). Re-word
the gate as 'a few measurement points/entries/events' and note that the
unit depends on the metric. Also fix the gating-field path: the recency
field lives at dataCoverage.newestMeasurementDaysAgo, not on summary.
2026-05-31 22:32:20 +02:00
Marc-André Bombeck f683e8fd6d feat(insights): add a calm support pointer for sustained low mood
The mood card noted persistent low phases but offered no gentle path to
support. When mood stays clearly low for several days, the model now
offers an autonomy-preserving pointer toward talking it through with a
trusted person or a professional — never alarming, never a diagnosis, no
emergency tone. The safety-contract matrix does not cover this pathway
and does not reach the per-metric assessment prompts, so it lives here.
2026-05-31 22:32:20 +02:00
Marc-André Bombeck 0e9e9bc4ba fix(insights): weight 30-day adherence over the noisy 7-day window
For an infrequent schedule such as a weekly injection, the 7-day
compliance figure is dominated by a single dose: one miss swings the
percentage sharply and reads as a collapse it is not. Tell the model to
lean on compliance30 as the load-bearing value when schedulesPerDay is
low and treat compliance7 as a rough pointer only. Output stays {summary}.
2026-05-31 22:32:20 +02:00
Marc-André Bombeck 4c873ebb37 fix(insights): give the overall assessment its own length budget
The overall-status card summarises up to six metrics, but it inherited
the single-metric 30-60 word budget, which forced the model to either go
generic or overrun. Grant the section an explicit 3-5 sentence / 50-80
word budget and cap it at naming two metrics by name, with the rest
mentioned only when they deviate notably from their own mean.
2026-05-31 22:32:20 +02:00
Marc-André Bombeck d29b11cdf4 refactor(insights): split bmi and weight assessment focus
The bmi and weight cards produced near-identical trend text for a user
with both metrics, since bmi is weight scaled by a constant. Re-aim each
card so they carry distinct information: bmi now centres on WHO-band
placement (call out a band crossing or a near-boundary value against the
person's own baseline), and weight stays on the continuous trend and
pace (kg/week, plateau, milestone). Each defers the other concern to its
sibling card.
2026-05-31 22:32:20 +02:00
Marc-André Bombeck 262a3ad70a docs(insights): document english tile-id contract + naming ADR
Regenerate `docs/api/openapi.yaml` so the `InsightsLayoutBody` enum
carries the canonical English tile ids first, then the
accepted-but-deprecated legacy German ids, with the normalisation +
deprecation spelled out in the schema description. Add ADR 0001 fixing
the convention — localised UI copy, English internal identifiers — and
the non-breaking alias strategy. Add an iOS coordination note covering
the new canonical ids, the continued acceptance of the legacy ids, and
the recommended migration path.
2026-05-31 22:12:25 +02:00
Marc-André Bombeck 607dd9e5df feat(insights): accept legacy german tile ids as aliases
The tile-layout enum migrates from German to English to match the route
slugs. The contract on `GET/PUT /api/insights/layout` stays
non-breaking for clients that persisted the old German ids (the iOS
layout sync among them):

- the Zod enum is built from `ACCEPTED_INSIGHTS_TILE_IDS` (canonical
  English plus the legacy German aliases), so a PUT carrying old ids
  validates rather than tripping a 422;
- `normalizeInsightsTileId` collapses each legacy id onto its canonical
  English replacement on both the read path (`resolveInsightsLayout`)
  and the write path (`serializeInsightsLayout`), so a pre-rename layout
  surfaces English ids on GET without a forced re-PUT and a legacy PUT
  persists English ids;
- a layout carrying both a legacy and a canonical id for one tile
  dedupes to a single canonical entry.

The legacy ids are accepted-but-deprecated. Tests cover the read-side
normalisation and the write-side 200 (no 422) + canonical persistence.
2026-05-31 22:12:25 +02:00
Marc-André Bombeck c4ccd7e297 refactor(insights): migrate route slugs to english with redirects
Rename every routed Insights sub-page slug from German to English
(`/insights/blutdruck` -> `/insights/blood-pressure`, `gewicht` ->
`weight`, `medikamente` -> `medications`, and the full v1.7.0 metric
tail). UI copy stays localised through `t()` keys; only the internal
slugs change. The slug registry in `src/lib/insights/sub-page-metric.ts`
is the single source of truth, so the tab strip, target summary, and
daily-briefing routing targets follow it.

`next.config.ts` `redirects()` emits a permanent redirect from every
legacy German slug to its English target, including a `:path*` variant
so nested routes survive. Bookmarks and cached PWA navigation keep
resolving.
2026-05-31 22:12:25 +02:00
Marc-André Bombeck b416cabbf1 feat(insights): rewrite the overall assessment prompt to the assessment spec
Drop the dead-field guidance (avg90/allTime, historicalComparison,
ratePressureProduct, bodyCompositionDivergence, seasonalVariation) and
the chart-token instruction. Describe the per-type measurementSeries map
and the adherence/mood/target context, pull them into one coherent
picture against the person's own baseline, and close with the single
most important doable step.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck 56cff68ec5 feat(insights): rewrite the medication-adherence assessment prompt to the assessment spec
Replace the historicalComparison and moodAdherenceRisk guidance with the
actual per-medication snapshot fields (compliance7/30, streak,
taken/skipped/missed, dailySeries). Read the recent direction as
compliance7 vs compliance30 against the person's own baseline, frame
positively, and close with one blame-free doable step.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck 0f25226fdd feat(insights): rewrite the mood assessment prompt to the assessment spec
Describe the graded mood series, target band and tag list, lead on the
weekly pattern against the person's own baseline, name persistent low or
high phases calmly as an observation rather than a diagnosis, and close
with one kind doable step.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck 4e04e375ad feat(insights): rewrite the BMI assessment prompt to the assessment spec
Describe the graded BMI series and target band, lead on the trend over
the single value, keep the WHO bands as placement anchors rather than a
label for the person, and name BMI's body-composition limits plainly.
Drop the chart-token instruction the status path strips out.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck 052bbbfd7c feat(insights): rewrite the weight assessment prompt to the assessment spec
Replace the dead-field guidance (historicalComparison.weight,
allTimeMax, slope30, bodyCompositionDivergence, sleep.avg7) with the
graded weight series. Lead on the weekly/monthly trend rather than the
single value, define plateau and sustainable pace against the person's
own baseline, anchor milestones to their own maximum, and gate BMI
context on a known profile height.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck 4f48160b3d feat(insights): rewrite the pulse assessment prompt to the assessment spec
Drop the stale snapshot vocabulary (avg7/30/90, historicalComparison,
slope30, rate-pressure product) and the chart-token instruction the
status path strips out. Describe the graded pulse series and target
band, compare the recent days to the person's own weekly/monthly
baseline at a ~5 bpm significance threshold, and frame a rising or
falling resting pulse as a possible explanation rather than a diagnosis.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck 0f9fc70440 feat(insights): rewrite the base + blood-pressure assessment prompts to the graded-snapshot spec
The status cards render only the model's summary field, yet the prompt
described a snapshot vocabulary (avg7/30/90, historicalComparison,
ratePressureProduct, seasonalVariation) that the graded snapshot no
longer carries, and demanded a full findings/correlations JSON schema
that this path never reads.

Rebuild the shared base prompt around the actual graded shape (summary +
recent/weekly/monthly/yearly with min/max/mean/slope), the own-baseline
comparison, a name -> place -> one-step structure, a warm
autonomy-supporting tone, a 2-4 sentence length, honest data-gating, and
a { summary } output. The blood-pressure section judges systolic and
diastolic together against the person's own baseline with ESH 2023 as
the placement anchor.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck cd8849cd51 feat(insights): drop the per-metric assessment cache on fresh measurements
Hang `invalidateStatusInsightsForTypes` off every measurement ingest
path so a new reading of a type drops the cached assessment rows that
reading dirties — the next mount or nightly warm pass then regenerates
them against the new data instead of serving the pre-measurement text
for the rest of the day.

Wired into both `/api/measurements` modes (single + multi-entry batch),
`/api/measurements/batch`, and the three Withings sync paths
(measures + activity + sleep), reusing the `collapseToTypeDayKeys`
result each already computes for its rollup recompute. The call is
fire-and-forget after the user's write commits: idempotent, never a
blocker on the request path, and a failure only warns.
2026-05-31 22:05:31 +02:00
Marc-André Bombeck 177ce576d3 feat(insights): warm the per-metric assessment caches in the nightly pre-gen
The comprehensive generator evicts the seven `insights.<scope>-status`
caches as part of its write so a stale comprehensive insight can never
leave a stale per-metric card behind — but it does not re-fill them.
Before this, the morning after the nightly pre-gen cron ran the
per-metric status caches were empty, so the first `/insights` mount
still ran one live status generation per card.

After a successful comprehensive generation the cron now forces the
seven `*StatusForUser` generators so their caches are warm, not empty,
by the user's first visit. The warm pass only runs on a `generated`
outcome (a no-provider `skipped` has nothing to warm; a `failed` run
means the chain is unhealthy this tick — re-running it seven more times
would only multiply the failure). Each generator resolves the provider
chain internally, so a provider-less account stays cheap. The per-user
budget bucket that already bounds the comprehensive pass also gates the
warm pass — both run behind the same once-per-20h gate.

`runInsightPregenerate` now reports `assessmentsWarmed` and emits an
`insights.pregenerate.run` wide-event with the full per-run tally so the
nightly dashboard can track how many assessments each tick wrote.

Also adds `invalidateStatusInsightsForTypes` + `PER_STATUS_SCOPES` to
the comprehensive generator: a type → scope map (WEIGHT → weight + bmi +
general, BP → blood-pressure + general, PULSE/resting-HR → pulse +
general, everything else → general) so the ingest path can drop only the
scopes a fresh reading dirties.
2026-05-31 22:05:31 +02:00
Marc-André Bombeck 68a9f114a5 test(insights): cover graded compression and stub-skip
Pin the snapshot payload budget: a 2-year daily weigher (weight + daily
BP) and a six-type dense account both serialise under the 24 000-char
cap, proving the graded rewrite holds the line on the worst-case
accounts. The stub-skip and timeout-no-persist behaviour is covered by
the per-generator cache-read tests + the shared status-cache suite.
2026-05-31 21:51:18 +02:00
Marc-André Bombeck 11a06196f3 perf(insights): compress status snapshots via graded series (raw->week->month->year)
The seven per-card generators embedded the full ~360-day daily array
per metric plus correlation pair arrays, and never touched the
WEEK/MONTH/YEAR rollup tier. A dense daily weigher ran the weight
snapshot ~80-110 KB; a many-type account could push general-status past
100 K tokens.

Embed the shared graded series instead of the full daily array, cap the
embedded correlation/paired arrays to their most recent entries, skip
measurement types with no data in general-status, and apply a generic
24 000-char snapshot budget that sheds yearly -> weekly -> array-tails
-> recent until it fits. The applyPayloadBudget daily buckets stay
in-process to drive the latest-day focus, in-target gates, and
correlation pairing; only the compact shape reaches the prompt.

Measured on a 2-year daily account: weight-status ~15 KB, general-status
~12 KB across six dense types — both well under the cap.
2026-05-31 21:51:18 +02:00
Marc-André Bombeck 1b78df345d feat(insights): add a shared graded-series compressor for AI snapshots
Turn a metric's history into a small, bucketed, AI-ready shape: the
last ~21 days verbatim at daily granularity, the ~10 weeks before that
as ISO-week means, the ~12 months before that as calendar-month means,
and everything older as yearly buckets with a least-squares trend
slope. ~30-45 rows per metric regardless of history depth, never an
individual reading beyond the recent window.

A pure in-memory builder folds raw points; a rollup-backed builder
sources the monthly/yearly slices from the pre-aggregated MONTH/YEAR
tier (readBestGranularityRollups) and the recent/weekly slices from a
bounded ~90-day raw read, so the coarse rollup tier finally earns its
write amplification. The recent/weekly bucketing mirrors the coach's
timeline split, duplicated here so the coach contract stays put.
2026-05-31 21:51:18 +02:00
Marc-André Bombeck 5432063f5c fix(insights): stop caching the timeout fallback and align the status timeout with the coach
The per-card status path capped provider generation at 20 s and, on
timeout, persisted the generic no-key fallback as a day-keyed cache row.
The cache-read only checked the day key and text, so that stub looked
like a real assessment and stuck until midnight — hiding the real,
data-driven text for the rest of the day on any account that hit a
single transient stall.

Align the budget with the provider clients' 60 s ceiling, route the
status path through resolveProviderChain + runRawCompletionWithFallback
so a degraded provider cascades like the coach, and stop persisting the
fallback: a timeout or error is a transient miss that serves the
fallback for the current render and re-attempts on the next mount. A
shared cache-read rejects any lingering timeout-stub rows by their
markers, and withTimeout now annotates real errors instead of folding
them silently into the timeout path.
2026-05-31 21:51:18 +02:00
Marc-André Bombeck 16b4768fd1 feat(insights): surface target range and explainer on category pages
Each insights category page now carries two additions placed beside the
chart and assessment:

- a target-range card (MetricTargetSummary) showing the numeric goal
  band and the share of logged days within it, read from the shared
  /api/insights/targets payload so the bands match the /targets editor
  exactly. Blood pressure stitches the systolic and diastolic bands into
  one S/D string. A discreet link routes to /targets to adjust the band.
- a question-mark explainer next to each heading (MetricExplainer in
  SubPageShell) opening a static, layperson 'What is X?' read. Popover on
  desktop, bottom-sheet on phones; keyboard- and touch-reachable with a
  44px hit surface. Copy ships in all six locales.

The /targets page stays the canonical place to tune the bands.
2026-05-31 21:32:32 +02:00
171 changed files with 11870 additions and 3028 deletions

No files matched your search

@@ -0,0 +1,80 @@
# v1.8.0 — server → iOS: Insights tile-id rename (non-breaking)
Date: 2026-05-31
From: server
To: iOS
Status: informational — no action required to keep working; action recommended before a future major
## Summary
v1.8.0 renames the Insights tile ids (and the matching web route slugs) from
German to English to make the identifier space consistent. **This is
non-breaking for the iOS layout sync.** The `GET/PUT /api/insights/layout`
endpoint keeps accepting the old German ids. You do not need to ship anything to
stay working. When convenient, migrate to the canonical English ids.
## What changed
The canonical tile ids in `GET/PUT /api/insights/layout` are now English:
| Legacy (≤ v1.7.x) | Canonical (v1.8.0+) |
|---|---|
| `blutdruck` | `blood-pressure` |
| `puls` | `pulse` |
| `sauerstoff` | `oxygen` |
| `koerpertemperatur` | `body-temperature` |
| `gewicht` | `weight` |
| `aktive-energie` | `active-energy` |
| `schlaf` | `sleep` |
| `ruhepuls` | `resting-pulse` |
| `stimmung` | `mood` |
| `medikamente` | `medications` |
`overview`, `bmi`, `hrv`, and `workouts` were already language-neutral and are
unchanged.
## Why it does not break you
- **PUT still accepts the legacy German ids.** The server's validation enum is
the union of the canonical English ids and the legacy German aliases, so a
`PUT` carrying `blutdruck` / `puls` / … validates (no 422).
- **The server normalises legacy → canonical on write.** A `PUT` with German ids
persists the English equivalents. So after any save, the stored layout is
canonical English regardless of what you sent.
- **GET always returns canonical English ids.** A layout you persisted before
v1.8.0 (German ids) is normalised on read — `GET` surfaces the English ids
without forcing a re-`PUT`.
- **Dedupe.** If a payload carries both a legacy and a canonical id for one tile,
the server keeps a single canonical entry.
So the worst case for an un-migrated iOS build is: it keeps sending German ids,
the server keeps accepting and normalising them, and on the next `GET` the app
sees English ids it does not recognise in its local enum. If your client filters
unknown tile ids defensively, that filter must learn the English ids — see
below.
## What iOS should do (recommended, before a future major)
1. **Add the English ids to your tile-id enum / model** (keep the German ones as
decode-only aliases if your decoder is strict, or just map both).
2. **Send English ids on `PUT`.** Once your build is out, you stop relying on the
server's alias acceptance.
3. **Decode `GET` responses expecting English ids.** Because the server
normalises on read, a current `GET` already returns English; an app that hard-
filters to the old German enum would drop every tile. Decode the English ids
before you rely on this endpoint in a v1.8.0+ environment.
## Deprecation timeline
The legacy German ids are accepted-but-deprecated. They will be **removed from
the accepted input set in a future major version** once we confirm clients have
migrated. No date is fixed yet; we will give notice through this channel before
the removal. Until then, both id sets validate.
## References
- Contract: `docs/api/openapi.yaml` → `InsightsLayoutBody` (lists canonical +
legacy ids, with the deprecation noted in the schema description).
- Rationale: `docs/adr/0001-insights-naming-convention.md`.
- Web route slugs got the same English rename with 301 redirects from the legacy
German URLs; that is web-only and does not affect the iOS contract.
+74
View File
@@ -1,5 +1,79 @@
# Changelog
## [1.8.4] — 2026-06-01 — Medication card accuracy + Insights polish
### Fixed
- **The medication card shows the correct next intake for every schedule.** Flexible "interval after the last dose" and one-time medications previously showed a next-intake derived from a simplified day-of-week rule that ignored the interval and the last logged dose — so a medication taken every few weeks proposed tomorrow and never moved after a dose was logged. Both the standard and the injection card now read the schedule engine's computed next-due, so the next intake is right on creation and advances the moment a dose is recorded.
- **Insights status polling is bounded.** When a model is configured but generation stalls, the per-category assessment card no longer polls indefinitely on an open page — it stops after a fixed ceiling and shows its static state.
- **Clean deploys no longer hit a missing settings column.** Four `app_settings` columns existed in the schema but had only ever been applied ad-hoc, so a migrations-only deploy could fail on first read; an idempotent migration now adds them (a no-op on instances that already have them).
### Changed
- **Logging a dose confirms itself.** Marking a medication taken or skipped now shows a brief confirmation, and the card's next-intake updates immediately.
- **Each Insights category explains itself inline.** The short metric definition now also appears as a caption under the category heading, alongside the existing question-mark tooltip.
- **Medication history shows where each dose was logged** — web, the iOS app, a reminder, or an import — as a small origin label on each entry.
## [1.8.3] — 2026-06-01 — Insights no longer block the interface
Opening an Insights category and switching between them could freeze the whole interface for several seconds while the per-category assessment was generated. The interface now stays responsive throughout.
### Fixed
- **Switching Insights categories no longer freezes the interface.** Each category's short assessment is now served from cache as an immediate, read-only response; when it is not yet ready the page shows a brief preparing state and the assessment is generated in the background, so navigation and taps stay responsive. The client request is capped, so a slow or unreachable model can never block the interface — the worst case is a preparing state, never a frozen screen.
- **The overnight pre-generation warms the assessment actually shown.** The nightly warm pass keyed its cache differently from what the page requests, so a returning visit often fell back to an on-demand generation; it now warms the languages the interface uses and runs even when the daily summary was already cached, so a returning visit lands on a ready assessment.
- **A stalled model no longer re-blocks every visit.** A generation timeout is briefly remembered so the next visits return immediately instead of retrying the slow path each time.
- **Streamed loading states.** Insights and the dashboard now render a skeleton while their first segment loads, rather than waiting on a blank transition.
## [1.8.2] — 2026-06-01 — One intake row per dose slot
A multi-time medication could end up with two entries for the same dose — one still open, one marked taken — for a dose the user had not taken. This release guarantees a single entry per scheduled dose.
### Fixed
- **A dose slot can no longer hold a duplicate entry.** Logging a dose now updates the slot's existing entry in place instead of inserting a second row, regardless of where the log came from, and the logged time is aligned to the scheduled dose rather than the exact moment of the tap. A twice-daily medication no longer shows the same time twice (once open, once taken), the daily count is no longer inflated, and the "due now" prompt is no longer suppressed for a dose that has not actually been taken.
- **A recorded dose is never silently un-recorded.** A background re-sync that replays an open dose onto a slot already marked taken is now ignored rather than clearing the taken mark, so an offline sync can never flip a taken dose back to missed.
- **Concurrent logs converge.** Two logs landing on the same dose at once resolve to one entry instead of failing or duplicating.
- **Existing duplicates are cleaned up on startup.** A one-time pass collapses any duplicate dose entries already stored, keeping the recorded dose and correcting the affected compliance figures.
## [1.8.1] — 2026-06-01 — Multi-time medication compliance
A follow-up to the multi-time compliance work in 1.7.3, closing the two surfaces it did not reach.
### Fixed
- **Every scheduled time of a multi-time medication is now loggable** — a medication taken more than once a day on a single schedule with several times (e.g. 07:00 and 19:00) surfaced only its first dose in the today tile and the logging sheet, so the second dose could never be recorded and the day's compliance was counted against a single expected dose. The today-window projection now creates one pending dose per scheduled time, matching how reminders are issued.
- **The compliance heatmap classifies each dose against its own time** — a twice-daily dose logged in the evening was measured against the morning time and read as very late, painting the day amber even when both doses were taken on time. Each logged dose is now matched to its nearest scheduled time, so a day with every dose taken on time reads as on time. Single-time schedules are unaffected.
## [1.8.0] — 2026-05-31 — Insights: reliable data-driven assessments, embedded targets, explainers
The per-metric Insights pages become the coherent heart of the app. The data-driven assessment — a short, honest reading of your own trend — now reliably reaches the page: it previously timed out and cached a generic placeholder for the rest of the day, so most users only ever saw the platitude. The generation budget is aligned with the provider, the placeholder is never cached, and the AI payload is compressed into a graded shape (recent days raw, then weekly, monthly, and yearly aggregates drawn from the rollup tier) so a heavy logger no longer ships thousands of raw points. Each metric's prompt is rewritten to a consistent house style — name the finding, place it against your own baseline, offer one concrete step; honest on poor values, never alarmist, never diagnostic. Target ranges move onto each category page beside the chart, every category gains a plain-language "what is this?" tooltip, and the assessment is warmed overnight so the page is a cache read instead of a live call. Route slugs and tile ids move to English (German tile ids stay accepted as aliases, so existing clients keep working).
### Added
- **Per-category target ranges** — each Insights category page shows its numeric target range and the share of recent days within target, beside the chart and the assessment, with a link to adjust the range. The dedicated targets page remains the editing surface.
- **Per-category explainer tooltips** — a question-mark affordance next to every category heading opens a short, plain-language definition of the metric, available offline in all six languages and reachable by keyboard and touch.
- **Nightly assessment pre-generation** — a budget-gated overnight job warms the per-metric assessment caches (and invalidates them when fresh measurements arrive), so opening a category page is a cache read rather than a synchronous model call.
- **Graded measurement compression for assessments** — a shared compressor folds a metric's history into recent (daily), weekly, monthly, and yearly buckets, drawing the monthly/yearly tiers from the rollup store, so the model receives a compact picture instead of the full daily series.
- **Naming decision record** — `docs/adr/0001-insights-naming-convention.md` documents the convention: localised UI, English internal keys and route slugs.
### Changed
- **Data-driven assessments reach the page reliably** — the per-metric assessment generation budget is aligned with the provider (was capped well below the provider floor), runs through the provider chain with fallback, and a transient timeout or error is treated as a passing miss rather than cached as a placeholder for the rest of the day.
- **Assessment wording** — every metric prompt follows one house style (name → place against own baseline → one actionable step; 2–4 sentences; honest, autonomy-supporting, non-diagnostic; says so plainly when the data is too thin). Blood pressure reads systolic and diastolic together; weight tracks the trend while BMI speaks to threshold bands; the mood assessment carries a calm support cue on a sustained low.
- **Insights route slugs are English** — `/insights/<german>` moves to `/insights/<english>` with permanent redirects from the old paths. The dashboard-layout tile ids are English canonically; the previous German ids stay accepted as aliases and are normalised on read and write, so a client that stored the old ids keeps working.
- **Per-metric assessment caches drop on measurement changes** — a fresh, edited, or deleted measurement invalidates the affected category's cached assessment so it regenerates rather than serving a stale reading.
## [1.7.3] — 2026-05-31 — Health-record PDF fixes, multi-time compliance
Two fixes to live behaviour.
### Fixed
- **Health-record export renders in the account language** — the PDF came out in English regardless of the in-app language because the export only consulted the browser's `Accept-Language`. The client now sends the active language and the server falls back to the language cookie before the browser header.
- **Health-record export layout** — charts now label their time axis (start and end date of the plotted window), modules are kept together instead of breaking across a page, a consistent bottom margin is held on every page, and a glyph-encoding issue that stretched a few lines (trend arrows and the `m²` unit) is resolved by sanitising to the font's supported characters.
- **Compliance counts every scheduled time on multi-time plans** — a medication taken twice a day on a weekday plan with two times but no recurrence rule reported 50% even when both doses were logged: the expected-dose count and the taken count expanded the schedule through two different code paths. Both now run through the one canonical recurrence engine, so the rate is correct for every schedule shape.
## [1.7.2] — 2026-05-31 — Coach source parity, first-paint snapshot, medication card cleanup
A focused follow-up to v1.7.0. The unified dashboard snapshot that shipped in v1.7.0 is now the default, so a cold dashboard paints its above-the-fold tiles together instead of letting the mood tile arrive ahead of the rest. The Coach's in-chat data-source rail now reads and writes the same persisted data clusters as the settings sheet — one source of truth that survives a reload, so what the panel shows always matches what reaches the model. The medication overview cards collapse their action row into a single overflow menu, and the detail page is pared back to the intake history under a read-only plan summary. The advanced-settings sheet widens into a two-column layout and offers a medications export beside the existing import.
@@ -0,0 +1,82 @@
# 0001 — Insights naming convention: localised UI, English identifiers
- Status: accepted
- Date: 2026-05-31
## Context
The Insights surface grew bilingually. The mother page (`/insights`) and its
routed metric sub-pages were keyed by German slugs (`/insights/blutdruck`,
`/insights/gewicht`, …) because German was the primary author voice when the
routed strip first shipped. Over time the surface accumulated a mix: route
folders, the tile-layout enum, and several internal maps were German, while
later additions (`hrv`, `oxygenSaturation`, `restingHr`, `activeEnergy`,
`workouts`) landed in English. The result was an inconsistent identifier space
where a contributor could not predict whether a given key was German or English.
Identifiers leak. A German route slug shows up in URLs, in browser history, in
the OpenAPI contract the iOS client reads, and in every internal map that pivots
on the slug. Mixed-language identifiers make the codebase harder to navigate and
make the public API contract read inconsistently.
Two surfaces also speak these identifiers across a boundary we do not control:
1. **URLs** — bookmarked and cached by the PWA.
2. **The tile-layout contract** — `GET/PUT /api/insights/layout`, which the
native iOS client persists against. The tile ids in that payload are a
client-visible contract.
## Decision
Separate the two naming axes cleanly:
- **UI copy is always localised.** Every visible string resolves through an
i18n `t()` key and is translated across all six locales (`de / en / es / fr /
it / pl`). The user never sees a raw identifier.
- **Internal identifiers are English.** Route slugs (`/insights/<slug>`), the
tile-layout enum (`INSIGHTS_TILE_IDS`), query keys, and the internal
slug→metric / slug→target maps all use established English terms. English is
the lingua franca of the codebase and of the public API contract.
Concretely, v1.8.0 migrates the routed Insights slugs and the tile-layout enum
from German to English (e.g. `blutdruck` → `blood-pressure`, `gewicht` →
`weight`, `medikamente` → `medications`). The full rename table lives in
`src/lib/insights/sub-page-metric.ts` (slugs) and `src/lib/insights-layout.ts`
(tile ids).
## Non-breaking strategy
The migration must not break either client-visible boundary:
- **URLs.** `next.config.ts` `redirects()` emits a `permanent: true` (301)
redirect from every legacy German slug to its English target, including a
`:path*` variant so any nested route survives. Bookmarks and cached PWA
navigation keep resolving.
- **Tile-layout contract.** The layout endpoint keeps **accepting** the legacy
German tile ids on input. The Zod enum is built from
`ACCEPTED_INSIGHTS_TILE_IDS` (canonical English ids *plus* the legacy German
aliases), so a `PUT` carrying old ids validates rather than tripping a 422.
`normalizeInsightsTileId` collapses each legacy id onto its canonical English
replacement; this normalisation runs on **both** the read path
(`resolveInsightsLayout`) and the write path (`serializeInsightsLayout`), so:
- a layout persisted by a `≤ v1.7.x` client surfaces canonical English ids on
`GET` without forcing a re-`PUT`;
- a `PUT` sending legacy ids persists canonical English ids;
- a layout that carries both a legacy and a canonical id for one tile dedupes
to a single canonical entry.
The legacy ids are accepted-but-deprecated. They will be removed from the
accepted set in a future major version once telemetry shows clients have
migrated. The OpenAPI `InsightsLayoutBody` schema documents the canonical ids,
the accepted legacy ids, and the deprecation.
## Consequences
- The Insights identifier space is uniformly English and predictable.
- No client breaks on upgrade: old URLs redirect, old tile ids normalise.
- The legacy-alias map and the redirect table are deliberate, finite debt to be
retired in a future major. Until then they are covered by tests
(`src/app/api/insights/layout/__tests__/route.test.ts`) that assert the
non-breaking round-trip.
- New Insights surfaces follow the convention from the start: English slug,
English tile id, localised `t()` copy.
+37 -9
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: HealthLog API
version: 1.7.2
version: 1.8.4
description: >-
Self-hosted personal-health-tracking PWA — public API surface for the iOS native client and external ingest.
@@ -2440,17 +2440,27 @@ components:
type: string
enum:
- overview
- blood-pressure
- pulse
- oxygen
- body-temperature
- weight
- bmi
- active-energy
- workouts
- sleep
- resting-pulse
- hrv
- mood
- medications
- blutdruck
- puls
- sauerstoff
- koerpertemperatur
- gewicht
- bmi
- aktive-energie
- workouts
- schlaf
- ruhepuls
- hrv
- stimmung
- medikamente
visible:
@@ -2467,7 +2477,11 @@ components:
- version
- tiles
description: "Per-user Insights tile layout: an ordered list of tiles with a visibility flag. `version` is the layout
schema version; tile ids are a closed enum derived from the server's tile registry."
schema version. Tile ids are a closed enum: the canonical ids are English (matching the routed
`/insights/<slug>` sub-pages). The legacy German ids (blutdruck, puls, sauerstoff, koerpertemperatur, gewicht,
aktive-energie, schlaf, ruhepuls, stimmung, medikamente) remain accepted on input for backward compatibility and
are normalised to their English equivalents before persisting; GET responses always carry the canonical English
ids. The legacy ids are deprecated and will be removed in a future major version."
CoachMessageFeedbackRequest:
type: object
properties:
@@ -5935,17 +5949,27 @@ components:
type: string
enum:
- overview
- blood-pressure
- pulse
- oxygen
- body-temperature
- weight
- bmi
- active-energy
- workouts
- sleep
- resting-pulse
- hrv
- mood
- medications
- blutdruck
- puls
- sauerstoff
- koerpertemperatur
- gewicht
- bmi
- aktive-energie
- workouts
- schlaf
- ruhepuls
- hrv
- stimmung
- medikamente
visible:
@@ -5964,7 +5988,11 @@ components:
- tiles
additionalProperties: false
description: "Per-user Insights tile layout: an ordered list of tiles with a visibility flag. `version` is the layout
schema version; tile ids are a closed enum derived from the server's tile registry."
schema version. Tile ids are a closed enum: the canonical ids are English (matching the routed
`/insights/<slug>` sub-pages). The legacy German ids (blutdruck, puls, sauerstoff, koerpertemperatur, gewicht,
aktive-energie, schlaf, ruhepuls, stimmung, medikamente) remain accepted on input for backward compatibility and
are normalised to their English equivalents before persisting; GET responses always carry the canonical English
ids. The legacy ids are deprecated and will be removed in a future major version."
Medication:
type: object
properties:
+92 -5
View File
@@ -549,6 +549,8 @@
"dayStreak": "Tage Serie",
"taken": "Genommen",
"skipped": "Übersprungen",
"intakeToastTaken": "{name} als genommen erfasst",
"intakeToastSkipped": "{name} übersprungen",
"weekdaySunday": "Sonntag",
"weekdayMonday": "Montag",
"weekdayTuesday": "Dienstag",
@@ -1004,10 +1006,11 @@
"phaseResetDefaults": "Auf Defaults zurücksetzen",
"phaseSaved": "Erinnerungsphasen gespeichert",
"phaseReset": "Auf Defaults zurückgesetzt",
"sourceWeb": "Webseite",
"sourceApi": "Externe API",
"sourceReminder": "Telegram / Erinnerung",
"sourceImport": "CSV-Import",
"sourceWeb": "Web",
"sourceApi": "iOS-App",
"sourceReminder": "Erinnerung",
"sourceImport": "Import",
"intakeSourceVia": "über {origin}",
"intakeHistoryEmptyTitle": "Noch keine Einnahmen erfasst",
"intakeHistoryEmptyDescription": "Trage eine Einnahme auf der Tagesübersicht ein, um den Verlauf aufzubauen.",
"intakeHistoryEmptyAction": "Zur Tagesübersicht",
@@ -1382,6 +1385,7 @@
"bmiEmptyDescription": "Für den BMI wird deine Körpergröße benötigt. Hinterlege sie unter Einstellungen → Account.",
"bmiEmptyAction": "Account-Einstellungen öffnen",
"noAnalysisYet": "Noch keine Analyse vorhanden.",
"assessmentPreparing": "Einschätzung wird vorbereitet…",
"noProviderConfigured": "Auswertung nicht verfügbar.",
"startAnalysis": "Analyse starten",
"refreshAnalysis": "Analyse aktualisieren",
@@ -1800,7 +1804,90 @@
"medikamenteEmptyDescription": "Adhärenz-Insights brauchen mindestens ein erfasstes Medikament.",
"medikamenteEmptyAction": "Medikamente öffnen",
"therapyTimelineDescription": "Chronologisches GLP-1-Therapieprotokoll — Dosis-Änderungen, Injektionen, Bestand, Nebenwirkungen.",
"bmiDescription": "BMI aus deinem Gewicht und deiner Größe abgeleitet, mit Einschätzung."
"bmiDescription": "BMI aus deinem Gewicht und deiner Größe abgeleitet, mit Einschätzung.",
"target": {
"range": "Ziel: {min}–{max} {unit}",
"bpRange": "Ziel: {sysMin}–{sysMax} / {diaMin}–{diaMax} {unit}",
"inTargetShare": "{pct}% der erfassten Tage im Zielbereich",
"adjustLink": "Zielbereich anpassen"
},
"explainer": {
"trigger": "Was ist {title}?",
"bloodPressureTitle": "Blutdruck",
"bloodPressureBody": "Der Blutdruck ist die Kraft, die das Blut auf die Gefäßwände ausübt, angegeben als systolisch zu diastolisch (Spitzenwert beim Herzschlag über dem Ruhewert dazwischen). Dauerhaft hohe Werte belasten Herz und Gefäße auf Dauer.",
"pulseTitle": "Puls",
"pulseBody": "Der Puls gibt an, wie oft das Herz pro Minute schlägt. Eine Einzelmessung spiegelt den Moment wider – in Ruhe liegt er meist bei 60–100 Schlägen pro Minute und steigt natürlicherweise bei Bewegung, Stress oder Koffein.",
"weightTitle": "Gewicht",
"weightBody": "Das Körpergewicht ist eines der einfachsten Signale für die langfristige Energiebilanz und die allgemeine Gesundheit. Der Trend über Wochen zählt weit mehr als ein einzelner Wert, der mit Flüssigkeit, Ernährung und Tageszeit schwankt.",
"bmiTitle": "Body-Mass-Index (BMI)",
"bmiBody": "Der BMI ist das Gewicht geteilt durch die Körpergröße zum Quadrat und ordnet Sie einer groben Gewichtskategorie zu. Er ist ein Orientierungswert, keine Diagnose, und unterscheidet nicht zwischen Muskeln und Fett.",
"sleepTitle": "Schlaf",
"sleepBody": "Die Schlafdauer ist die tatsächlich geschlafene Zeit pro Nacht, aufgeteilt in Leicht-, Tief- und REM-Schlaf. Die meisten Erwachsenen brauchen etwa sieben bis neun Stunden; gleichmäßige Menge und Qualität unterstützen Erholung, Stimmung und Stoffwechsel.",
"moodTitle": "Stimmung",
"moodBody": "Die Stimmungserfassung hält auf einer einfachen Skala fest, wie Sie sich fühlen. Regelmäßiges Protokollieren zeigt Muster – wie Schlaf, Aktivität oder Medikamente mit dem Befinden zusammenhängen –, die ein einzelner Tag nie offenbart.",
"medicationsTitle": "Medikamenten-Therapietreue",
"medicationsBody": "Die Therapietreue zeigt, wie zuverlässig Sie Ihre Medikamente wie verordnet einnehmen, hier als Anteil der erwarteten Dosen, die Sie erfasst haben. Eine gleichmäßige Einnahme entscheidet oft darüber, ob eine Therapie wie beabsichtigt wirkt.",
"restingHrTitle": "Ruhepuls",
"restingHrBody": "Der Ruhepuls ist die Herzfrequenz in völliger Ruhe, meist über Nacht gemessen. Ein niedriger Ruhepuls deutet in der Regel auf eine bessere Herz-Kreislauf-Fitness hin, ein steigender Trend kann ein frühes Zeichen für Stress oder Krankheit sein.",
"hrvTitle": "Herzfrequenzvariabilität (HRV)",
"hrvBody": "Die HRV ist die kleine Schwankung der Zeit zwischen aufeinanderfolgenden Herzschlägen. Eine höhere Variabilität spiegelt meist ein gut erholtes, anpassungsfähiges Nervensystem wider, ein anhaltender Rückgang kann auf Erschöpfung, Stress oder mangelnde Erholung hinweisen.",
"oxygenSaturationTitle": "Sauerstoffsättigung (SpO₂)",
"oxygenSaturationBody": "Die SpO₂ ist der Prozentsatz der roten Blutkörperchen, die Sauerstoff transportieren. Werte von 95–100 % sind in Ruhe normal; Werte, die dauerhaft unter 90 % liegen, verdienen Aufmerksamkeit, kurze nächtliche Abfälle sind jedoch häufig.",
"bodyTemperatureTitle": "Körpertemperatur",
"bodyTemperatureBody": "Die Körpertemperatur spiegelt Ihren Kernwärmezustand wider, normalerweise um 37 °C mit kleinen Tagesschwankungen. Ein anhaltender Anstieg kann auf eine Infektion hindeuten; nächtliche Messungen am Handgelenk erfassen vor allem relative Änderungen, keinen klinischen Wert.",
"activeEnergyTitle": "Aktive Energie",
"activeEnergyBody": "Die aktive Energie sind die Kalorien, die Sie durch Bewegung verbrennen, zusätzlich zum Grundumsatz in Ruhe. Sie ist ein direktes Maß dafür, wie körperlich aktiv Ihr Tag war.",
"workoutsTitle": "Workouts",
"workoutsBody": "Workouts sind die strukturierten Trainingseinheiten, die Ihre Geräte mit Art, Dauer und Energie aufzeichnen. Ihre Erfassung zeigt, wie sich regelmäßiges Training über Wochen summiert und wie es mit Ihren anderen Gesundheitssignalen zusammenhängt.",
"respiratoryRateTitle": "Atemfrequenz",
"respiratoryRateBody": "Die Atemfrequenz ist die Anzahl der Atemzüge pro Minute. In Ruhe atmen die meisten Erwachsenen etwa zwölf- bis zwanzigmal pro Minute; ein anhaltender Anstieg kann mit Krankheit, Anstrengung oder Stress einhergehen.",
"bodyWaterTitle": "Gesamtkörperwasser",
"bodyWaterBody": "Das Gesamtkörperwasser ist der Anteil deines Körpergewichts, der aus Flüssigkeit in und um die Zellen besteht. Es schwankt mit Flüssigkeitshaushalt, Ernährung und Aktivität, daher sagt der Trend über Wochen mehr aus als ein einzelner Wert.",
"boneMassTitle": "Knochenmasse",
"boneMassBody": "Die Knochenmasse ist das geschätzte Gewicht der Mineralien in deinem Skelett. Waagengestützte Schätzungen sind ungefähr, doch ein gleichbleibender oder steigender Trend unterstützt die langfristige Knochenstärke.",
"fatFreeMassTitle": "Fettfreie Masse",
"fatFreeMassBody": "Die fettfreie Masse ist alles in deinem Körper, das kein Fett ist — Muskeln, Knochen, Organe und Wasser. Sie zu halten oder aufzubauen, während das Gewicht sinkt, deutet meist auf eine gesündere Körperzusammensetzung hin.",
"fatMassTitle": "Fettmasse",
"fatMassBody": "Die Fettmasse ist das Gesamtgewicht des Körperfetts. Etwas Fett ist für Hormone und Energiespeicher unverzichtbar, doch zu viel — besonders am Bauch — erhöht das langfristige Gesundheitsrisiko.",
"muscleMassTitle": "Muskelmasse",
"muscleMassBody": "Die Muskelmasse ist das geschätzte Gewicht der Muskeln in deinem Körper. Mehr Muskeln unterstützen Kraft, Stoffwechsel und Beweglichkeit und müssen mit zunehmendem Alter aktiv erhalten werden.",
"visceralFatTitle": "Viszeralfett",
"visceralFatBody": "Viszeralfett ist das Fett, das tief im Bauchraum um die Organe gespeichert wird. Anders als das Unterhautfett ist ein hoher Wert eng mit Herzkrankheiten und Typ-2-Diabetes verbunden, daher ist niedriger meist besser.",
"leanBodyMassTitle": "Magermasse",
"leanBodyMassBody": "Die Magermasse ist dein Gesamtgewicht abzüglich des Körperfetts — Muskeln, Knochen, Organe und Wasser zusammen. Sie neben dem Gewicht zu verfolgen zeigt, ob Veränderungen aus Muskeln oder aus Fett stammen.",
"flightsClimbedTitle": "Etagen gestiegen",
"flightsClimbedBody": "Die gestiegenen Etagen zählen die Stockwerke, die du täglich nach oben gehst, wobei eine Etage etwa drei Metern Höhe entspricht. Es ist ein einfacher Marker für Alltagsaktivität und Beinarbeit.",
"walkingDistanceTitle": "Geh- + Laufstrecke",
"walkingDistanceBody": "Die Geh- und Laufstrecke ist die Strecke, die du täglich zu Fuß zurücklegst. Sie ergänzt die Schrittzahl, indem sie zeigt, wie weit du dich bewegt hast, nicht nur wie oft du getreten bist.",
"walkingSteadinessTitle": "Gehstabilität",
"walkingSteadinessBody": "Die Gehstabilität schätzt, wie stabil und ausgewogen dein Gangbild ist, eingeteilt von OK bis niedrig. Ein niedriger Wert deutet auf ein höheres Sturzrisiko hin und sollte ärztlich besprochen werden.",
"walkingHeartRateTitle": "Herzfrequenz beim Gehen",
"walkingHeartRateBody": "Die Herzfrequenz beim Gehen ist dein durchschnittlicher Puls bei einem gleichmäßigen Spaziergang. Ein über die Zeit niedrigerer Wert spiegelt bei gleicher Anstrengung oft eine bessere Herz-Kreislauf-Fitness wider.",
"walkingAsymmetryTitle": "Gangasymmetrie",
"walkingAsymmetryBody": "Die Gangasymmetrie ist der Anteil der Zeit, in der deine Schritte zwischen linkem und rechtem Bein ungleichmäßig sind. Ein höherer Prozentsatz kann auf Schmerzen, eine Verletzung oder ein Gangproblem hindeuten, das näher betrachtet werden sollte.",
"doubleSupportTimeTitle": "Doppelunterstützungszeit",
"doubleSupportTimeBody": "Die Doppelunterstützungszeit ist der Anteil jedes Gehzyklus, in dem beide Füße gleichzeitig den Boden berühren. Ein höherer Prozentsatz bedeutet meist ein vorsichtigeres, weniger stabiles Gangbild.",
"stepLengthTitle": "Schrittlänge",
"stepLengthBody": "Die Schrittlänge ist der durchschnittliche Abstand von einem Fußauftritt zum nächsten. Eine über die Zeit kürzere Schrittlänge kann Müdigkeit, Vorsicht oder eine veränderte Beweglichkeit widerspiegeln.",
"walkingSpeedTitle": "Gehgeschwindigkeit",
"walkingSpeedBody": "Die Gehgeschwindigkeit ist, wie schnell du dich auf ebenem Untergrund fortbewegst. Sie ist ein gut untersuchter Marker für allgemeine Gesundheit und Beweglichkeit, und ein gleichbleibendes oder steigendes Tempo ist ein gutes Zeichen.",
"pulseWaveVelocityTitle": "Pulswellengeschwindigkeit",
"pulseWaveVelocityBody": "Die Pulswellengeschwindigkeit misst, wie schnell die Druckwelle jedes Herzschlags durch deine Arterien läuft. Eine schnellere Welle weist auf steifere Arterien hin, was mit einem höheren Herz-Kreislauf-Risiko verbunden ist.",
"vascularAgeTitle": "Gefäßalter",
"vascularAgeBody": "Das Gefäßalter schätzt anhand der Arteriensteifigkeit, wie alt sich deine Arterien im Vergleich zu deinem tatsächlichen Alter verhalten. Ein Gefäßalter unter dem echten Alter deutet auf gesündere Blutgefäße hin.",
"environmentalAudioTitle": "Umgebungslautstärke",
"environmentalAudioBody": "Die Umgebungslautstärke erfasst die Lautstärke deiner Umwelt in Dezibel. Anhaltende Belastung über etwa 70 dB kann das Gehör mit der Zeit schädigen, daher sind niedrigere Tagesmittel sicherer.",
"headphoneAudioTitle": "Kopfhörerlautstärke",
"headphoneAudioBody": "Die Kopfhörerlautstärke erfasst in Dezibel, wie laut du über Ohrhörer oder Kopfhörer hörst. Die Lautstärke niedrig zu halten und Pausen einzulegen schützt dein Gehör langfristig.",
"audioEventsTitle": "Laute Geräuschereignisse",
"audioEventsBody": "Laute Geräuschereignisse markieren Momente, in denen der Lärm um dich herum ein Niveau erreicht hat, das bei ausreichender Belastung das Gehör schädigen kann. Häufige Ereignisse sind ein Hinweis, eine ruhigere Umgebung oder Gehörschutz zu suchen.",
"daylightTitle": "Zeit im Tageslicht",
"daylightBody": "Die Zeit im Tageslicht ist, wie lange du dich täglich im Freien im Licht aufhältst. Regelmäßiges Tageslicht unterstützt einen gesunden Schlaf-Wach-Rhythmus und die Stimmung, und Zeit im Freien ist mit der Augengesundheit verbunden.",
"bloodGlucoseTitle": "Blutzucker",
"bloodGlucoseBody": "Der Blutzucker ist die Zuckermenge in deinem Blut, die wichtigste Energiequelle des Körpers. Er steigt nach dem Essen und pendelt sich zwischen den Mahlzeiten ein; dauerhaft hohe Werte können auf Diabetes oder Prädiabetes hinweisen.",
"skinTemperatureTitle": "Hauttemperatur",
"skinTemperatureBody": "Die Hauttemperatur ist hier die kleine nächtliche Abweichung deiner Handgelenkstemperatur von deinem eigenen Ausgangswert, keine absolute Fiebermessung. Veränderungen können Schlaf, Umgebung, Krankheit oder Zyklusphase widerspiegeln."
}
},
"sleep": {
"title": "Schlaf",
+92 -5
View File
@@ -549,6 +549,8 @@
"dayStreak": "day streak",
"taken": "Taken",
"skipped": "Skipped",
"intakeToastTaken": "{name} recorded as taken",
"intakeToastSkipped": "{name} skipped",
"weekdaySunday": "Sunday",
"weekdayMonday": "Monday",
"weekdayTuesday": "Tuesday",
@@ -1004,10 +1006,11 @@
"phaseResetDefaults": "Reset to defaults",
"phaseSaved": "Reminder phases saved",
"phaseReset": "Reset to defaults",
"sourceWeb": "Website",
"sourceApi": "External API",
"sourceReminder": "Telegram / Reminder",
"sourceImport": "CSV Import",
"sourceWeb": "Web",
"sourceApi": "iOS App",
"sourceReminder": "Reminder",
"sourceImport": "Import",
"intakeSourceVia": "via {origin}",
"intakeHistoryEmptyTitle": "No intakes recorded yet",
"intakeHistoryEmptyDescription": "Log a dose on the daily intake page to start building the history.",
"intakeHistoryEmptyAction": "Open daily intake",
@@ -1376,6 +1379,7 @@
},
"insights": {
"noAnalysisYet": "No analysis yet.",
"assessmentPreparing": "Preparing your assessment…",
"emptyTitle": "Not enough data yet",
"emptyDescription": "Insights light up once you've logged a handful of measurements. Start with weight or blood pressure.",
"emptyAddMeasurement": "Add a measurement",
@@ -1800,7 +1804,90 @@
"medikamenteEmptyDescription": "Compliance insights need at least one tracked medication.",
"medikamenteEmptyAction": "Open medications",
"therapyTimelineDescription": "Chronological GLP-1 therapy log — dose changes, injections, inventory, side effects.",
"bmiDescription": "BMI derived from your weight and height, with a written assessment."
"bmiDescription": "BMI derived from your weight and height, with a written assessment.",
"target": {
"range": "Target: {min}–{max} {unit}",
"bpRange": "Target: {sysMin}–{sysMax} / {diaMin}–{diaMax} {unit}",
"inTargetShare": "{pct}% of logged days within target",
"adjustLink": "Adjust target range"
},
"explainer": {
"trigger": "What is {title}?",
"bloodPressureTitle": "Blood pressure",
"bloodPressureBody": "Blood pressure is the force your blood exerts on the artery walls, written as systolic over diastolic (the peak during a heartbeat over the resting value between beats). Consistently high readings strain the heart and blood vessels over time.",
"pulseTitle": "Pulse",
"pulseBody": "Your pulse is how many times your heart beats per minute. A spot reading reflects what you were doing in the moment — at rest it is typically 60–100 beats per minute, and it rises naturally with movement, stress, or caffeine.",
"weightTitle": "Weight",
"weightBody": "Body weight is one of the simplest signals of long-term energy balance and overall health. The trend over weeks matters far more than any single reading, which fluctuates with hydration, food, and time of day.",
"bmiTitle": "Body mass index (BMI)",
"bmiBody": "BMI is your weight divided by your height squared, giving a single number that places you in a broad weight category. It is a population-level screen, not a diagnosis, and does not distinguish muscle from fat.",
"sleepTitle": "Sleep",
"sleepBody": "Sleep duration is how long you actually slept across the night, split into light, deep, and REM stages. Most adults need roughly seven to nine hours; both consistent quantity and quality support recovery, mood, and metabolism.",
"moodTitle": "Mood",
"moodBody": "Mood tracking records how you feel over time on a simple scale. Logging it regularly reveals patterns — how sleep, activity, or medication line up with how you feel — that a single day never shows.",
"medicationsTitle": "Medication adherence",
"medicationsBody": "Adherence is how reliably you take your medication as prescribed, shown here as the share of expected doses you actually logged. Steady intake is often what makes a treatment work as intended.",
"restingHrTitle": "Resting heart rate",
"restingHrBody": "Resting heart rate is your heart rate when you are completely at rest, usually measured overnight. A lower resting rate generally points to better cardiovascular fitness, and a rising trend can be an early sign of stress or illness.",
"hrvTitle": "Heart rate variability (HRV)",
"hrvBody": "HRV is the tiny variation in time between consecutive heartbeats. Higher variability usually reflects a well-recovered, adaptable nervous system, while a sustained drop can signal fatigue, stress, or insufficient recovery.",
"oxygenSaturationTitle": "Oxygen saturation (SpO₂)",
"oxygenSaturationBody": "SpO₂ is the percentage of your red blood cells carrying oxygen. Readings of 95–100% are normal at rest; values that stay below 90% warrant attention, though brief nightly dips are common.",
"bodyTemperatureTitle": "Body temperature",
"bodyTemperatureBody": "Body temperature reflects your core thermal state, normally around 37 °C with small daily swings. A sustained rise can indicate infection, while overnight wrist readings mainly track relative changes rather than a clinical value.",
"activeEnergyTitle": "Active energy",
"activeEnergyBody": "Active energy is the calories you burn through movement, on top of the baseline your body uses at rest. It is a direct measure of how physically active your day was.",
"workoutsTitle": "Workouts",
"workoutsBody": "Workouts are the structured exercise sessions your devices record, with type, duration, and energy. Tracking them shows how regular training accumulates over weeks and how it relates to your other health signals.",
"respiratoryRateTitle": "Respiratory rate",
"respiratoryRateBody": "Respiratory rate is the number of breaths you take per minute. At rest most adults breathe roughly twelve to twenty times a minute; a sustained rise can accompany illness, exertion, or stress.",
"bodyWaterTitle": "Total body water",
"bodyWaterBody": "Total body water is the share of your body weight made up of fluid, inside and around your cells. It shifts with hydration, food, and activity, so the trend over weeks tells you more than any single reading.",
"boneMassTitle": "Bone mass",
"boneMassBody": "Bone mass is the estimated weight of the mineral in your skeleton. Scale-based estimates are approximate, but a steady or rising trend supports long-term bone strength.",
"fatFreeMassTitle": "Fat-free mass",
"fatFreeMassBody": "Fat-free mass is everything in your body that is not fat — muscle, bone, organs, and water. Holding or building it while losing weight usually signals healthier body composition.",
"fatMassTitle": "Fat mass",
"fatMassBody": "Fat mass is the total weight of fat in your body. Some fat is essential for hormones and energy storage, but too much — especially around the abdomen — raises long-term health risk.",
"muscleMassTitle": "Muscle mass",
"muscleMassBody": "Muscle mass is the estimated weight of the muscle in your body. More muscle supports strength, metabolism, and mobility, and it tends to need active effort to preserve as you age.",
"visceralFatTitle": "Visceral fat",
"visceralFatBody": "Visceral fat is the fat stored deep in the abdomen around your organs. Unlike fat under the skin, a high level is closely linked to heart disease and type 2 diabetes, so lower is generally better.",
"leanBodyMassTitle": "Lean body mass",
"leanBodyMassBody": "Lean body mass is your total weight minus body fat — muscle, bone, organs, and water combined. Tracking it alongside weight shows whether changes come from muscle or from fat.",
"flightsClimbedTitle": "Flights climbed",
"flightsClimbedBody": "Flights climbed counts the floors you go up each day, with one flight roughly ten feet of elevation. It is a simple marker of incidental activity and lower-body effort.",
"walkingDistanceTitle": "Walking + running distance",
"walkingDistanceBody": "Walking and running distance is the ground you cover on foot each day. It complements step count by reflecting how far you moved, not just how often you stepped.",
"walkingSteadinessTitle": "Walking steadiness",
"walkingSteadinessBody": "Walking steadiness estimates how stable and balanced your gait is, classed from OK to low. A lower level points to a higher chance of a fall and is worth discussing with a clinician.",
"walkingHeartRateTitle": "Walking heart rate",
"walkingHeartRateBody": "Walking heart rate is your average pulse during a steady walk. A lower walking rate over time often reflects improving cardiovascular fitness for the same effort.",
"walkingAsymmetryTitle": "Walking asymmetry",
"walkingAsymmetryBody": "Walking asymmetry is the share of time your steps are uneven between the left and right leg. A higher percentage can point to pain, injury, or a gait problem worth looking into.",
"doubleSupportTimeTitle": "Double support time",
"doubleSupportTimeBody": "Double support time is the share of each walking cycle when both feet touch the ground at once. A higher percentage usually means a more cautious, less stable gait.",
"stepLengthTitle": "Step length",
"stepLengthBody": "Step length is the average distance from one footfall to the next. A shorter step over time can reflect fatigue, caution, or a change in mobility.",
"walkingSpeedTitle": "Walking speed",
"walkingSpeedBody": "Walking speed is how fast you move on a level walk. It is a well-studied marker of overall health and mobility, and a steady or rising pace is a good sign.",
"pulseWaveVelocityTitle": "Pulse wave velocity",
"pulseWaveVelocityBody": "Pulse wave velocity measures how fast the pressure wave from each heartbeat travels along your arteries. A faster wave indicates stiffer arteries, which is linked to higher cardiovascular risk.",
"vascularAgeTitle": "Vascular age",
"vascularAgeBody": "Vascular age estimates how old your arteries behave compared with your actual age, based on arterial stiffness. A vascular age below your real age suggests healthier blood vessels.",
"environmentalAudioTitle": "Environmental sound levels",
"environmentalAudioBody": "Environmental sound levels track the loudness of the world around you in decibels. Prolonged exposure above about 70 dB can damage hearing over time, so lower daily averages are safer.",
"headphoneAudioTitle": "Headphone audio levels",
"headphoneAudioBody": "Headphone audio levels track how loudly you listen through earbuds or headphones, in decibels. Keeping the volume down and taking breaks protects your hearing over the long run.",
"audioEventsTitle": "Loud sound events",
"audioEventsBody": "Loud sound events flag moments when noise around you reached a level that can harm hearing with enough exposure. Frequent events are a cue to seek quieter surroundings or hearing protection.",
"daylightTitle": "Time in daylight",
"daylightBody": "Time in daylight is how long you spend in outdoor light each day. Regular daylight supports a healthy sleep-wake rhythm and mood, and time outdoors is linked to eye health.",
"bloodGlucoseTitle": "Blood glucose",
"bloodGlucoseBody": "Blood glucose is the amount of sugar in your blood, the body's main energy source. It rises after eating and settles between meals; readings that stay high over time can signal diabetes or prediabetes.",
"skinTemperatureTitle": "Skin temperature",
"skinTemperatureBody": "Skin temperature here is the small nightly change in your wrist temperature from your own baseline, not an absolute fever reading. Shifts can track sleep, environment, illness, or menstrual-cycle phase."
}
},
"sleep": {
"title": "Sleep",
+89 -2
View File
@@ -549,6 +549,8 @@
"dayStreak": "días de racha",
"taken": "Tomada",
"skipped": "Omitida",
"intakeToastTaken": "{name} registrada como tomada",
"intakeToastSkipped": "{name} omitida",
"weekdaySunday": "Domingo",
"weekdayMonday": "Lunes",
"weekdayTuesday": "Martes",
@@ -1005,9 +1007,10 @@
"phaseSaved": "Fases de recordatorio guardadas",
"phaseReset": "Restablecidas a valores por defecto",
"sourceWeb": "Web",
"sourceApi": "API",
"sourceApi": "App de iOS",
"sourceReminder": "Recordatorio",
"sourceImport": "Importación",
"intakeSourceVia": "vía {origin}",
"intakeHistoryEmptyTitle": "Aún no hay tomas",
"intakeHistoryEmptyDescription": "En cuanto registres una toma, aparecerá aquí con la hora y la fuente.",
"intakeHistoryEmptyAction": "Registrar toma",
@@ -1376,6 +1379,7 @@
},
"insights": {
"noAnalysisYet": "Aún no hay análisis.",
"assessmentPreparing": "Preparando tu evaluación…",
"emptyTitle": "Aún no hay datos suficientes",
"emptyDescription": "Los insights aparecen en cuanto registres algunas mediciones. Empieza por peso o tensión arterial.",
"emptyAddMeasurement": "Registrar medición",
@@ -1800,7 +1804,90 @@
"medikamenteEmptyDescription": "Los insights de adherencia necesitan al menos un medicamento registrado.",
"medikamenteEmptyAction": "Abrir medicamentos",
"therapyTimelineDescription": "Protocolo cronológico de terapia GLP-1 — cambios de dosis, inyecciones, existencias, efectos secundarios.",
"bmiDescription": "IMC derivado de tu peso y altura, con valoración."
"bmiDescription": "IMC derivado de tu peso y altura, con valoración.",
"target": {
"range": "Objetivo: {min}–{max} {unit}",
"bpRange": "Objetivo: {sysMin}–{sysMax} / {diaMin}–{diaMax} {unit}",
"inTargetShare": "{pct}% de los días registrados dentro del objetivo",
"adjustLink": "Ajustar el rango objetivo"
},
"explainer": {
"trigger": "¿Qué es {title}?",
"bloodPressureTitle": "Presión arterial",
"bloodPressureBody": "La presión arterial es la fuerza que ejerce la sangre sobre las paredes de las arterias, expresada como sistólica sobre diastólica (el pico durante un latido sobre el valor en reposo entre latidos). Los valores altos de forma constante sobrecargan el corazón y los vasos con el tiempo.",
"pulseTitle": "Pulso",
"pulseBody": "El pulso es cuántas veces late el corazón por minuto. Una medición puntual refleja lo que hacías en ese momento: en reposo suele ser de 60 a 100 latidos por minuto y sube de forma natural con el movimiento, el estrés o la cafeína.",
"weightTitle": "Peso",
"weightBody": "El peso corporal es una de las señales más simples del balance energético a largo plazo y de la salud general. La tendencia a lo largo de las semanas importa mucho más que cualquier lectura individual, que varía con la hidratación, la comida y la hora del día.",
"bmiTitle": "Índice de masa corporal (IMC)",
"bmiBody": "El IMC es tu peso dividido por tu altura al cuadrado, un único número que te sitúa en una categoría amplia de peso. Es un cribado poblacional, no un diagnóstico, y no distingue el músculo de la grasa.",
"sleepTitle": "Sueño",
"sleepBody": "La duración del sueño es cuánto dormiste realmente durante la noche, dividido en fases ligera, profunda y REM. La mayoría de los adultos necesita entre siete y nueve horas; tanto la cantidad como la calidad constantes favorecen la recuperación, el ánimo y el metabolismo.",
"moodTitle": "Estado de ánimo",
"moodBody": "El registro del estado de ánimo anota cómo te sientes con el tiempo en una escala sencilla. Anotarlo con regularidad revela patrones —cómo el sueño, la actividad o la medicación se relacionan con cómo te sientes— que un solo día nunca muestra.",
"medicationsTitle": "Adherencia a la medicación",
"medicationsBody": "La adherencia es la fiabilidad con la que tomas tu medicación según lo prescrito, aquí como la proporción de dosis previstas que registraste. Una toma constante suele ser lo que hace que un tratamiento funcione como se pretende.",
"restingHrTitle": "Frecuencia cardíaca en reposo",
"restingHrBody": "La frecuencia cardíaca en reposo es tu ritmo cardíaco cuando estás completamente en reposo, normalmente medido durante la noche. Una frecuencia más baja suele indicar mejor forma cardiovascular, y una tendencia al alza puede ser una señal temprana de estrés o enfermedad.",
"hrvTitle": "Variabilidad de la frecuencia cardíaca (VFC)",
"hrvBody": "La VFC es la pequeña variación en el tiempo entre latidos consecutivos. Una mayor variabilidad suele reflejar un sistema nervioso bien recuperado y adaptable, mientras que una caída sostenida puede señalar fatiga, estrés o recuperación insuficiente.",
"oxygenSaturationTitle": "Saturación de oxígeno (SpO₂)",
"oxygenSaturationBody": "La SpO₂ es el porcentaje de glóbulos rojos que transportan oxígeno. Los valores de 95 a 100 % son normales en reposo; los valores que se mantienen por debajo del 90 % merecen atención, aunque las bajadas breves nocturnas son frecuentes.",
"bodyTemperatureTitle": "Temperatura corporal",
"bodyTemperatureBody": "La temperatura corporal refleja tu estado térmico central, normalmente en torno a 37 °C con pequeñas variaciones diarias. Un aumento sostenido puede indicar una infección, mientras que las lecturas nocturnas en la muñeca reflejan sobre todo cambios relativos, no un valor clínico.",
"activeEnergyTitle": "Energía activa",
"activeEnergyBody": "La energía activa son las calorías que quemas con el movimiento, además del consumo basal en reposo. Es una medida directa de lo físicamente activo que fue tu día.",
"workoutsTitle": "Entrenamientos",
"workoutsBody": "Los entrenamientos son las sesiones de ejercicio estructurado que registran tus dispositivos, con tipo, duración y energía. Registrarlos muestra cómo el entrenamiento regular se acumula a lo largo de las semanas y cómo se relaciona con tus otras señales de salud.",
"respiratoryRateTitle": "Frecuencia respiratoria",
"respiratoryRateBody": "La frecuencia respiratoria es el número de respiraciones que haces por minuto. En reposo, la mayoría de los adultos respiran entre doce y veinte veces por minuto; un aumento sostenido puede acompañar a una enfermedad, el esfuerzo o el estrés.",
"bodyWaterTitle": "Agua corporal total",
"bodyWaterBody": "El agua corporal total es la parte de tu peso compuesta por líquido, dentro y alrededor de las células. Varía con la hidratación, la comida y la actividad, así que la tendencia a lo largo de semanas dice más que una sola medición.",
"boneMassTitle": "Masa ósea",
"boneMassBody": "La masa ósea es el peso estimado del mineral de tu esqueleto. Las estimaciones de la báscula son aproximadas, pero una tendencia estable o al alza favorece la fortaleza ósea a largo plazo.",
"fatFreeMassTitle": "Masa libre de grasa",
"fatFreeMassBody": "La masa libre de grasa es todo lo que en tu cuerpo no es grasa: músculo, hueso, órganos y agua. Mantenerla o aumentarla mientras pierdes peso suele indicar una composición corporal más sana.",
"fatMassTitle": "Masa grasa",
"fatMassBody": "La masa grasa es el peso total de la grasa de tu cuerpo. Algo de grasa es esencial para las hormonas y la reserva de energía, pero un exceso —sobre todo en el abdomen— eleva el riesgo para la salud a largo plazo.",
"muscleMassTitle": "Masa muscular",
"muscleMassBody": "La masa muscular es el peso estimado del músculo de tu cuerpo. Más músculo favorece la fuerza, el metabolismo y la movilidad, y suele requerir esfuerzo activo para conservarse con la edad.",
"visceralFatTitle": "Grasa visceral",
"visceralFatBody": "La grasa visceral es la grasa almacenada en lo profundo del abdomen, alrededor de los órganos. A diferencia de la grasa bajo la piel, un nivel alto se asocia estrechamente con enfermedad cardíaca y diabetes tipo 2, por lo que cuanto más baja, mejor.",
"leanBodyMassTitle": "Masa magra corporal",
"leanBodyMassBody": "La masa magra corporal es tu peso total menos la grasa: músculo, hueso, órganos y agua en conjunto. Seguirla junto al peso muestra si los cambios vienen del músculo o de la grasa.",
"flightsClimbedTitle": "Pisos subidos",
"flightsClimbedBody": "Los pisos subidos cuentan las plantas que subes cada día, con un piso equivalente a unos tres metros de altura. Es un indicador sencillo de la actividad cotidiana y el esfuerzo del tren inferior.",
"walkingDistanceTitle": "Distancia a pie y corriendo",
"walkingDistanceBody": "La distancia a pie y corriendo es el terreno que recorres caminando cada día. Complementa el recuento de pasos al reflejar cuánto te moviste, no solo con qué frecuencia diste pasos.",
"walkingSteadinessTitle": "Estabilidad al caminar",
"walkingSteadinessBody": "La estabilidad al caminar estima cuán estable y equilibrada es tu marcha, clasificada de correcta a baja. Un nivel bajo indica mayor probabilidad de caída y conviene comentarlo con un profesional.",
"walkingHeartRateTitle": "Frecuencia cardíaca al caminar",
"walkingHeartRateBody": "La frecuencia cardíaca al caminar es tu pulso medio durante una caminata constante. Un valor más bajo con el tiempo suele reflejar una mejor forma cardiovascular para el mismo esfuerzo.",
"walkingAsymmetryTitle": "Asimetría al caminar",
"walkingAsymmetryBody": "La asimetría al caminar es la proporción de tiempo en que tus pasos son desiguales entre la pierna izquierda y la derecha. Un porcentaje más alto puede indicar dolor, lesión o un problema de marcha que conviene revisar.",
"doubleSupportTimeTitle": "Tiempo de doble apoyo",
"doubleSupportTimeBody": "El tiempo de doble apoyo es la proporción de cada ciclo de marcha en que ambos pies tocan el suelo a la vez. Un porcentaje más alto suele indicar una marcha más cautelosa y menos estable.",
"stepLengthTitle": "Longitud de zancada",
"stepLengthBody": "La longitud de zancada es la distancia media de una pisada a la siguiente. Una zancada más corta con el tiempo puede reflejar fatiga, cautela o un cambio en la movilidad.",
"walkingSpeedTitle": "Velocidad al caminar",
"walkingSpeedBody": "La velocidad al caminar es lo rápido que te mueves en terreno llano. Es un marcador bien estudiado de la salud general y la movilidad, y un ritmo estable o al alza es buena señal.",
"pulseWaveVelocityTitle": "Velocidad de la onda de pulso",
"pulseWaveVelocityBody": "La velocidad de la onda de pulso mide la rapidez con que la onda de presión de cada latido viaja por tus arterias. Una onda más rápida indica arterias más rígidas, lo que se asocia a mayor riesgo cardiovascular.",
"vascularAgeTitle": "Edad vascular",
"vascularAgeBody": "La edad vascular estima qué edad aparentan tus arterias en comparación con tu edad real, según la rigidez arterial. Una edad vascular por debajo de la real sugiere vasos sanguíneos más sanos.",
"environmentalAudioTitle": "Niveles de sonido ambiental",
"environmentalAudioBody": "Los niveles de sonido ambiental registran el volumen del entorno en decibelios. La exposición prolongada por encima de unos 70 dB puede dañar la audición con el tiempo, así que los promedios diarios más bajos son más seguros.",
"headphoneAudioTitle": "Niveles de audio con auriculares",
"headphoneAudioBody": "Los niveles de audio con auriculares registran en decibelios el volumen al que escuchas con auriculares. Bajar el volumen y hacer pausas protege tu audición a largo plazo.",
"audioEventsTitle": "Eventos de sonido fuerte",
"audioEventsBody": "Los eventos de sonido fuerte señalan momentos en que el ruido a tu alrededor alcanzó un nivel que puede dañar la audición con suficiente exposición. Los eventos frecuentes son una señal para buscar un entorno más silencioso o protección auditiva.",
"daylightTitle": "Tiempo a la luz del día",
"daylightBody": "El tiempo a la luz del día es cuánto pasas bajo luz exterior cada día. La luz diurna regular favorece un ritmo sueño-vigilia y un estado de ánimo saludables, y el tiempo al aire libre se asocia con la salud ocular.",
"bloodGlucoseTitle": "Glucosa en sangre",
"bloodGlucoseBody": "La glucosa en sangre es la cantidad de azúcar en tu sangre, la principal fuente de energía del cuerpo. Sube tras comer y se estabiliza entre comidas; valores que se mantienen altos con el tiempo pueden indicar diabetes o prediabetes.",
"skinTemperatureTitle": "Temperatura de la piel",
"skinTemperatureBody": "La temperatura de la piel aquí es el pequeño cambio nocturno de la temperatura de tu muñeca respecto a tu propio valor de referencia, no una medición absoluta de fiebre. Las variaciones pueden seguir el sueño, el entorno, una enfermedad o la fase del ciclo menstrual."
}
},
"sleep": {
"title": "Sueño",
+89 -2
View File
@@ -549,6 +549,8 @@
"dayStreak": "jours de série",
"taken": "Pris",
"skipped": "Sauté",
"intakeToastTaken": "{name} enregistré comme pris",
"intakeToastSkipped": "{name} sauté",
"weekdaySunday": "Dimanche",
"weekdayMonday": "Lundi",
"weekdayTuesday": "Mardi",
@@ -1005,9 +1007,10 @@
"phaseSaved": "Phases de rappel enregistrées",
"phaseReset": "Réinitialisées par défaut",
"sourceWeb": "Web",
"sourceApi": "API",
"sourceApi": "App iOS",
"sourceReminder": "Rappel",
"sourceImport": "Import",
"intakeSourceVia": "via {origin}",
"intakeHistoryEmptyTitle": "Aucune prise pour l’instant",
"intakeHistoryEmptyDescription": "Dès que tu enregistreras une prise, elle apparaîtra ici avec l’heure et la source.",
"intakeHistoryEmptyAction": "Enregistrer une prise",
@@ -1376,6 +1379,7 @@
},
"insights": {
"noAnalysisYet": "Pas encore d’analyse.",
"assessmentPreparing": "Préparation de votre évaluation…",
"emptyTitle": "Pas encore assez de données",
"emptyDescription": "Les insights apparaissent dès que tu auras saisi quelques mesures. Commence par le poids ou la tension.",
"emptyAddMeasurement": "Saisir une mesure",
@@ -1800,7 +1804,90 @@
"medikamenteEmptyDescription": "Les insights d’observance ont besoin d’au moins un médicament enregistré.",
"medikamenteEmptyAction": "Ouvrir les médicaments",
"therapyTimelineDescription": "Journal chronologique de la thérapie GLP-1 — changements de dose, injections, stock, effets secondaires.",
"bmiDescription": "IMC dérivé de ton poids et de ta taille, avec évaluation."
"bmiDescription": "IMC dérivé de ton poids et de ta taille, avec évaluation.",
"target": {
"range": "Cible : {min}–{max} {unit}",
"bpRange": "Cible : {sysMin}–{sysMax} / {diaMin}–{diaMax} {unit}",
"inTargetShare": "{pct}% des jours enregistrés dans la cible",
"adjustLink": "Ajuster la plage cible"
},
"explainer": {
"trigger": "Qu'est-ce que {title} ?",
"bloodPressureTitle": "Tension artérielle",
"bloodPressureBody": "La tension artérielle est la force exercée par le sang sur les parois des artères, exprimée en systolique sur diastolique (le pic lors d'un battement sur la valeur de repos entre les battements). Des valeurs durablement élevées sollicitent le cœur et les vaisseaux à la longue.",
"pulseTitle": "Pouls",
"pulseBody": "Le pouls correspond au nombre de battements du cœur par minute. Une mesure ponctuelle reflète ce que vous faisiez à l'instant : au repos, il est généralement de 60 à 100 battements par minute et augmente naturellement avec le mouvement, le stress ou la caféine.",
"weightTitle": "Poids",
"weightBody": "Le poids corporel est l'un des signaux les plus simples de l'équilibre énergétique à long terme et de la santé globale. La tendance sur plusieurs semaines compte bien plus qu'une mesure isolée, qui varie avec l'hydratation, l'alimentation et l'heure de la journée.",
"bmiTitle": "Indice de masse corporelle (IMC)",
"bmiBody": "L'IMC correspond à votre poids divisé par votre taille au carré, un seul chiffre qui vous situe dans une large catégorie de poids. C'est un dépistage de population, pas un diagnostic, et il ne distingue pas le muscle de la graisse.",
"sleepTitle": "Sommeil",
"sleepBody": "La durée du sommeil est le temps réellement dormi au cours de la nuit, réparti entre sommeil léger, profond et paradoxal. La plupart des adultes ont besoin d'environ sept à neuf heures ; une quantité et une qualité régulières soutiennent la récupération, l'humeur et le métabolisme.",
"moodTitle": "Humeur",
"moodBody": "Le suivi de l'humeur consigne ce que vous ressentez au fil du temps sur une échelle simple. Le noter régulièrement révèle des tendances — comment le sommeil, l'activité ou les médicaments s'alignent sur votre ressenti — qu'une seule journée ne montre jamais.",
"medicationsTitle": "Observance du traitement",
"medicationsBody": "L'observance mesure la fiabilité avec laquelle vous prenez votre traitement comme prescrit, ici sous forme de la part des doses attendues que vous avez enregistrées. Une prise régulière est souvent ce qui permet à un traitement d'agir comme prévu.",
"restingHrTitle": "Fréquence cardiaque au repos",
"restingHrBody": "La fréquence cardiaque au repos est votre rythme cardiaque lorsque vous êtes totalement au repos, généralement mesuré la nuit. Une fréquence plus basse indique souvent une meilleure forme cardiovasculaire, et une tendance à la hausse peut être un signe précoce de stress ou de maladie.",
"hrvTitle": "Variabilité de la fréquence cardiaque (VFC)",
"hrvBody": "La VFC est la petite variation du temps entre des battements consécutifs. Une variabilité plus élevée reflète généralement un système nerveux bien récupéré et adaptable, tandis qu'une baisse durable peut signaler de la fatigue, du stress ou une récupération insuffisante.",
"oxygenSaturationTitle": "Saturation en oxygène (SpO₂)",
"oxygenSaturationBody": "La SpO₂ est le pourcentage de globules rouges transportant de l'oxygène. Des valeurs de 95 à 100 % sont normales au repos ; des valeurs qui restent sous 90 % méritent attention, bien que de brèves baisses nocturnes soient fréquentes.",
"bodyTemperatureTitle": "Température corporelle",
"bodyTemperatureBody": "La température corporelle reflète votre état thermique central, normalement autour de 37 °C avec de petites variations quotidiennes. Une hausse durable peut indiquer une infection, tandis que les mesures nocturnes au poignet suivent surtout des variations relatives plutôt qu'une valeur clinique.",
"activeEnergyTitle": "Énergie active",
"activeEnergyBody": "L'énergie active correspond aux calories que vous brûlez par le mouvement, en plus de la dépense de base au repos. C'est une mesure directe du niveau d'activité physique de votre journée.",
"workoutsTitle": "Entraînements",
"workoutsBody": "Les entraînements sont les séances d'exercice structurées que vos appareils enregistrent, avec le type, la durée et l'énergie. Les suivre montre comment un entraînement régulier s'accumule au fil des semaines et comment il se relie à vos autres signaux de santé.",
"respiratoryRateTitle": "Fréquence respiratoire",
"respiratoryRateBody": "La fréquence respiratoire est le nombre de respirations que vous prenez par minute. Au repos, la plupart des adultes respirent environ douze à vingt fois par minute ; une hausse durable peut accompagner une maladie, un effort ou du stress.",
"bodyWaterTitle": "Eau corporelle totale",
"bodyWaterBody": "L'eau corporelle totale est la part de votre poids constituée de liquide, à l'intérieur et autour des cellules. Elle varie avec l'hydratation, l'alimentation et l'activité, si bien que la tendance sur plusieurs semaines en dit plus qu'une seule mesure.",
"boneMassTitle": "Masse osseuse",
"boneMassBody": "La masse osseuse est le poids estimé des minéraux de votre squelette. Les estimations sur balance sont approximatives, mais une tendance stable ou en hausse soutient la solidité osseuse à long terme.",
"fatFreeMassTitle": "Masse non grasse",
"fatFreeMassBody": "La masse non grasse est tout ce qui, dans votre corps, n'est pas de la graisse : muscle, os, organes et eau. La maintenir ou la développer tout en perdant du poids signale en général une composition corporelle plus saine.",
"fatMassTitle": "Masse grasse",
"fatMassBody": "La masse grasse est le poids total de la graisse de votre corps. Une part de graisse est indispensable aux hormones et au stockage d'énergie, mais un excès — surtout au niveau de l'abdomen — augmente le risque pour la santé à long terme.",
"muscleMassTitle": "Masse musculaire",
"muscleMassBody": "La masse musculaire est le poids estimé des muscles de votre corps. Plus de muscle soutient la force, le métabolisme et la mobilité, et demande généralement un effort actif pour être préservé avec l'âge.",
"visceralFatTitle": "Graisse viscérale",
"visceralFatBody": "La graisse viscérale est la graisse stockée au plus profond de l'abdomen, autour des organes. Contrairement à la graisse sous la peau, un niveau élevé est étroitement lié aux maladies cardiaques et au diabète de type 2 : plus elle est basse, mieux c'est.",
"leanBodyMassTitle": "Masse maigre",
"leanBodyMassBody": "La masse maigre est votre poids total moins la graisse corporelle : muscle, os, organes et eau réunis. La suivre en parallèle du poids montre si les variations viennent du muscle ou de la graisse.",
"flightsClimbedTitle": "Étages montés",
"flightsClimbedBody": "Les étages montés comptent les niveaux que vous gravissez chaque jour, un étage correspondant à environ trois mètres de dénivelé. C'est un indicateur simple de l'activité du quotidien et de l'effort des jambes.",
"walkingDistanceTitle": "Distance à pied et en course",
"walkingDistanceBody": "La distance à pied et en course est le trajet que vous parcourez à pied chaque jour. Elle complète le nombre de pas en reflétant la distance parcourue, pas seulement la fréquence des pas.",
"walkingSteadinessTitle": "Stabilité de la marche",
"walkingSteadinessBody": "La stabilité de la marche estime à quel point votre démarche est stable et équilibrée, classée d'acceptable à faible. Un niveau bas indique un risque de chute plus élevé et mérite d'être évoqué avec un professionnel de santé.",
"walkingHeartRateTitle": "Fréquence cardiaque à la marche",
"walkingHeartRateBody": "La fréquence cardiaque à la marche est votre pouls moyen lors d'une marche régulière. Une valeur plus basse au fil du temps reflète souvent une meilleure forme cardiovasculaire pour le même effort.",
"walkingAsymmetryTitle": "Asymétrie de la marche",
"walkingAsymmetryBody": "L'asymétrie de la marche est la part du temps où vos pas sont inégaux entre la jambe gauche et la droite. Un pourcentage plus élevé peut signaler une douleur, une blessure ou un trouble de la marche à examiner.",
"doubleSupportTimeTitle": "Temps de double appui",
"doubleSupportTimeBody": "Le temps de double appui est la part de chaque cycle de marche où les deux pieds touchent le sol en même temps. Un pourcentage plus élevé traduit en général une démarche plus prudente et moins stable.",
"stepLengthTitle": "Longueur de pas",
"stepLengthBody": "La longueur de pas est la distance moyenne d'une foulée à la suivante. Un pas plus court au fil du temps peut traduire de la fatigue, de la prudence ou un changement de mobilité.",
"walkingSpeedTitle": "Vitesse de marche",
"walkingSpeedBody": "La vitesse de marche est la rapidité de votre déplacement sur terrain plat. C'est un marqueur bien étudié de la santé générale et de la mobilité, et une allure stable ou en hausse est bon signe.",
"pulseWaveVelocityTitle": "Vitesse de l'onde de pouls",
"pulseWaveVelocityBody": "La vitesse de l'onde de pouls mesure la rapidité avec laquelle l'onde de pression de chaque battement parcourt vos artères. Une onde plus rapide indique des artères plus rigides, liées à un risque cardiovasculaire accru.",
"vascularAgeTitle": "Âge vasculaire",
"vascularAgeBody": "L'âge vasculaire estime, d'après la rigidité artérielle, l'âge apparent de vos artères par rapport à votre âge réel. Un âge vasculaire inférieur à votre âge réel suggère des vaisseaux sanguins en meilleure santé.",
"environmentalAudioTitle": "Niveaux sonores ambiants",
"environmentalAudioBody": "Les niveaux sonores ambiants suivent le volume de votre environnement en décibels. Une exposition prolongée au-delà d'environ 70 dB peut endommager l'audition avec le temps : des moyennes journalières plus basses sont plus sûres.",
"headphoneAudioTitle": "Niveaux audio au casque",
"headphoneAudioBody": "Les niveaux audio au casque suivent, en décibels, le volume auquel vous écoutez avec des écouteurs ou un casque. Baisser le volume et faire des pauses protège votre audition sur le long terme.",
"audioEventsTitle": "Événements sonores forts",
"audioEventsBody": "Les événements sonores forts signalent les moments où le bruit autour de vous a atteint un niveau pouvant nuire à l'audition en cas d'exposition suffisante. Des événements fréquents invitent à rechercher un environnement plus calme ou une protection auditive.",
"daylightTitle": "Temps à la lumière du jour",
"daylightBody": "Le temps à la lumière du jour correspond à la durée passée en lumière extérieure chaque jour. Une lumière naturelle régulière soutient un rythme veille-sommeil et une humeur sains, et le temps passé dehors est lié à la santé oculaire.",
"bloodGlucoseTitle": "Glycémie",
"bloodGlucoseBody": "La glycémie est la quantité de sucre dans votre sang, principale source d'énergie de l'organisme. Elle augmente après les repas et se stabilise entre eux ; des valeurs durablement élevées peuvent signaler un diabète ou un prédiabète.",
"skinTemperatureTitle": "Température cutanée",
"skinTemperatureBody": "La température cutanée correspond ici à la petite variation nocturne de la température de votre poignet par rapport à votre propre référence, et non à une mesure absolue de fièvre. Les variations peuvent suivre le sommeil, l'environnement, une maladie ou la phase du cycle menstruel."
}
},
"sleep": {
"title": "Sommeil",
+89 -2
View File
@@ -549,6 +549,8 @@
"dayStreak": "giorni di serie",
"taken": "Assunta",
"skipped": "Saltata",
"intakeToastTaken": "{name} registrata come assunta",
"intakeToastSkipped": "{name} saltata",
"weekdaySunday": "Domenica",
"weekdayMonday": "Lunedì",
"weekdayTuesday": "Martedì",
@@ -1005,9 +1007,10 @@
"phaseSaved": "Fasi di promemoria salvate",
"phaseReset": "Ripristinate ai valori predefiniti",
"sourceWeb": "Web",
"sourceApi": "API",
"sourceApi": "App iOS",
"sourceReminder": "Promemoria",
"sourceImport": "Importazione",
"intakeSourceVia": "tramite {origin}",
"intakeHistoryEmptyTitle": "Ancora nessuna assunzione",
"intakeHistoryEmptyDescription": "Appena registrerai un’assunzione, comparirà qui con orario e sorgente.",
"intakeHistoryEmptyAction": "Registra un’assunzione",
@@ -1376,6 +1379,7 @@
},
"insights": {
"noAnalysisYet": "Ancora nessuna analisi.",
"assessmentPreparing": "Preparazione della valutazione…",
"emptyTitle": "Dati ancora insufficienti",
"emptyDescription": "Gli insights compaiono appena registri qualche misurazione. Inizia da peso o pressione.",
"emptyAddMeasurement": "Registra misurazione",
@@ -1800,7 +1804,90 @@
"medikamenteEmptyDescription": "Gli insights di aderenza richiedono almeno un farmaco registrato.",
"medikamenteEmptyAction": "Apri farmaci",
"therapyTimelineDescription": "Protocollo cronologico della terapia GLP-1 — cambi di dose, iniezioni, scorte, effetti collaterali.",
"bmiDescription": "BMI derivato dal tuo peso e dalla tua altezza, con valutazione."
"bmiDescription": "BMI derivato dal tuo peso e dalla tua altezza, con valutazione.",
"target": {
"range": "Obiettivo: {min}–{max} {unit}",
"bpRange": "Obiettivo: {sysMin}–{sysMax} / {diaMin}–{diaMax} {unit}",
"inTargetShare": "{pct}% dei giorni registrati nell'obiettivo",
"adjustLink": "Modifica l'intervallo obiettivo"
},
"explainer": {
"trigger": "Che cos'è {title}?",
"bloodPressureTitle": "Pressione arteriosa",
"bloodPressureBody": "La pressione arteriosa è la forza che il sangue esercita sulle pareti delle arterie, indicata come sistolica su diastolica (il picco durante un battito sul valore a riposo tra i battiti). Valori costantemente alti affaticano il cuore e i vasi nel tempo.",
"pulseTitle": "Polso",
"pulseBody": "Il polso indica quante volte il cuore batte al minuto. Una misurazione singola riflette ciò che stavi facendo in quel momento: a riposo è di solito tra 60 e 100 battiti al minuto e aumenta naturalmente con il movimento, lo stress o la caffeina.",
"weightTitle": "Peso",
"weightBody": "Il peso corporeo è uno dei segnali più semplici dell'equilibrio energetico a lungo termine e della salute generale. L'andamento nelle settimane conta molto più di una singola misurazione, che varia con l'idratazione, il cibo e l'ora del giorno.",
"bmiTitle": "Indice di massa corporea (IMC)",
"bmiBody": "L'IMC è il peso diviso per l'altezza al quadrato, un singolo numero che ti colloca in un'ampia categoria di peso. È uno screening di popolazione, non una diagnosi, e non distingue il muscolo dal grasso.",
"sleepTitle": "Sonno",
"sleepBody": "La durata del sonno è quanto hai effettivamente dormito nella notte, suddivisa in fasi leggera, profonda e REM. La maggior parte degli adulti necessita di circa sette-nove ore; quantità e qualità costanti favoriscono recupero, umore e metabolismo.",
"moodTitle": "Umore",
"moodBody": "Il monitoraggio dell'umore registra come ti senti nel tempo su una scala semplice. Annotarlo con regolarità rivela schemi — come sonno, attività o farmaci si allineano a come ti senti — che un singolo giorno non mostra mai.",
"medicationsTitle": "Aderenza alla terapia",
"medicationsBody": "L'aderenza misura quanto regolarmente assumi i farmaci come prescritto, qui come quota delle dosi previste che hai registrato. Un'assunzione costante è spesso ciò che fa funzionare una terapia come previsto.",
"restingHrTitle": "Frequenza cardiaca a riposo",
"restingHrBody": "La frequenza cardiaca a riposo è il battito quando sei completamente a riposo, di solito misurato durante la notte. Una frequenza più bassa indica in genere una migliore forma cardiovascolare, mentre un andamento in aumento può essere un segnale precoce di stress o malattia.",
"hrvTitle": "Variabilità della frequenza cardiaca (HRV)",
"hrvBody": "L'HRV è la piccola variazione del tempo tra battiti consecutivi. Una variabilità più alta riflette di solito un sistema nervoso ben recuperato e adattabile, mentre un calo prolungato può segnalare affaticamento, stress o recupero insufficiente.",
"oxygenSaturationTitle": "Saturazione di ossigeno (SpO₂)",
"oxygenSaturationBody": "La SpO₂ è la percentuale di globuli rossi che trasportano ossigeno. Valori tra 95 e 100% sono normali a riposo; valori che restano sotto il 90% meritano attenzione, anche se brevi cali notturni sono comuni.",
"bodyTemperatureTitle": "Temperatura corporea",
"bodyTemperatureBody": "La temperatura corporea riflette il tuo stato termico centrale, normalmente intorno ai 37 °C con piccole oscillazioni giornaliere. Un aumento prolungato può indicare un'infezione, mentre le misurazioni notturne al polso seguono soprattutto variazioni relative, non un valore clinico.",
"activeEnergyTitle": "Energia attiva",
"activeEnergyBody": "L'energia attiva sono le calorie che bruci con il movimento, oltre al consumo di base a riposo. È una misura diretta di quanto è stata fisicamente attiva la tua giornata.",
"workoutsTitle": "Allenamenti",
"workoutsBody": "Gli allenamenti sono le sessioni di esercizio strutturato che i tuoi dispositivi registrano, con tipo, durata ed energia. Tracciarli mostra come l'allenamento regolare si accumula nel corso delle settimane e come si collega agli altri segnali di salute.",
"respiratoryRateTitle": "Frequenza respiratoria",
"respiratoryRateBody": "La frequenza respiratoria è il numero di respiri che fai al minuto. A riposo la maggior parte degli adulti respira circa dodici-venti volte al minuto; un aumento prolungato può accompagnare malattia, sforzo o stress.",
"bodyWaterTitle": "Acqua corporea totale",
"bodyWaterBody": "L'acqua corporea totale è la quota del tuo peso costituita da liquido, dentro e intorno alle cellule. Varia con l'idratazione, l'alimentazione e l'attività, quindi l'andamento nelle settimane dice più di una singola misura.",
"boneMassTitle": "Massa ossea",
"boneMassBody": "La massa ossea è il peso stimato dei minerali del tuo scheletro. Le stime da bilancia sono approssimative, ma un andamento stabile o in aumento sostiene la robustezza ossea a lungo termine.",
"fatFreeMassTitle": "Massa magra",
"fatFreeMassBody": "La massa magra è tutto ciò che nel corpo non è grasso: muscoli, ossa, organi e acqua. Mantenerla o aumentarla mentre si perde peso indica di solito una composizione corporea più sana.",
"fatMassTitle": "Massa grassa",
"fatMassBody": "La massa grassa è il peso totale del grasso nel corpo. Un po' di grasso è essenziale per gli ormoni e le riserve di energia, ma un eccesso — soprattutto sull'addome — aumenta il rischio per la salute a lungo termine.",
"muscleMassTitle": "Massa muscolare",
"muscleMassBody": "La massa muscolare è il peso stimato dei muscoli del corpo. Più muscolo sostiene forza, metabolismo e mobilità, e di solito richiede impegno attivo per essere mantenuto con l'età.",
"visceralFatTitle": "Grasso viscerale",
"visceralFatBody": "Il grasso viscerale è il grasso depositato in profondità nell'addome, intorno agli organi. A differenza del grasso sottocutaneo, un livello elevato è strettamente legato a malattie cardiache e diabete di tipo 2, quindi più basso è in genere meglio.",
"leanBodyMassTitle": "Massa magra corporea",
"leanBodyMassBody": "La massa magra corporea è il peso totale meno il grasso: muscoli, ossa, organi e acqua insieme. Seguirla accanto al peso mostra se i cambiamenti derivano dal muscolo o dal grasso.",
"flightsClimbedTitle": "Piani saliti",
"flightsClimbedBody": "I piani saliti contano i livelli che sali ogni giorno, dove un piano corrisponde a circa tre metri di dislivello. È un indicatore semplice dell'attività quotidiana e dello sforzo degli arti inferiori.",
"walkingDistanceTitle": "Distanza a piedi e di corsa",
"walkingDistanceBody": "La distanza a piedi e di corsa è il percorso che copri a piedi ogni giorno. Integra il conteggio dei passi mostrando quanto ti sei mosso, non solo quanto spesso hai mosso il passo.",
"walkingSteadinessTitle": "Stabilità del cammino",
"walkingSteadinessBody": "La stabilità del cammino stima quanto è stabile ed equilibrata la tua andatura, classificata da buona a bassa. Un livello basso indica una maggiore probabilità di caduta ed è opportuno parlarne con un medico.",
"walkingHeartRateTitle": "Frequenza cardiaca in camminata",
"walkingHeartRateBody": "La frequenza cardiaca in camminata è il battito medio durante una camminata costante. Un valore più basso nel tempo riflette spesso una migliore forma cardiovascolare a parità di sforzo.",
"walkingAsymmetryTitle": "Asimmetria del cammino",
"walkingAsymmetryBody": "L'asimmetria del cammino è la quota di tempo in cui i tuoi passi sono diseguali tra gamba sinistra e destra. Una percentuale più alta può indicare dolore, un infortunio o un problema di andatura da approfondire.",
"doubleSupportTimeTitle": "Tempo di doppio appoggio",
"doubleSupportTimeBody": "Il tempo di doppio appoggio è la quota di ogni ciclo del passo in cui entrambi i piedi toccano terra contemporaneamente. Una percentuale più alta indica di solito un'andatura più prudente e meno stabile.",
"stepLengthTitle": "Lunghezza del passo",
"stepLengthBody": "La lunghezza del passo è la distanza media da un appoggio del piede al successivo. Un passo più corto nel tempo può riflettere stanchezza, prudenza o un cambiamento nella mobilità.",
"walkingSpeedTitle": "Velocità del cammino",
"walkingSpeedBody": "La velocità del cammino è quanto rapidamente ti muovi in piano. È un marcatore ben studiato della salute generale e della mobilità, e un ritmo stabile o in aumento è un buon segno.",
"pulseWaveVelocityTitle": "Velocità dell'onda di polso",
"pulseWaveVelocityBody": "La velocità dell'onda di polso misura la rapidità con cui l'onda di pressione di ogni battito percorre le arterie. Un'onda più veloce indica arterie più rigide, associate a un rischio cardiovascolare più alto.",
"vascularAgeTitle": "Età vascolare",
"vascularAgeBody": "L'età vascolare stima quanto si comportano vecchie le tue arterie rispetto alla tua età reale, in base alla rigidità arteriosa. Un'età vascolare inferiore a quella reale suggerisce vasi sanguigni più sani.",
"environmentalAudioTitle": "Livelli sonori ambientali",
"environmentalAudioBody": "I livelli sonori ambientali rilevano il volume dell'ambiente intorno a te in decibel. Un'esposizione prolungata sopra i 70 dB circa può danneggiare l'udito nel tempo, quindi medie giornaliere più basse sono più sicure.",
"headphoneAudioTitle": "Livelli audio in cuffia",
"headphoneAudioBody": "I livelli audio in cuffia rilevano in decibel quanto forte ascolti con auricolari o cuffie. Tenere basso il volume e fare pause protegge l'udito nel lungo periodo.",
"audioEventsTitle": "Eventi sonori intensi",
"audioEventsBody": "Gli eventi sonori intensi segnalano i momenti in cui il rumore intorno a te ha raggiunto un livello che può danneggiare l'udito con esposizione sufficiente. Eventi frequenti sono un invito a cercare un ambiente più silenzioso o protezioni acustiche.",
"daylightTitle": "Tempo alla luce del giorno",
"daylightBody": "Il tempo alla luce del giorno è quanto trascorri sotto la luce esterna ogni giorno. La luce diurna regolare sostiene un sano ritmo sonno-veglia e l'umore, e il tempo all'aperto è collegato alla salute degli occhi.",
"bloodGlucoseTitle": "Glicemia",
"bloodGlucoseBody": "La glicemia è la quantità di zucchero nel sangue, la principale fonte di energia del corpo. Sale dopo i pasti e si stabilizza tra un pasto e l'altro; valori che restano alti nel tempo possono indicare diabete o prediabete.",
"skinTemperatureTitle": "Temperatura cutanea",
"skinTemperatureBody": "La temperatura cutanea qui è la piccola variazione notturna della temperatura del polso rispetto al tuo valore di riferimento, non una misura assoluta della febbre. Le variazioni possono seguire sonno, ambiente, malattia o fase del ciclo mestruale."
}
},
"sleep": {
"title": "Sonno",
+89 -2
View File
@@ -549,6 +549,8 @@
"dayStreak": "dni serii",
"taken": "Przyjęte",
"skipped": "Pominięte",
"intakeToastTaken": "{name} oznaczone jako przyjęte",
"intakeToastSkipped": "{name} pominięte",
"weekdaySunday": "Niedziela",
"weekdayMonday": "Poniedziałek",
"weekdayTuesday": "Wtorek",
@@ -1005,9 +1007,10 @@
"phaseSaved": "Fazy przypomnień zapisane",
"phaseReset": "Przywrócono wartości domyślne",
"sourceWeb": "Web",
"sourceApi": "API",
"sourceApi": "Aplikacja iOS",
"sourceReminder": "Przypomnienie",
"sourceImport": "Import",
"intakeSourceVia": "przez {origin}",
"intakeHistoryEmptyTitle": "Brak przyjęć",
"intakeHistoryEmptyDescription": "Gdy tylko zarejestrujesz przyjęcie, pojawi się tu wraz z godziną i źródłem.",
"intakeHistoryEmptyAction": "Zarejestruj przyjęcie",
@@ -1376,6 +1379,7 @@
},
"insights": {
"noAnalysisYet": "Brak analizy.",
"assessmentPreparing": "Przygotowywanie oceny…",
"emptyTitle": "Jeszcze za mało danych",
"emptyDescription": "Insights pojawią się, gdy zarejestrujesz kilka pomiarów. Zacznij od wagi lub ciśnienia.",
"emptyAddMeasurement": "Zarejestruj pomiar",
@@ -1800,7 +1804,90 @@
"medikamenteEmptyDescription": "Insights przestrzegania wymagają przynajmniej jednego zarejestrowanego leku.",
"medikamenteEmptyAction": "Otwórz leki",
"therapyTimelineDescription": "Chronologiczny protokół terapii GLP-1 — zmiany dawki, iniekcje, stan, działania niepożądane.",
"bmiDescription": "BMI obliczone z twojej wagi i wzrostu, z oceną."
"bmiDescription": "BMI obliczone z twojej wagi i wzrostu, z oceną.",
"target": {
"range": "Cel: {min}–{max} {unit}",
"bpRange": "Cel: {sysMin}–{sysMax} / {diaMin}–{diaMax} {unit}",
"inTargetShare": "{pct}% zarejestrowanych dni w zakresie celu",
"adjustLink": "Dostosuj zakres docelowy"
},
"explainer": {
"trigger": "Czym jest {title}?",
"bloodPressureTitle": "Ciśnienie krwi",
"bloodPressureBody": "Ciśnienie krwi to siła, z jaką krew napiera na ściany tętnic, zapisywana jako skurczowe do rozkurczowego (szczyt podczas uderzenia serca do wartości spoczynkowej między uderzeniami). Stale wysokie wartości z czasem obciążają serce i naczynia.",
"pulseTitle": "Tętno",
"pulseBody": "Tętno to liczba uderzeń serca na minutę. Pojedynczy pomiar odzwierciedla to, co robiłeś w danej chwili — w spoczynku wynosi zwykle 60–100 uderzeń na minutę i naturalnie rośnie przy ruchu, stresie lub kofeinie.",
"weightTitle": "Waga",
"weightBody": "Masa ciała to jeden z najprostszych sygnałów długoterminowego bilansu energetycznego i ogólnego zdrowia. Trend na przestrzeni tygodni liczy się znacznie bardziej niż pojedynczy odczyt, który zmienia się wraz z nawodnieniem, jedzeniem i porą dnia.",
"bmiTitle": "Wskaźnik masy ciała (BMI)",
"bmiBody": "BMI to waga podzielona przez wzrost do kwadratu — jedna liczba przypisująca Cię do szerokiej kategorii wagowej. To badanie przesiewowe dla populacji, a nie diagnoza, i nie odróżnia mięśni od tłuszczu.",
"sleepTitle": "Sen",
"sleepBody": "Długość snu to czas, który faktycznie przespałeś w nocy, podzielony na fazy lekką, głęboką i REM. Większość dorosłych potrzebuje około siedmiu do dziewięciu godzin; stała ilość i jakość wspierają regenerację, nastrój i metabolizm.",
"moodTitle": "Nastrój",
"moodBody": "Śledzenie nastroju rejestruje Twoje samopoczucie w czasie na prostej skali. Regularne zapisywanie ujawnia wzorce — jak sen, aktywność czy leki łączą się z samopoczuciem — których pojedynczy dzień nigdy nie pokaże.",
"medicationsTitle": "Przestrzeganie zaleceń lekowych",
"medicationsBody": "Przestrzeganie zaleceń to rzetelność przyjmowania leków zgodnie z zaleceniami, pokazana tu jako odsetek oczekiwanych dawek, które zarejestrowałeś. Regularne przyjmowanie często decyduje o tym, czy terapia działa zgodnie z zamierzeniem.",
"restingHrTitle": "Tętno spoczynkowe",
"restingHrBody": "Tętno spoczynkowe to częstość uderzeń serca w pełnym spoczynku, zwykle mierzona w nocy. Niższe tętno zwykle wskazuje na lepszą wydolność krążeniową, a rosnący trend może być wczesnym sygnałem stresu lub choroby.",
"hrvTitle": "Zmienność rytmu serca (HRV)",
"hrvBody": "HRV to drobna zmienność czasu między kolejnymi uderzeniami serca. Wyższa zmienność zwykle odzwierciedla dobrze zregenerowany, elastyczny układ nerwowy, a utrzymujący się spadek może sygnalizować zmęczenie, stres lub niewystarczającą regenerację.",
"oxygenSaturationTitle": "Saturacja tlenem (SpO₂)",
"oxygenSaturationBody": "SpO₂ to odsetek czerwonych krwinek przenoszących tlen. Wartości 95–100% są normalne w spoczynku; wartości utrzymujące się poniżej 90% wymagają uwagi, choć krótkie nocne spadki są częste.",
"bodyTemperatureTitle": "Temperatura ciała",
"bodyTemperatureBody": "Temperatura ciała odzwierciedla stan cieplny rdzenia, zwykle około 37 °C z niewielkimi dobowymi wahaniami. Utrzymujący się wzrost może wskazywać na infekcję, podczas gdy nocne pomiary na nadgarstku śledzą głównie zmiany względne, a nie wartość kliniczną.",
"activeEnergyTitle": "Energia aktywna",
"activeEnergyBody": "Energia aktywna to kalorie spalane przez ruch, ponad podstawowy wydatek w spoczynku. To bezpośrednia miara tego, jak aktywny fizycznie był Twój dzień.",
"workoutsTitle": "Treningi",
"workoutsBody": "Treningi to ustrukturyzowane sesje ćwiczeń rejestrowane przez Twoje urządzenia, wraz z typem, czasem trwania i energią. Ich śledzenie pokazuje, jak regularny trening kumuluje się przez tygodnie i jak wiąże się z innymi sygnałami zdrowotnymi.",
"respiratoryRateTitle": "Częstość oddechów",
"respiratoryRateBody": "Częstość oddechów to liczba wdechów na minutę. W spoczynku większość dorosłych oddycha około dwunastu do dwudziestu razy na minutę; utrzymujący się wzrost może towarzyszyć chorobie, wysiłkowi lub stresowi.",
"bodyWaterTitle": "Całkowita woda w organizmie",
"bodyWaterBody": "Całkowita woda w organizmie to udział płynów w masie ciała, wewnątrz i wokół komórek. Zmienia się wraz z nawodnieniem, posiłkami i aktywnością, więc trend w ciągu tygodni mówi więcej niż pojedynczy pomiar.",
"boneMassTitle": "Masa kostna",
"boneMassBody": "Masa kostna to szacowana waga minerałów w szkielecie. Pomiary z wagi są przybliżone, ale stabilny lub rosnący trend sprzyja długotrwałej wytrzymałości kości.",
"fatFreeMassTitle": "Masa beztłuszczowa",
"fatFreeMassBody": "Masa beztłuszczowa to wszystko w ciele, co nie jest tłuszczem — mięśnie, kości, narządy i woda. Utrzymanie lub jej budowanie przy spadku wagi zwykle wskazuje na zdrowszy skład ciała.",
"fatMassTitle": "Masa tłuszczowa",
"fatMassBody": "Masa tłuszczowa to łączna waga tłuszczu w ciele. Pewna ilość tłuszczu jest niezbędna dla hormonów i magazynowania energii, ale jego nadmiar — zwłaszcza w okolicy brzucha — zwiększa długoterminowe ryzyko zdrowotne.",
"muscleMassTitle": "Masa mięśniowa",
"muscleMassBody": "Masa mięśniowa to szacowana waga mięśni w ciele. Więcej mięśni wspiera siłę, metabolizm i sprawność, a ich utrzymanie z wiekiem zwykle wymaga aktywnego wysiłku.",
"visceralFatTitle": "Tłuszcz trzewny",
"visceralFatBody": "Tłuszcz trzewny to tłuszcz gromadzony głęboko w jamie brzusznej wokół narządów. W odróżnieniu od tłuszczu podskórnego jego wysoki poziom jest ściśle powiązany z chorobami serca i cukrzycą typu 2, więc im niżej, tym lepiej.",
"leanBodyMassTitle": "Beztłuszczowa masa ciała",
"leanBodyMassBody": "Beztłuszczowa masa ciała to całkowita waga pomniejszona o tłuszcz — mięśnie, kości, narządy i woda razem. Śledzenie jej obok wagi pokazuje, czy zmiany wynikają z mięśni, czy z tłuszczu.",
"flightsClimbedTitle": "Pokonane piętra",
"flightsClimbedBody": "Pokonane piętra liczą kondygnacje, które pokonujesz w górę każdego dnia, gdzie jedno piętro to około trzech metrów wzniesienia. To prosty wskaźnik codziennej aktywności i wysiłku nóg.",
"walkingDistanceTitle": "Dystans marszu i biegu",
"walkingDistanceBody": "Dystans marszu i biegu to droga, jaką pokonujesz pieszo każdego dnia. Uzupełnia liczbę kroków, pokazując, jak daleko się poruszałeś, a nie tylko jak często stawiałeś kroki.",
"walkingSteadinessTitle": "Stabilność chodu",
"walkingSteadinessBody": "Stabilność chodu szacuje, jak stabilny i zrównoważony jest twój sposób chodzenia, w skali od dobrej do niskiej. Niski poziom wskazuje na większe ryzyko upadku i warto omówić go z lekarzem.",
"walkingHeartRateTitle": "Tętno podczas chodzenia",
"walkingHeartRateBody": "Tętno podczas chodzenia to średni puls w trakcie równego marszu. Niższa wartość w czasie często odzwierciedla poprawę wydolności krążeniowej przy tym samym wysiłku.",
"walkingAsymmetryTitle": "Asymetria chodu",
"walkingAsymmetryBody": "Asymetria chodu to odsetek czasu, w którym kroki są nierówne między lewą a prawą nogą. Wyższy procent może wskazywać na ból, kontuzję lub problem z chodem wart sprawdzenia.",
"doubleSupportTimeTitle": "Czas podwójnego podparcia",
"doubleSupportTimeBody": "Czas podwójnego podparcia to udział każdego cyklu chodu, w którym obie stopy dotykają ziemi jednocześnie. Wyższy procent zwykle oznacza ostrożniejszy, mniej stabilny chód.",
"stepLengthTitle": "Długość kroku",
"stepLengthBody": "Długość kroku to średnia odległość od jednego postawienia stopy do następnego. Krótszy krok w czasie może odzwierciedlać zmęczenie, ostrożność lub zmianę sprawności ruchowej.",
"walkingSpeedTitle": "Prędkość chodu",
"walkingSpeedBody": "Prędkość chodu to tempo poruszania się po płaskim terenie. To dobrze zbadany wskaźnik ogólnego zdrowia i sprawności, a stałe lub rosnące tempo to dobry znak.",
"pulseWaveVelocityTitle": "Prędkość fali tętna",
"pulseWaveVelocityBody": "Prędkość fali tętna mierzy, jak szybko fala ciśnienia z każdego uderzenia serca przemieszcza się przez tętnice. Szybsza fala wskazuje na sztywniejsze tętnice, co wiąże się z wyższym ryzykiem sercowo-naczyniowym.",
"vascularAgeTitle": "Wiek naczyniowy",
"vascularAgeBody": "Wiek naczyniowy szacuje, jak stare zachowują się twoje tętnice w porównaniu z rzeczywistym wiekiem, na podstawie sztywności tętnic. Wiek naczyniowy niższy od rzeczywistego sugeruje zdrowsze naczynia krwionośne.",
"environmentalAudioTitle": "Poziom dźwięku otoczenia",
"environmentalAudioBody": "Poziom dźwięku otoczenia śledzi głośność otoczenia w decybelach. Długotrwała ekspozycja powyżej około 70 dB może z czasem uszkodzić słuch, więc niższe średnie dzienne są bezpieczniejsze.",
"headphoneAudioTitle": "Poziom dźwięku w słuchawkach",
"headphoneAudioBody": "Poziom dźwięku w słuchawkach śledzi w decybelach, jak głośno słuchasz przez słuchawki. Ściszanie głośności i robienie przerw chroni słuch w dłuższej perspektywie.",
"audioEventsTitle": "Zdarzenia głośnego dźwięku",
"audioEventsBody": "Zdarzenia głośnego dźwięku oznaczają momenty, gdy hałas wokół ciebie osiągnął poziom mogący przy wystarczającej ekspozycji uszkodzić słuch. Częste zdarzenia to sygnał, by poszukać cichszego otoczenia lub ochrony słuchu.",
"daylightTitle": "Czas w świetle dziennym",
"daylightBody": "Czas w świetle dziennym to ilość czasu spędzanego w świetle na zewnątrz każdego dnia. Regularne światło dzienne wspiera zdrowy rytm snu i czuwania oraz nastrój, a czas na świeżym powietrzu wiąże się ze zdrowiem oczu.",
"bloodGlucoseTitle": "Poziom glukozy we krwi",
"bloodGlucoseBody": "Poziom glukozy we krwi to ilość cukru we krwi, głównego źródła energii organizmu. Rośnie po jedzeniu i ustala się między posiłkami; wartości utrzymujące się wysoko mogą sygnalizować cukrzycę lub stan przedcukrzycowy.",
"skinTemperatureTitle": "Temperatura skóry",
"skinTemperatureBody": "Temperatura skóry to tutaj niewielka nocna zmiana temperatury nadgarstka względem twojej własnej wartości bazowej, a nie bezwzględny pomiar gorączki. Zmiany mogą odzwierciedlać sen, otoczenie, chorobę lub fazę cyklu menstruacyjnego."
}
},
"sleep": {
"title": "Sen",
+59
View File
@@ -53,6 +53,65 @@ const nextConfig: NextConfig = {
// from memory instead of paying a full reload. See
// `src/lib/http/cache-headers.ts` for the typed constant reused by
// route handlers that opt into the same posture.
// v1.8.0 — the routed Insights sub-pages migrated from German to
// English slugs (`/insights/blutdruck` → `/insights/blood-pressure`,
// …). Every legacy German URL 301-redirects to its English target so
// bookmarks, the PWA's cached navigation, and any external link keep
// resolving. The redirect set is exhaustive and matches the rename
// table in `docs/adr/0001-insights-naming-convention.md`; the slug
// registry itself lives in `src/lib/insights/sub-page-metric.ts`.
// `bmi`, `hrv`, and `workouts` were already English and need no entry.
async redirects() {
const insightsSlugRenames: Array<[string, string]> = [
["blutdruck", "blood-pressure"],
["puls", "pulse"],
["sauerstoff", "oxygen"],
["koerpertemperatur", "body-temperature"],
["atemfrequenz", "respiratory-rate"],
["gewicht", "weight"],
["koerperwasser", "body-water"],
["knochenmasse", "bone-mass"],
["fettfreie-masse", "fat-free-mass"],
["fettmasse", "fat-mass"],
["muskelmasse", "muscle-mass"],
["viszeralfett", "visceral-fat"],
["magermasse", "lean-body-mass"],
["aktive-energie", "active-energy"],
["stockwerke", "flights-climbed"],
["gehstrecke", "walking-distance"],
["gangstabilitaet", "walking-steadiness"],
["gehpuls", "walking-heart-rate"],
["gangasymmetrie", "walking-asymmetry"],
["doppelstandphase", "double-support-time"],
["schrittlaenge", "step-length"],
["gehgeschwindigkeit", "walking-speed"],
["schlaf", "sleep"],
["ruhepuls", "resting-pulse"],
["pulswellengeschwindigkeit", "pulse-wave-velocity"],
["gefaessalter", "vascular-age"],
["laermbelastung", "environmental-audio"],
["kopfhoererpegel", "headphone-audio"],
["laermereignisse", "audio-events"],
["tageslicht", "daylight"],
["blutzucker", "blood-glucose"],
["hauttemperatur", "skin-temperature"],
["stimmung", "mood"],
["medikamente", "medications"],
];
return insightsSlugRenames.flatMap(([from, to]) => [
{
source: `/insights/${from}`,
destination: `/insights/${to}`,
permanent: true,
},
// Preserve any nested path (e.g. a future `/insights/sleep/2026-05-31`).
{
source: `/insights/${from}/:path*`,
destination: `/insights/${to}/:path*`,
permanent: true,
},
]);
},
async headers() {
return [
{
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "healthlog",
"version": "1.7.2",
"version": "1.8.4",
"description": "Self-hosted personal-health-tracking PWA with Withings integration, AI insights, and doctor-report PDF export.",
"license": "AGPL-3.0-only",
"homepage": "https://healthlog.dev",
@@ -0,0 +1,20 @@
-- 0098_app_settings_global_toggles_drift_fix
-- Four `app_settings` columns have been on `prisma/schema.prisma` since the
-- per-channel global notification toggles + admin default-locale work but
-- never landed in the migration history (applied via `prisma db push` to
-- existing environments but not committed as a migration). The drift is
-- invisible on a database kept in sync via `db push`, but a database built
-- from migrations alone is missing the columns — and the admin settings
-- read path (`/api/admin/settings`) selects `default_locale`, so a fresh
-- deploy reports `column "default_locale" does not exist` on first read.
--
-- Same class of drift as 0025_user_locale_drift_fix. Each add uses
-- `IF NOT EXISTS` with the schema default, so the migration is a safe no-op
-- against any environment already carrying the columns and a clean add
-- against one built strictly from this migrations directory (CI test
-- containers, fresh deploys, demo seeds).
ALTER TABLE "app_settings"
ADD COLUMN IF NOT EXISTS "default_locale" TEXT NOT NULL DEFAULT 'de',
ADD COLUMN IF NOT EXISTS "telegram_global" BOOLEAN NOT NULL DEFAULT true,
ADD COLUMN IF NOT EXISTS "ntfy_global" BOOLEAN NOT NULL DEFAULT true,
ADD COLUMN IF NOT EXISTS "web_push_global" BOOLEAN NOT NULL DEFAULT true;
+12 -12
View File
@@ -247,14 +247,14 @@ async function seed() {
const takenTime = new Date(date);
takenTime.setHours(8, Math.floor(Math.random() * 45), 0);
await client.query(
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at)
VALUES ($1, $2, $3, $4, $5, false, 'WEB', $5)`,
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, false, 'WEB', $5, $5)`,
[cuid(), userId, med1Id, date, takenTime],
);
} else {
await client.query(
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at)
VALUES ($1, $2, $3, $4, NULL, true, 'WEB', $4)`,
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at, updated_at)
VALUES ($1, $2, $3, $4, NULL, true, 'WEB', $4, $4)`,
[cuid(), userId, med1Id, date],
);
}
@@ -265,14 +265,14 @@ async function seed() {
const takenTime = new Date(date);
takenTime.setHours(8, Math.floor(5 + Math.random() * 50), 0);
await client.query(
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at)
VALUES ($1, $2, $3, $4, $5, false, 'WEB', $5)`,
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, false, 'WEB', $5, $5)`,
[cuid(), userId, med2Id, date, takenTime],
);
} else {
await client.query(
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at)
VALUES ($1, $2, $3, $4, NULL, true, 'WEB', $4)`,
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at, updated_at)
VALUES ($1, $2, $3, $4, NULL, true, 'WEB', $4, $4)`,
[cuid(), userId, med2Id, date],
);
}
@@ -284,14 +284,14 @@ async function seed() {
const takenTime = new Date(date);
takenTime.setHours(20, Math.floor(Math.random() * 60), 0);
await client.query(
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at)
VALUES ($1, $2, $3, $4, $5, false, 'WEB', $5)`,
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, false, 'WEB', $5, $5)`,
[cuid(), userId, med3Id, date, takenTime],
);
} else {
await client.query(
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at)
VALUES ($1, $2, $3, $4, NULL, true, 'WEB', $4)`,
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at, updated_at)
VALUES ($1, $2, $3, $4, NULL, true, 'WEB', $4, $4)`,
[cuid(), userId, med3Id, date],
);
}
@@ -623,6 +623,68 @@ describe("GET /api/dashboard/summary", () => {
]);
});
it("projects one row per timesOfDay for a twice-daily schedule", async () => {
// A single MedicationSchedule row carrying two first-class
// `timesOfDay` is two distinct dose slots per day. Pre-fix the
// projector minted only the `windowStart` slot, so the second daily
// dose never appeared in the today-tile and the event-count
// compliance rollup read half the expected doses (a 2×/day med
// showed 50%). Assert the backfill mints both slots.
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-05-21T03:00:00.000Z"));
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.medication.findMany).mockResolvedValue([
{
id: "med-twice-daily",
startsOn: null,
endsOn: null,
oneShot: false,
createdAt: new Date("2026-01-01T00:00:00Z"),
schedules: [
{
id: "sched-bid",
medicationId: "med-twice-daily",
windowStart: "07:00",
windowEnd: "07:30",
daysOfWeek: null,
timesOfDay: ["07:00", "19:00"],
reminderGraceMinutes: null,
rrule: null,
rollingIntervalDays: null,
},
],
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.findMany).mockImplementation(((
args: unknown,
) => {
const a = args as { where: { OR?: unknown }; select?: { id?: boolean } };
if (a.where.OR) return Promise.resolve([]) as never;
if (!a.select?.id) return Promise.resolve([]) as never;
return Promise.resolve([]) as never;
}) as never);
vi.mocked(prisma.medicationIntakeEvent.createMany).mockResolvedValue({
count: 2,
} as never);
const res = await callGet(makeReq());
expect(res.status).toBe(200);
expect(prisma.medicationIntakeEvent.createMany).toHaveBeenCalledTimes(1);
const args = vi.mocked(prisma.medicationIntakeEvent.createMany).mock
.calls[0][0] as {
data: Array<{ medicationId: string; scheduledFor: Date }>;
};
expect(args.data).toHaveLength(2);
const hours = args.data
.map((r) => new Date(r.scheduledFor).getUTCHours())
.sort((a, b) => a - b);
// 07:00 and 19:00 in the default zone (Europe/Berlin, UTC+2 in May)
// materialise to 05:00 and 17:00 UTC. The assertion that matters is
// two distinct slots, not one.
expect(hours).toEqual([5, 17]);
vi.useRealTimers();
});
it("is idempotent on a second pass (v1.4.39 W-SERVER-FIX-2)", async () => {
// When the existence probe already sees a row for the projected
// slot (e.g. the intake route or the reminder worker minted it
@@ -9,6 +9,7 @@
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
import { PDFParse } from "pdf-parse";
vi.mock("@/lib/db", () => ({
prisma: {
@@ -38,14 +39,27 @@ const SESSION_OK = {
user: { id: "user-1", email: "test@example.com", role: "USER" },
} as const;
function mkReq(body: unknown): NextRequest {
function mkReq(
body: unknown,
headers: Record<string, string> = {},
): NextRequest {
return new NextRequest("http://localhost/api/export/health-record", {
method: "POST",
headers: { "content-type": "application/json" },
headers: { "content-type": "application/json", ...headers },
body: JSON.stringify(body),
});
}
async function pdfText(res: Response): Promise<string> {
const bytes = new Uint8Array(await res.arrayBuffer());
const parser = new PDFParse({ data: bytes });
try {
return (await parser.getText()).text;
} finally {
await parser.destroy();
}
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
@@ -137,6 +151,46 @@ describe("POST /api/export/health-record — outputs", () => {
expect(buf.subarray(0, 2).toString("latin1")).toBe("PK");
});
it("renders the PDF in the explicit selection locale", async () => {
const { POST } = await import("../route");
const res = await POST(
mkReq({ format: "pdf", locale: "de", practiceName: "Sample Practice" }),
);
const text = await pdfText(res);
// German cover label.
expect(text).toContain("Praxis:");
});
it("falls back to the healthlog-locale cookie when no locale is sent", async () => {
const { POST } = await import("../route");
const res = await POST(
mkReq(
{ format: "pdf", practiceName: "Sample Practice" },
{
// Browser default English, but the in-app cookie says German — the
// cookie must win over Accept-Language.
"accept-language": "en-US,en;q=0.9",
cookie: "healthlog-locale=de",
},
),
);
const text = await pdfText(res);
expect(text).toContain("Praxis:");
expect(text).not.toContain("Practice:");
});
it("uses Accept-Language only when neither selection nor cookie is present", async () => {
const { POST } = await import("../route");
const res = await POST(
mkReq(
{ format: "pdf", practiceName: "Sample Practice" },
{ "accept-language": "en-US,en;q=0.9" },
),
);
const text = await pdfText(res);
expect(text).toContain("Practice:");
});
it("scopes the aggregator measurement read to the session user", async () => {
const { POST } = await import("../route");
await POST(mkReq({ format: "fhir", userId: "user-2" } as never));
+13 -1
View File
@@ -46,7 +46,7 @@ import {
} from "@/lib/validations/health-record-export";
import { getServerTranslator } from "@/lib/i18n/server-translator";
import { parseLocaleFromAcceptLanguage } from "@/lib/format-locale";
import { type Locale } from "@/lib/i18n/config";
import { locales, type Locale } from "@/lib/i18n/config";
import { resolveUserTimezone } from "@/lib/tz/resolver";
export const POST = apiHandler(async (request: NextRequest) => {
@@ -72,8 +72,20 @@ export const POST = apiHandler(async (request: NextRequest) => {
const sections = toDoctorReportPrefs(selection.sections);
const includeCharts = selection.includeCharts ?? true;
// Locale resolution, most-specific first: the explicit selection wins, then
// the in-app `healthlog-locale` cookie (what the user actually chose in the
// UI), and only then the browser's Accept-Language header. The header is the
// weakest signal — a German user on an English-default browser would
// otherwise get an English report.
const cookieValue = request.cookies.get("healthlog-locale")?.value;
const cookieLocale = (locales as readonly string[]).includes(
cookieValue ?? "",
)
? (cookieValue as Locale)
: null;
const locale: Locale =
selection.locale ??
cookieLocale ??
parseLocaleFromAcceptLanguage(
request.headers.get("accept-language") ?? "",
);
@@ -23,9 +23,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
});
const locale = resolveBloodPressureStatusLocale(resolved);
// v1.8.3 — read-only: serve the cache, enqueue generation out of band on
// a miss. The GET never awaits the provider, so opening /insights/<metric>
// can no longer pin the main thread behind a cold LLM round-trip.
const result = await generateBloodPressureStatusForUser(user.id, {
locale,
force: false,
readOnly: true,
});
annotate({ action: { name: "insights.blood-pressure-status" } });
+4
View File
@@ -23,9 +23,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
});
const locale = resolveBmiStatusLocale(resolved);
// v1.8.3 — read-only: serve the cache, enqueue generation out of band on
// a miss. The GET never awaits the provider, so opening /insights/<metric>
// can no longer pin the main thread behind a cold LLM round-trip.
const result = await generateBmiStatusForUser(user.id, {
locale,
force: false,
readOnly: true,
});
annotate({ action: { name: "insights.bmi-status" } });
+1 -1
View File
@@ -4,7 +4,7 @@
* Returns a chronological merge of every GLP-1-relevant event the user
* has logged: dose changes, injections (with site if recorded),
* inventory events, and side-effect-tagged mood entries from the
* trailing 90 days. Used by /insights/medikamente's TherapyTimeline
* trailing 90 days. Used by /insights/medications' TherapyTimeline
* component. Web-only users without a GLP-1 medication get
* `hasGlp1: false` so the component hides cleanly.
*/
@@ -122,7 +122,7 @@ describe("GET /api/insights/layout", () => {
version: 1,
tiles: [
{ id: "overview", visible: false, order: 0 },
{ id: "blutdruck", visible: true, order: 1 },
{ id: "blood-pressure", visible: true, order: 1 },
],
},
} as never);
@@ -141,12 +141,42 @@ describe("GET /api/insights/layout", () => {
order: 0,
});
expect(body.data.tiles[1]).toEqual({
id: "blutdruck",
id: "blood-pressure",
visible: true,
order: 1,
});
expect(body.data.tiles.length).toBe(DEFAULT_INSIGHTS_LAYOUT.tiles.length);
});
it("normalises a legacy German tile id stored by a ≤ v1.7.x client to its canonical English id on read", async () => {
// A layout persisted before the v1.8.0 rename (or by an iOS client
// still speaking the German ids). The resolver must surface the
// canonical English id so the GET contract is current-build clean
// without forcing a re-PUT.
vi.mocked(prisma.user.findUnique).mockResolvedValue({
insightsLayoutJson: {
version: 1,
tiles: [
{ id: "overview", visible: true, order: 0 },
{ id: "blutdruck", visible: true, order: 1 },
{ id: "stimmung", visible: false, order: 2 },
],
},
} as never);
const res = await callGet();
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { tiles: Array<{ id: string; visible: boolean; order: number }> };
};
const ids = body.data.tiles.map((t) => t.id);
// Legacy ids collapse to their English replacement…
expect(ids).toContain("blood-pressure");
expect(ids).toContain("mood");
// …and the German originals never leak back out.
expect(ids).not.toContain("blutdruck");
expect(ids).not.toContain("stimmung");
});
});
describe("PUT /api/insights/layout — happy path", () => {
@@ -157,8 +187,8 @@ describe("PUT /api/insights/layout — happy path", () => {
version: 1,
tiles: [
{ id: "overview", visible: true, order: 0 },
{ id: "blutdruck", visible: true, order: 1 },
{ id: "puls", visible: false, order: 2 },
{ id: "blood-pressure", visible: true, order: 1 },
{ id: "pulse", visible: false, order: 2 },
],
};
const res = await callPut(makeReq(payload));
@@ -168,7 +198,7 @@ describe("PUT /api/insights/layout — happy path", () => {
};
expect(body.data.tiles[0]?.id).toBe("overview");
expect(body.data.tiles[0]?.order).toBe(0);
expect(body.data.tiles[2]?.id).toBe("puls");
expect(body.data.tiles[2]?.id).toBe("pulse");
expect(body.data.tiles[2]?.visible).toBe(false);
expect(prisma.user.update).toHaveBeenCalledTimes(1);
@@ -179,6 +209,47 @@ describe("PUT /api/insights/layout — happy path", () => {
expect(updateCall.where.id).toBe("user-1");
expect(updateCall.data.insightsLayoutJson).toBeTruthy();
});
it("accepts a body carrying legacy German tile ids and persists the canonical English ones", async () => {
// Non-breaking iOS contract: a client still sending the pre-v1.8.0
// German ids must NOT 422. The route validates the legacy ids and
// `serializeInsightsLayout` normalises them to English before the
// row persists, so the stored blob is always canonical.
vi.mocked(prisma.user.update).mockResolvedValue({} as never);
const payload = {
version: 1,
tiles: [
{ id: "overview", visible: true, order: 0 },
{ id: "blutdruck", visible: true, order: 1 },
{ id: "medikamente", visible: true, order: 2 },
],
};
const res = await callPut(makeReq(payload));
// No 422 — the legacy ids pass validation.
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { tiles: Array<{ id: string }> };
};
const returnedIds = body.data.tiles.map((t) => t.id);
expect(returnedIds).toContain("blood-pressure");
expect(returnedIds).toContain("medications");
expect(returnedIds).not.toContain("blutdruck");
expect(returnedIds).not.toContain("medikamente");
// The persisted blob is canonical too.
const updateCall = vi.mocked(prisma.user.update).mock.calls[0]?.[0] as unknown as {
data: { insightsLayoutJson: { tiles: Array<{ id: string }> } };
};
const persistedIds = updateCall.data.insightsLayoutJson.tiles.map(
(t) => t.id,
);
expect(persistedIds).toContain("blood-pressure");
expect(persistedIds).toContain("medications");
expect(persistedIds).not.toContain("blutdruck");
expect(persistedIds).not.toContain("medikamente");
});
});
describe("PUT /api/insights/layout — 422 multi-issue envelope", () => {
+13 -6
View File
@@ -27,7 +27,7 @@ import {
resolveInsightsLayout,
serializeInsightsLayout,
DEFAULT_INSIGHTS_LAYOUT,
INSIGHTS_TILE_IDS,
ACCEPTED_INSIGHTS_TILE_IDS,
type InsightsLayout,
} from "@/lib/insights-layout";
import { Prisma } from "@/generated/prisma/client";
@@ -38,11 +38,18 @@ import { redactSensitiveFields } from "@/lib/observability/redact-payload";
import { shouldEmitAuditRow } from "@/lib/audit-dedup";
import type { NextRequest } from "next/server";
// Derive the enum from `INSIGHTS_TILE_IDS` so the schema + the default
// layout cannot drift — the same root-cause class that produced the
// v1.4.16 A5 silent-422 on dashboard widgets when `achievements` was
// added to the layout but not to the validation enum.
const tileIdEnum = z.enum(INSIGHTS_TILE_IDS);
// Derive the enum from `ACCEPTED_INSIGHTS_TILE_IDS` so the schema + the
// default layout cannot drift — the same root-cause class that produced
// the v1.4.16 A5 silent-422 on dashboard widgets when `achievements`
// was added to the layout but not to the validation enum.
//
// v1.8.0 — the accepted set is canonical English ids PLUS the legacy
// German aliases, so an iOS client still PUTting `blutdruck` / `puls` /
// … passes validation rather than tripping a 422 on the rename.
// `serializeInsightsLayout` normalises any legacy id onto its canonical
// English replacement before the row persists, so the stored blob is
// always canonical regardless of which id the client sent.
const tileIdEnum = z.enum(ACCEPTED_INSIGHTS_TILE_IDS);
const layoutSchema = z.object({
version: z.literal(1),
@@ -23,9 +23,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
});
const locale = resolveMedicationComplianceStatusLocale(resolved);
// v1.8.3 — read-only: serve the cache, enqueue generation out of band on
// a miss. The GET never awaits the provider, so opening /insights/<metric>
// can no longer pin the main thread behind a cold LLM round-trip.
const result = await generateMedicationComplianceStatusForUser(user.id, {
locale,
force: false,
readOnly: true,
});
annotate({ action: { name: "insights.medication-compliance-status" } });
@@ -23,9 +23,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
});
const locale = resolveMoodStatusLocale(resolved);
// v1.8.3 — read-only: serve the cache, enqueue generation out of band on
// a miss. The GET never awaits the provider, so opening /insights/<metric>
// can no longer pin the main thread behind a cold LLM round-trip.
const result = await generateMoodStatusForUser(user.id, {
locale,
force: false,
readOnly: true,
});
annotate({ action: { name: "insights.mood-status" } });
@@ -23,9 +23,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
});
const locale = resolvePulseStatusLocale(resolved);
// v1.8.3 — read-only: serve the cache, enqueue generation out of band on
// a miss. The GET never awaits the provider, so opening /insights/<metric>
// can no longer pin the main thread behind a cold LLM round-trip.
const result = await generatePulseStatusForUser(user.id, {
locale,
force: false,
readOnly: true,
});
annotate({ action: { name: "insights.pulse-status" } });
@@ -23,9 +23,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
});
const locale = resolveWeightStatusLocale(resolved);
// v1.8.3 — read-only: serve the cache, enqueue generation out of band on
// a miss. The GET never awaits the provider, so opening /insights/<metric>
// can no longer pin the main thread behind a cold LLM round-trip.
const result = await generateWeightStatusForUser(user.id, {
locale,
force: false,
readOnly: true,
});
annotate({ action: { name: "insights.weight-status" } });
+20
View File
@@ -12,6 +12,7 @@ import {
} from "@/lib/api-response";
import { updateMeasurementSchema } from "@/lib/validations/measurement";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import { invalidateStatusInsightsForTypes } from "@/lib/insights/comprehensive-generate";
import { recomputeBucketsForMeasurement } from "@/lib/rollups/measurement-rollups";
import { Prisma } from "@/generated/prisma/client";
import { NextRequest } from "next/server";
@@ -172,6 +173,18 @@ export const PUT = apiHandler(
console.warn("[measurements] rollup recompute failed", err);
}
// v1.8.0 — drop the cached per-metric assessment rows this edit
// dirties so the next mount / nightly warm pass regenerates against
// the new value. An edit can re-type a row, so invalidate both the
// old and the new type's scopes. Fire-and-forget: never blocks the
// user's edit.
invalidateStatusInsightsForTypes(user.id, [
existing.type,
measurement.type,
]).catch((err) => {
console.warn("[measurements] status-insight invalidate failed", err);
});
return apiSuccess(measurement);
},
);
@@ -238,6 +251,13 @@ export const DELETE = apiHandler(
console.warn("[measurements] rollup recompute failed", err);
}
// v1.8.0 — drop the cached per-metric assessment rows this deletion
// dirties so the next mount / nightly warm pass regenerates against
// the reduced history. Fire-and-forget: never blocks the user's delete.
invalidateStatusInsightsForTypes(user.id, [existing.type]).catch((err) => {
console.warn("[measurements] status-insight invalidate failed", err);
});
return apiSuccess({ deleted: true });
},
);
+12
View File
@@ -46,6 +46,7 @@ import { deviceTypeEnum } from "@/lib/validations/source-priority";
import { checkRateLimit } from "@/lib/rate-limit";
import { enqueuePrDetection } from "@/lib/jobs/pr-detection";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import { invalidateStatusInsightsForTypes } from "@/lib/insights/comprehensive-generate";
import {
recomputeBucketsForMeasurement,
collapseToTypeDayKeys,
@@ -484,6 +485,17 @@ async function postBatch(request: NextRequest): Promise<Response> {
for (const k of insertedKeys) {
await recomputeBucketsForMeasurement(user.id, k.type, k.measuredAt);
}
// v1.8.0 — drop the cached per-metric assessment rows the ingested
// types dirty so the next mount / nightly warm pass regenerates
// them against the new data instead of serving stale text.
// Fire-and-forget: never a blocker on the user's ingest.
invalidateStatusInsightsForTypes(
user.id,
insertedKeys.map((k) => k.type),
).catch((err) => {
console.warn("[measurements] status-insight invalidate failed", err);
});
} catch (err) {
console.warn("[measurements] rollup recompute failed", err);
}
@@ -35,6 +35,7 @@ import {
safeJson,
} from "@/lib/api-response";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import { invalidateStatusInsightsForTypes } from "@/lib/insights/comprehensive-generate";
import {
recomputeBucketsForMeasurement,
collapseToTypeDayKeys,
@@ -152,6 +153,17 @@ async function deleteByExternalIds(request: NextRequest): Promise<Response> {
} catch (err) {
console.warn("[measurements] rollup recompute failed", err);
}
// v1.8.0 — drop the cached per-metric assessment rows the deleted
// types dirty so the next mount / nightly warm pass regenerates
// against the reconciled history. Fire-and-forget: never blocks the
// iOS reconciliation.
invalidateStatusInsightsForTypes(
user.id,
affectedRows.map((row) => row.type),
).catch((err) => {
console.warn("[measurements] status-insight invalidate failed", err);
});
}
return apiSuccess({ deletedCount: result.count });
+18
View File
@@ -28,6 +28,7 @@ import {
} from "@/lib/measurements/drain-per-sample-cumulative";
import { withIdempotency } from "@/lib/idempotency";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import { invalidateStatusInsightsForTypes } from "@/lib/insights/comprehensive-generate";
import {
recomputeBucketsForMeasurement,
collapseToTypeDayKeys,
@@ -664,6 +665,16 @@ async function postMeasurement(request: NextRequest) {
for (const k of keys) {
await recomputeBucketsForMeasurement(user.id, k.type, k.measuredAt);
}
// v1.8.0 — drop the cached per-metric assessment rows the ingested
// types dirty so the next mount / nightly warm pass regenerates
// them against the new data. Fire-and-forget: never blocks ingest.
invalidateStatusInsightsForTypes(
user.id,
keys.map((k) => k.type),
).catch((err) => {
console.warn("[measurements] status-insight invalidate failed", err);
});
} catch (err) {
console.warn("[measurements] rollup recompute failed", err);
}
@@ -768,5 +779,12 @@ async function postMeasurement(request: NextRequest) {
console.warn("[measurements] rollup recompute failed", err);
}
// v1.8.0 — drop the cached per-metric assessment rows this type
// dirties so the next mount / nightly warm pass regenerates against
// the new row. Fire-and-forget: never blocks the user's write.
invalidateStatusInsightsForTypes(user.id, [measurement.type]).catch((err) => {
console.warn("[measurements] status-insight invalidate failed", err);
});
return apiSuccess(measurement, 201);
}
@@ -0,0 +1,241 @@
/**
* v1.8.1 B15 follow-on — per-slot timing classification for the History
* compliance heatmap.
*
* The `dailyCompliance` builder in `GET /api/medications/[id]/compliance`
* classifies each taken intake into early / on_time / late / very_late
* buckets and paints the heatmap cell off those counts. The bug: a
* twice-daily medication stored as ONE schedule row
* (`timesOfDay = ["07:00","19:00"]`, `windowStart = "07:00"`) matched the
* 19:00 dose against the single `windowStart` "07:00" — classifying a
* perfectly on-time evening dose as `very_late` (~12h late) and painting
* the cell orange even though both doses were taken on time.
*
* The fix matches each taken event to the closest effective time-of-day
* SLOT across every schedule (candidate slots = `timesOfDay` when
* non-empty, else `[windowStart]`) and classifies against that slot's
* window (slot..slot+span, span = windowEnd − windowStart). Single-time
* schedules stay byte-identical to the pre-fix behaviour.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
medication: { findUnique: vi.fn() },
medicationIntakeEvent: { findMany: vi.fn() },
},
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/medications/route-guards", () => ({
assertMedicationOwnership: vi.fn().mockResolvedValue(null),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { GET } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { getUserTodayBounds } from "@/lib/timezone";
import { userDayKey } from "@/lib/tz/format";
// UTC keeps the half-open day slice (`[dayStart, dayEnd)`) and the
// classifier's window anchor (`setUTCHours` on the day-start date) in the
// same reference frame, so the fixture instants below land deterministically
// in range regardless of the host timezone.
const TZ = "UTC";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const, timezone: TZ },
};
const ROUTE_PARAMS = { params: Promise.resolve({ id: "med-1" }) };
// A representative "yesterday" so the day is fully in the past and the
// medication's createdAt clearly precedes it. The route walks 90 days
// back from `new Date()`; this instant lands well inside that window.
const DAY_OFFSET = 1;
function dayBoundsForOffset(offset: number) {
const now = new Date();
const representative = new Date(
now.getTime() - offset * 24 * 60 * 60 * 1000 - 12 * 60 * 60 * 1000,
);
const { start, end } = getUserTodayBounds(representative, TZ);
return { start, endInclusive: end };
}
// Build a UTC instant for a given "HH:mm" anchored on the day-start date,
// mirroring how `classifyIntakeTiming` interprets the window via
// `setUTCHours` on the scheduled date. Keeps the fixture's takenAt aligned
// with the classifier's reference frame regardless of host timezone.
function atSlotUTC(dayStart: Date, hhmm: string): Date {
const [h, m] = hhmm.split(":").map(Number);
const d = new Date(dayStart);
d.setUTCHours(h, m, 0, 0);
return d;
}
function medication(schedules: unknown[]) {
return {
id: "med-1",
userId: "user-1",
createdAt: new Date(Date.now() - 200 * 24 * 60 * 60 * 1000),
startsOn: null,
endsOn: null,
oneShot: false,
schedules,
};
}
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
});
async function callRoute(): Promise<Record<string, unknown>> {
const res = await GET(new Request("http://localhost"), ROUTE_PARAMS);
expect(res.status).toBe(200);
const body = await res.json();
return body.data.dailyCompliance as Record<string, unknown>;
}
describe("GET /api/medications/[id]/compliance — per-slot timing", () => {
it("classifies both doses of a single-row twice-daily schedule as on_time (green cell)", async () => {
const { start: dayStart } = dayBoundsForOffset(DAY_OFFSET);
const dateKey = userDayKey(dayStart, TZ);
// ONE schedule row, two times-of-day, a 1h window per slot.
vi.mocked(prisma.medication.findUnique).mockResolvedValue(
medication([
{
id: "sched-1",
windowStart: "07:00",
windowEnd: "08:00",
timesOfDay: ["07:00", "19:00"],
daysOfWeek: null,
rrule: null,
rollingIntervalDays: null,
reminderGraceMinutes: null,
scheduleType: "SCHEDULED",
cyclicOnWeeks: null,
cyclicOffWeeks: null,
},
]) as never,
);
// Both doses logged right at their slot times.
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([
{
takenAt: atSlotUTC(dayStart, "07:05"),
skipped: false,
scheduledFor: atSlotUTC(dayStart, "07:00"),
},
{
takenAt: atSlotUTC(dayStart, "19:05"),
skipped: false,
scheduledFor: atSlotUTC(dayStart, "19:00"),
},
] as never);
const daily = await callRoute();
const entry = daily[dateKey] as Record<string, number> | undefined;
expect(entry).toBeDefined();
expect(entry!.veryLate).toBe(0);
expect(entry!.late).toBe(0);
// Both doses compliant → green cell.
expect(entry!.onTime).toBe(2);
});
it("keeps single-time schedules byte-identical: a 12h-late dose is still very_late", async () => {
const { start: dayStart } = dayBoundsForOffset(DAY_OFFSET);
const dateKey = userDayKey(dayStart, TZ);
vi.mocked(prisma.medication.findUnique).mockResolvedValue(
medication([
{
id: "sched-1",
windowStart: "07:00",
windowEnd: "08:00",
timesOfDay: [], // single-time: candidate = [windowStart]
daysOfWeek: null,
rrule: null,
rollingIntervalDays: null,
reminderGraceMinutes: null,
scheduleType: "SCHEDULED",
cyclicOnWeeks: null,
cyclicOffWeeks: null,
},
]) as never,
);
// Single 07:00 schedule, dose taken at 19:00 → ~12h late → very_late.
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([
{
takenAt: atSlotUTC(dayStart, "19:00"),
skipped: false,
scheduledFor: atSlotUTC(dayStart, "07:00"),
},
] as never);
const daily = await callRoute();
const entry = daily[dateKey] as Record<string, number> | undefined;
expect(entry).toBeDefined();
expect(entry!.veryLate).toBe(1);
expect(entry!.onTime).toBe(0);
expect(entry!.late).toBe(0);
});
it("handles an overnight per-slot window (23:00 slot, 1h span) as on_time near the slot", async () => {
const { start: dayStart } = dayBoundsForOffset(DAY_OFFSET);
const dateKey = userDayKey(dayStart, TZ);
vi.mocked(prisma.medication.findUnique).mockResolvedValue(
medication([
{
id: "sched-1",
windowStart: "23:00",
windowEnd: "00:00", // overnight: end <= start
timesOfDay: ["09:00", "23:00"],
daysOfWeek: null,
rrule: null,
rollingIntervalDays: null,
reminderGraceMinutes: null,
scheduleType: "SCHEDULED",
cyclicOnWeeks: null,
cyclicOffWeeks: null,
},
]) as never,
);
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([
{
takenAt: atSlotUTC(dayStart, "23:10"),
skipped: false,
scheduledFor: atSlotUTC(dayStart, "23:00"),
},
] as never);
const daily = await callRoute();
const entry = daily[dateKey] as Record<string, number> | undefined;
expect(entry).toBeDefined();
expect(entry!.veryLate).toBe(0);
expect(entry!.late).toBe(0);
expect(entry!.onTime).toBe(1);
});
});
@@ -16,6 +16,74 @@ import { userDayKey } from "@/lib/tz/format";
type RouteParams = { params: Promise<{ id: string }> };
/** A single effective dose slot with its derived punctuality window. */
interface SlotWindow {
/** Minute-of-day of the slot's start time (used for nearest-slot match). */
startMinutes: number;
/** "HH:mm" slot start — fed to `classifyIntakeTiming` as `windowStart`. */
windowStart: string;
/** "HH:mm" slot end = slot start + the schedule's window span. */
windowEnd: string;
}
const MINUTES_PER_DAY = 24 * 60;
/** Parse "HH:mm" into minute-of-day. */
function hhmmToMinutes(time: string): number {
const [h, m] = time.split(":").map(Number);
return h * 60 + m;
}
/** Format a minute-of-day (wrapped into 0..1439) back to "HH:mm". */
function minutesToHHmm(minutes: number): string {
const wrapped = ((minutes % MINUTES_PER_DAY) + MINUTES_PER_DAY) %
MINUTES_PER_DAY;
const h = Math.floor(wrapped / 60);
const m = wrapped % 60;
return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
}
/**
* v1.8.1 B15 follow-on — expand every schedule into its effective dose
* slots so timing classification matches against the right time-of-day.
*
* Candidate slot times for a schedule are its `timesOfDay` when non-empty,
* else `[windowStart]` (so single-time schedules collapse to one slot at
* `windowStart` and stay byte-identical to the pre-fix matcher). Each
* slot's punctuality window is anchored at the slot time and spans the
* schedule's `windowEnd − windowStart` duration; overnight windows
* (`windowEnd ≤ windowStart`) add a day to the span before deriving the
* per-slot end. Multi-schedule meds union their slots — the matcher then
* picks the single closest slot across all of them.
*/
function buildSlotCandidates(
schedules: { windowStart: string; windowEnd: string; timesOfDay: string[] }[],
): SlotWindow[] {
const slots: SlotWindow[] = [];
for (const sched of schedules) {
const startMin = hhmmToMinutes(sched.windowStart);
let endMin = hhmmToMinutes(sched.windowEnd);
// Overnight window: the end is on the following day.
if (endMin <= startMin) endMin += MINUTES_PER_DAY;
const spanMinutes = endMin - startMin;
const times =
sched.timesOfDay.length > 0 ? sched.timesOfDay : [sched.windowStart];
for (const time of times) {
const slotStartMin = hhmmToMinutes(time);
slots.push({
startMinutes: slotStartMin,
windowStart: minutesToHHmm(slotStartMin),
// `classifyIntakeTiming` re-detects the overnight wrap from the
// HH:mm pair, so a wrapped end formats back into 0..1439 cleanly.
windowEnd: minutesToHHmm(slotStartMin + spanMinutes),
});
}
}
return slots;
}
export const GET = apiHandler(
async (_request: Request, { params }: RouteParams) => {
const { user } = await requireAuth();
@@ -115,33 +183,49 @@ export const GET = apiHandler(
let veryLate = 0;
let early = 0;
// v1.8.1 B15 follow-on — match each taken event to the closest
// effective time-of-day SLOT, not merely `windowStart`. A single
// schedule row carrying `timesOfDay = ["07:00","19:00"]` is two
// distinct dose slots; matching the evening dose against the lone
// `windowStart` "07:00" mis-classified it as `very_late` (~12h late)
// and painted the heatmap cell orange even when both doses were
// taken on time. Candidate slots for a schedule are its `timesOfDay`
// when non-empty, else `[windowStart]` — so single-time schedules
// collapse to exactly one candidate at `windowStart` and stay
// byte-identical to the pre-fix behaviour. The per-slot window
// mirrors the projector / cadence anchor: effective windowStart is
// the slot time, effective windowEnd is the slot time plus the
// schedule's `windowEnd − windowStart` span (overnight spans where
// `windowEnd ≤ windowStart` add a day).
const slotCandidates = buildSlotCandidates(medication.schedules);
for (const evt of takenEvents) {
if (medication.schedules.length === 0) {
if (slotCandidates.length === 0) {
// No schedule info: treat all taken as on_time
onTime++;
continue;
}
// Match event to the closest schedule window by scheduledFor time
// Match event to the closest slot window by scheduledFor time.
const evtHour = evt.scheduledFor.getUTCHours();
const evtMin = evt.scheduledFor.getUTCMinutes();
const evtMinutes = evtHour * 60 + evtMin;
let bestSchedule = medication.schedules[0];
let bestSlot = slotCandidates[0];
let bestDist = Infinity;
for (const sched of medication.schedules) {
const [sh, sm] = sched.windowStart.split(":").map(Number);
const dist = Math.abs(evtHour * 60 + evtMin - (sh * 60 + sm));
for (const slot of slotCandidates) {
const dist = Math.abs(evtMinutes - slot.startMinutes);
if (dist < bestDist) {
bestDist = dist;
bestSchedule = sched;
bestSlot = slot;
}
}
const timing = classifyIntakeTiming(
evt.takenAt,
bestSchedule.windowStart,
bestSchedule.windowEnd,
bestSlot.windowStart,
bestSlot.windowEnd,
dayStart, // the scheduled date
);
@@ -26,6 +26,10 @@ vi.mock("@/lib/db", () => ({
prisma: {
medication: {
findUnique: vi.fn(),
// v1.8.2 — the slot-snap resolver loads the medication via
// findFirst; default to a schedule-less med so the resolver returns
// null (unscheduled path) and the original insert behaviour holds.
findFirst: vi.fn(),
update: vi.fn(),
updateMany: vi.fn(),
},
@@ -34,6 +38,8 @@ vi.mock("@/lib/db", () => ({
findFirst: vi.fn(),
count: vi.fn(),
create: vi.fn(),
// v1.8.2 reconcile — the shared slot upsert updates in place.
update: vi.fn(),
},
auditLog: { create: vi.fn() },
$transaction: vi.fn(),
@@ -307,6 +313,16 @@ describe("POST /api/medications/[id]/intake — one-shot lifecycle", () => {
skipped: false,
};
vi.mocked(prisma.$transaction).mockResolvedValue([createdEvent] as never);
// v1.8.2 — slot-snap resolver loads the med; no schedules → null slot
// → original insert + dedup path preserved.
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce({
id: "med-1",
startsOn: null,
endsOn: null,
oneShot: true,
createdAt: new Date(),
schedules: [],
} as never);
vi.mocked(prisma.medicationIntakeEvent.findFirst).mockResolvedValueOnce(
null as never, // dedup probe
);
@@ -336,3 +352,184 @@ describe("POST /api/medications/[id]/intake — one-shot lifecycle", () => {
});
});
});
// ────────────────────────────────────────────────────────────────────
// v1.8.2 reconcile — slot-snap upsert invariants through the route
// ────────────────────────────────────────────────────────────────────
describe("POST /api/medications/[id]/intake — v1.8.2 reconcile (M2 inventory)", () => {
function postReq(body: unknown): NextRequest {
return new NextRequest("http://localhost/api/medications/med-1/intake", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
// A scheduled med (07:00 / 19:00) so the resolver returns a canonical
// slot and the write routes through the shared upsert.
const SCHEDULED_MED = {
id: "med-1",
startsOn: null,
endsOn: null,
oneShot: false,
createdAt: new Date("2026-01-01T00:00:00Z"),
schedules: [
{
id: "s1",
windowStart: "07:00",
windowEnd: "07:00",
daysOfWeek: null,
timesOfDay: ["07:00", "19:00"],
reminderGraceMinutes: null,
rrule: null,
rollingIntervalDays: null,
scheduleType: "SCHEDULED",
cyclicOnWeeks: null,
cyclicOffWeeks: null,
},
],
};
it("does NOT decrement inventory on a re-post of an already-taken slot (M2)", async () => {
const { consumeOneDose } = await import(
"@/lib/medications/inventory/service"
);
// Resolver load → scheduled med.
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce(
SCHEDULED_MED as never,
);
// Slot find (shared upsert) → an existing TAKEN row at the 07:00 slot.
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValueOnce([
{
id: "row-taken",
takenAt: new Date("2026-06-15T05:01:00Z"),
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "WEB",
createdAt: new Date("2026-06-15T05:01:00Z"),
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValueOnce({
id: "row-taken",
takenAt: new Date("2026-06-15T05:02:00Z"),
skipped: false,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "WEB",
} as never);
vi.mocked(prisma.medication.update).mockResolvedValue({} as never);
// Reconcile probes (non-one-shot → noop).
vi.mocked(prisma.medication.findUnique).mockResolvedValue({
oneShot: false,
active: true,
} as never);
const res = await POST(
postReq({
scheduledFor: "2026-06-15T05:00:30.000Z",
takenAt: "2026-06-15T05:02:00.000Z",
}),
ROUTE_PARAMS,
);
expect(res.status).toBe(201);
// Re-post of an already-taken slot → no pending→taken transition →
// inventory must NOT be consumed.
expect(consumeOneDose).not.toHaveBeenCalled();
// The row was updated, not duplicated.
expect(prisma.medicationIntakeEvent.update).toHaveBeenCalledTimes(1);
expect(prisma.medicationIntakeEvent.create).not.toHaveBeenCalled();
});
it("DOES decrement inventory on a genuine pending→taken move (M2)", async () => {
const { consumeOneDose } = await import(
"@/lib/medications/inventory/service"
);
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce(
SCHEDULED_MED as never,
);
// Slot find → a PENDING REMINDER row (no takenAt).
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValueOnce([
{
id: "row-pending",
takenAt: null,
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
createdAt: new Date("2026-06-15T00:00:00Z"),
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValueOnce({
id: "row-pending",
takenAt: new Date("2026-06-15T05:02:00Z"),
skipped: false,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
} as never);
vi.mocked(prisma.medication.update).mockResolvedValue({} as never);
vi.mocked(prisma.medication.findUnique).mockResolvedValue({
oneShot: false,
active: true,
} as never);
const res = await POST(
postReq({
scheduledFor: "2026-06-15T05:00:30.000Z",
takenAt: "2026-06-15T05:02:00.000Z",
}),
ROUTE_PARAMS,
);
expect(res.status).toBe(201);
expect(consumeOneDose).toHaveBeenCalledTimes(1);
});
it("re-finds and updates the slot when the create races a P2002 (C1)", async () => {
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce(
SCHEDULED_MED as never,
);
// First slot find → empty. Create throws P2002. Re-find → the racing
// pending row. Update applies the taken write onto it.
vi.mocked(prisma.medicationIntakeEvent.findMany)
.mockResolvedValueOnce([] as never)
.mockResolvedValueOnce([
{
id: "row-raced",
takenAt: null,
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
createdAt: new Date("2026-06-15T00:00:00Z"),
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.create).mockRejectedValueOnce(
Object.assign(new Error("unique"), { code: "P2002" }),
);
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValueOnce({
id: "row-raced",
takenAt: new Date("2026-06-15T05:02:00Z"),
skipped: false,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
} as never);
vi.mocked(prisma.medication.update).mockResolvedValue({} as never);
vi.mocked(prisma.medication.findUnique).mockResolvedValue({
oneShot: false,
active: true,
} as never);
const res = await POST(
postReq({
scheduledFor: "2026-06-15T05:00:30.000Z",
takenAt: "2026-06-15T05:02:00.000Z",
}),
ROUTE_PARAMS,
);
// The dose tap is NOT dropped — converges to the racing row, 201.
expect(res.status).toBe(201);
expect(prisma.medicationIntakeEvent.update).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: "row-raced" } }),
);
});
});
+106 -25
View File
@@ -19,6 +19,10 @@ import { reconcileOneShotState } from "@/lib/medications/lifecycle";
import { assertMedicationOwnership } from "@/lib/medications/route-guards";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
import { recomputeMedicationComplianceForEvent } from "@/lib/rollups/medication-compliance-rollups";
import {
applyCanonicalSlotWrite,
resolveSlotInstantForWrite,
} from "@/lib/medications/scheduling/slot-upsert";
import { NextRequest } from "next/server";
type RouteParams = { params: Promise<{ id: string }> };
@@ -74,6 +78,38 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
const { scheduledFor, takenAt, skipped, idempotencyKey } = parsed.data;
const resolvedTakenAt = skipped ? null : (takenAt ?? new Date());
const incomingScheduledFor = scheduledFor ?? takenAt ?? new Date();
// C2 — the per-med route only ever carries an explicit user gesture:
// `resolvedTakenAt` is `now()` for any non-skip POST (there is no
// "mark pending" write on this route), so a non-skip is an explicit
// taken and a `skipped:true` body is an explicit skip. Neither is a
// pending projection echo, so the no-downgrade guard never trips here —
// it is the bulk/sync route that replays pending echoes. The flags are
// threaded through so the shared upsert applies last-write-wins.
const isExplicitTaken = !skipped;
const isExplicitSkip = skipped === true;
// v1.8.2 — source-agnostic slot snap. A twice-daily med carries a
// pending REMINDER row the projector/worker minted at the canonical
// `localHmAsUtc` slot instant. Without this, a manual "Genommen" write
// (source WEB) inserted a SECOND row for the slot because the unique
// key includes `source` and the iOS-vs-server `scheduledFor` can drift
// by a minute — inflating compliance to 100% and suppressing the
// "take now" prompt for a dose the user hadn't taken. Snap the write
// to the canonical slot and update the existing row in place.
//
// Resolved BEFORE the idempotency/dedup window so a scheduled dose
// routes through the slot upsert (which is itself the dedup): the
// legacy 60-second window would otherwise short-circuit by returning
// the slot's pending REMINDER row WITHOUT applying the user's takenAt.
const canonicalSlot = await resolveSlotInstantForWrite({
userId: user.id,
medicationId: id,
userTz: user.timezone,
incoming: incomingScheduledFor,
});
// Idempotency check (explicit key or server-side dedup window)
if (idempotencyKey) {
const existing = await prisma.medicationIntakeEvent.findFirst({
@@ -86,8 +122,10 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
if (existing) {
return apiSuccess(existing);
}
} else {
// Server-side dedup: prevent double-logging within 60 seconds
} else if (!canonicalSlot) {
// Unscheduled / PRN only — the slot upsert handles dedup for
// scheduled doses by collapsing onto the canonical slot row.
// Server-side dedup: prevent double-logging within 60 seconds.
const recentDuplicate = await prisma.medicationIntakeEvent.findFirst({
where: {
userId: user.id,
@@ -102,28 +140,65 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
}
}
const [event] = await prisma.$transaction([
prisma.medicationIntakeEvent.create({
data: {
userId: user.id,
medicationId: id,
scheduledFor: scheduledFor ?? takenAt ?? new Date(),
takenAt: skipped ? null : (takenAt ?? new Date()),
skipped,
source: "WEB",
idempotencyKey: idempotencyKey ?? null,
},
}),
// Reset snooze when medication is taken
...(!skipped
? [
prisma.medication.update({
where: { id },
data: { snoozedUntil: null },
}),
]
: []),
]);
let event;
// v1.8.2 reconcile — whether this write moved the slot pending→taken.
// Only that transition decrements pen inventory (M2). For the
// unscheduled/PRN branch a non-skip write always records a fresh dose,
// so it consumes when not skipped.
let consumedTransition = !skipped;
if (canonicalSlot) {
// Scheduled dose — converge onto the one canonical slot row regardless
// of `source` (the pending REMINDER row, or any prior row for this
// slot) through the shared upsert: H1 deterministic selection, C2
// no-downgrade guard, and a C1 race-safe create that re-finds + updates
// on a P2002 collision rather than 500-ing or duplicating.
const applied = await applyCanonicalSlotWrite({
client: prisma,
userId: user.id,
medicationId: id,
canonicalSlot,
takenAt: resolvedTakenAt,
skipped,
isExplicitTaken,
isExplicitSkip,
idempotencyKey: idempotencyKey ?? null,
createSource: "WEB",
});
event = applied.row;
consumedTransition = applied.consumedTransition;
// Reset the snooze when a dose is actually recorded (not on a
// no-downgrade no-op, which left the prior taken row untouched).
if (!skipped && !applied.noDowngradeNoOp) {
await prisma.medication.update({
where: { id },
data: { snoozedUntil: null },
});
}
} else {
// Unscheduled / PRN / off-slot — keep the original insert behaviour.
[event] = await prisma.$transaction([
prisma.medicationIntakeEvent.create({
data: {
userId: user.id,
medicationId: id,
scheduledFor: incomingScheduledFor,
takenAt: resolvedTakenAt,
skipped,
source: "WEB",
idempotencyKey: idempotencyKey ?? null,
},
}),
// Reset snooze when medication is taken
...(!skipped
? [
prisma.medication.update({
where: { id },
data: { snoozedUntil: null },
}),
]
: []),
]);
}
// v1.4.25 W19b — pen-inventory dose decrement. Only fires for
// non-skipped intakes; a skipped event is not a consumption event.
@@ -131,8 +206,14 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
// meds). Failures here must never block the intake write, so
// errors are swallowed and logged — the intake is the source of
// truth, the inventory is an opt-in companion.
//
// v1.8.2 M2 — gate on an ACTUAL pending→taken transition. An idempotent
// re-post of an already-taken slot updates the row in place but must NOT
// decrement again, else a repeated iOS sync drifts the GLP-1 pen count
// down on every replay. `consumedTransition` is false when the slot was
// already taken (or on a no-downgrade no-op).
let inventoryOutcome: Awaited<ReturnType<typeof consumeOneDose>> = null;
if (!skipped) {
if (!skipped && consumedTransition) {
try {
inventoryOutcome = await consumeOneDose({
userId: user.id,
@@ -9,10 +9,15 @@ vi.mock("@/lib/db", () => ({
prisma: {
medication: {
findMany: vi.fn(),
// v1.8.2 — the slot resolver loads the med via findFirst.
findFirst: vi.fn(),
},
medicationIntakeEvent: {
create: vi.fn(),
findUnique: vi.fn(),
// v1.8.2 reconcile — shared slot upsert reads + updates in place.
findMany: vi.fn(),
update: vi.fn(),
},
auditLog: { create: vi.fn() },
},
@@ -151,3 +156,164 @@ describe("POST /api/medications/intake/bulk — 422 multi-issue (v1.4.43 W6)", (
expect(res.status).toBe(422);
});
});
// ────────────────────────────────────────────────────────────────────
// v1.8.2 reconcile — bulk slot-snap upsert invariants (C2 + C1)
// ────────────────────────────────────────────────────────────────────
describe("POST /api/medications/intake/bulk — v1.8.2 reconcile", () => {
const SCHEDULED_MED = {
id: "med-1",
startsOn: null,
endsOn: null,
oneShot: false,
createdAt: new Date("2026-01-01T00:00:00Z"),
schedules: [
{
id: "s1",
windowStart: "07:00",
windowEnd: "07:00",
daysOfWeek: null,
timesOfDay: ["07:00", "19:00"],
reminderGraceMinutes: null,
rrule: null,
rollingIntervalDays: null,
scheduleType: "SCHEDULED",
cyclicOnWeeks: null,
cyclicOffWeeks: null,
},
],
};
beforeEach(() => {
vi.mocked(prisma.medication.findMany).mockResolvedValue([
{ id: "med-1" },
] as never);
vi.mocked(prisma.medication.findFirst).mockResolvedValue(
SCHEDULED_MED as never,
);
});
it("C2 — a pending echo onto an already-TAKEN slot is reported duplicate, NOT a downgrade", async () => {
// Existing TAKEN row at the 07:00 slot. The bulk entry is a pending
// echo (no takenAt, skipped false) — must NOT clear takenAt.
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValueOnce([
{
id: "row-taken",
takenAt: new Date("2026-06-15T05:01:00Z"),
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "WEB",
createdAt: new Date("2026-06-15T05:01:00Z"),
},
] as never);
const res = await POST(
postReq({
entries: [
{
medicationId: "med-1",
scheduledFor: "2026-06-15T05:00:30.000Z",
// no takenAt, skipped defaults false → pending echo
},
],
}),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: {
duplicates: number;
updated: number;
entries: Array<{ status: string; id?: string }>;
};
};
expect(body.data.duplicates).toBe(1);
expect(body.data.updated).toBe(0);
expect(body.data.entries[0].status).toBe("duplicate");
// The recorded dose was NEVER touched — no update issued.
expect(prisma.medicationIntakeEvent.update).not.toHaveBeenCalled();
});
it("C2 — an explicit takenAt still applies onto a pending slot (status updated)", async () => {
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValueOnce([
{
id: "row-pending",
takenAt: null,
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
createdAt: new Date("2026-06-15T00:00:00Z"),
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValueOnce({
id: "row-pending",
} as never);
const res = await POST(
postReq({
entries: [
{
medicationId: "med-1",
scheduledFor: "2026-06-15T05:00:30.000Z",
takenAt: "2026-06-15T05:02:00.000Z",
},
],
}),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { updated: number; entries: Array<{ status: string }> };
};
expect(body.data.updated).toBe(1);
expect(body.data.entries[0].status).toBe("updated");
});
it("C1 — a same-slot P2002 on create converges via re-find+update, not dropped as duplicate", async () => {
// First slot find empty → create races a P2002 → re-find returns the
// racing pending row → update applies the incoming takenAt.
vi.mocked(prisma.medicationIntakeEvent.findMany)
.mockResolvedValueOnce([] as never)
.mockResolvedValueOnce([
{
id: "row-raced",
takenAt: null,
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
createdAt: new Date("2026-06-15T00:00:00Z"),
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.create).mockRejectedValueOnce(
Object.assign(new Error("unique"), { code: "P2002" }),
);
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValueOnce({
id: "row-raced",
} as never);
const res = await POST(
postReq({
entries: [
{
medicationId: "med-1",
scheduledFor: "2026-06-15T05:00:30.000Z",
takenAt: "2026-06-15T05:02:00.000Z",
},
],
}),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { updated: number; entries: Array<{ status: string; id?: string }> };
};
// The dose is APPLIED to the existing row, not silently dropped.
expect(body.data.updated).toBe(1);
expect(body.data.entries[0].status).toBe("updated");
expect(body.data.entries[0].id).toBe("row-raced");
expect(prisma.medicationIntakeEvent.update).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: "row-raced" } }),
);
});
});
+91 -16
View File
@@ -47,6 +47,10 @@ import {
recomputeMedicationComplianceForDay,
dayKeyForScheduledFor,
} from "@/lib/rollups/medication-compliance-rollups";
import {
applyCanonicalSlotWrite,
resolveSlotInstantForWrite,
} from "@/lib/medications/scheduling/slot-upsert";
const MAX_ENTRIES_PER_BATCH = 500;
const BATCH_RATE_LIMIT_MAX = 60;
@@ -70,7 +74,12 @@ const bulkPayloadSchema = z.object({
entries: z.array(bulkEntrySchema).min(1).max(MAX_ENTRIES_PER_BATCH),
});
type EntryStatus = "inserted" | "duplicate" | "skipped";
// v1.8.2 — `updated` joins the per-entry status vocabulary: a write that
// snaps onto an existing scheduled-slot row (e.g. the pending REMINDER
// row) updates it in place rather than inserting. The iOS sync engine
// treats `updated` the same as `inserted` for cursor advancement — both
// mean "the server accepted this entry and produced a row id".
type EntryStatus = "inserted" | "updated" | "duplicate" | "skipped";
interface EntryResult {
index: number;
status: EntryStatus;
@@ -154,6 +163,7 @@ async function postBulk(request: NextRequest): Promise<Response> {
const results: EntryResult[] = [];
let inserted = 0;
let updated = 0;
let duplicates = 0;
const skipped: Array<{ index: number; reason: string }> = [];
// v1.4.39 W-MED — collect distinct `(medicationId, dayKey)` pairs
@@ -173,31 +183,93 @@ async function postBulk(request: NextRequest): Promise<Response> {
}
try {
const scheduledFor = entry.scheduledFor ?? new Date();
// The idempotencyKey, when supplied, has a UNIQUE index. A
// re-submission of the same key returns the existing row via
// P2002 → status: "duplicate".
const row = await prisma.medicationIntakeEvent.create({
data: {
const incomingScheduledFor =
entry.scheduledFor ?? entry.takenAt ?? new Date();
// v1.8.2 — source-agnostic slot snap. iOS posts the "Genommen"
// reminder action here (source API); without this it inserted a
// SECOND row for a slot already carrying the projector/worker's
// pending REMINDER row (the unique key includes `source`, and the
// iOS-vs-server `scheduledFor` drifts by a minute). Snap onto the
// canonical slot instant and update the existing row in place.
const canonicalSlot = await resolveSlotInstantForWrite({
userId: user.id,
medicationId: entry.medicationId,
userTz: user.timezone,
incoming: incomingScheduledFor,
});
const scheduledFor = canonicalSlot ?? incomingScheduledFor;
// C2 — classify the incoming write. An offline-sync replay echoes a
// PENDING projection (no `takenAt`, `skipped:false`) for a slot the
// user may already have actioned; that echo must NEVER clear a
// recorded `takenAt`. An explicit `takenAt` or `skipped:true` is a
// real user action and applies last-write-wins.
const isExplicitTaken = !entry.skipped && entry.takenAt !== undefined;
const isExplicitSkip = entry.skipped === true;
if (canonicalSlot) {
// Scheduled dose — converge onto the one canonical slot row through
// the shared upsert: H1 deterministic selection, C2 no-downgrade
// guard, and a C1 race-safe create that re-finds + updates on a
// P2002 collision rather than misclassifying it as a duplicate and
// dropping the dose.
const applied = await applyCanonicalSlotWrite({
client: prisma,
userId: user.id,
medicationId: entry.medicationId,
scheduledFor,
canonicalSlot,
takenAt: entry.takenAt ?? null,
skipped: entry.skipped,
source: "API",
isExplicitTaken,
isExplicitSkip,
idempotencyKey: entry.idempotencyKey ?? null,
},
});
inserted += 1;
results.push({ index: i, status: "inserted", id: row.id });
createSource: "API",
});
if (applied.noDowngradeNoOp) {
// C2 — pending echo onto an already-actioned slot. Report it as a
// duplicate so the iOS cursor advances WITHOUT downgrading the
// recorded dose.
duplicates += 1;
results.push({ index: i, status: "duplicate", id: applied.row.id });
} else if (applied.outcome === "updated") {
updated += 1;
results.push({ index: i, status: "updated", id: applied.row.id });
} else {
inserted += 1;
results.push({ index: i, status: "inserted", id: applied.row.id });
}
} else {
// Unscheduled / PRN — insert. The idempotencyKey, when supplied,
// has a UNIQUE index; a re-submission returns the existing row via
// P2002 → status: "duplicate".
const row = await prisma.medicationIntakeEvent.create({
data: {
userId: user.id,
medicationId: entry.medicationId,
scheduledFor,
takenAt: entry.takenAt ?? null,
skipped: entry.skipped,
source: "API",
idempotencyKey: entry.idempotencyKey ?? null,
},
});
inserted += 1;
results.push({ index: i, status: "inserted", id: row.id });
}
const dayKey = dayKeyForScheduledFor(scheduledFor, user.timezone);
touchedDays.set(`${entry.medicationId}|${dayKey}`, {
medicationId: entry.medicationId,
dayKey,
});
} catch (err: unknown) {
// P2002 = unique-constraint violation; the idempotencyKey
// already exists → "duplicate", not an error.
// P2002 = unique-constraint violation. Two shapes reach here:
// 1. an idempotencyKey collision on the unscheduled/PRN insert →
// "duplicate" (the canonical-slot path already absorbs its own
// same-slot P2002 race inside `applyCanonicalSlotWrite`);
// 2. a same-slot collision on the unscheduled insert. In both
// cases we surface the existing row id so the cursor advances.
if (
typeof err === "object" &&
err !== null &&
@@ -231,6 +303,7 @@ async function postBulk(request: NextRequest): Promise<Response> {
details: {
processed: entries.length,
inserted,
updated,
duplicates,
skipped: skipped.length,
},
@@ -241,6 +314,7 @@ async function postBulk(request: NextRequest): Promise<Response> {
meta: {
processed: entries.length,
inserted,
updated,
duplicates,
skipped: skipped.length,
},
@@ -249,7 +323,7 @@ async function postBulk(request: NextRequest): Promise<Response> {
// v1.4.34 IW-G — bust per-user medications + compliance + achievement
// caches when at least one row landed so the next read reflects the
// ingested batch.
if (inserted > 0) {
if (inserted > 0 || updated > 0) {
invalidateUserMedications(user.id);
}
@@ -282,6 +356,7 @@ async function postBulk(request: NextRequest): Promise<Response> {
return apiSuccess({
processed: entries.length,
inserted,
updated,
duplicates,
skipped,
entries: results,
@@ -0,0 +1,131 @@
import { describe, it, expect } from "vitest";
import { readFileSync, readdirSync, statSync } from "node:fs";
import { join } from "node:path";
/**
* v1.8.0 — explainer-metric key guard.
*
* `<MetricExplainer>` builds its i18n lookups from a template literal:
*
* t(`insights.subPage.explainer.${metric}Title`)
* t(`insights.subPage.explainer.${metric}Body`)
*
* The static `i18n-call-site-coverage.test.ts` only sees literal
* `t("…")` calls, so a typo in an `explainerMetric=` prop would resolve
* to a missing key and paint the raw key string into the popover — with
* no CI signal. This test closes that gap the same way the
* Health-Score provenance key tests pin their dynamic keys: it walks
* every `explainerMetric="…"` value used under `src/app/insights/**`
* (plus the shared `healthkit-metric-page` scaffold) and asserts that
* both the `<value>Title` and `<value>Body` leaves exist in
* `messages/en.json`. `i18n-locale-integrity.test.ts` then propagates
* the EN guarantee across the other five locales.
*/
const ROOT = join(__dirname, "../../../..");
const INSIGHTS_DIR = join(ROOT, "src/app/insights");
const HEALTHKIT_PAGE = join(
ROOT,
"src/components/insights/healthkit-metric-page.tsx",
);
const EN_BUNDLE_PATH = join(ROOT, "messages/en.json");
function walk(dir: string, out: string[] = []): string[] {
for (const name of readdirSync(dir)) {
const p = join(dir, name);
if (statSync(p).isDirectory()) {
if (name === "__tests__") continue;
walk(p, out);
} else if (name.endsWith(".tsx")) {
out.push(p);
}
}
return out;
}
interface PropSite {
value: string;
file: string;
line: number;
}
// Match `explainerMetric="someValue"` — a string-literal prop. The
// component contract only accepts a static string, so a dynamic
// `explainerMetric={expr}` would be a different (and unverifiable)
// shape; none exist in the tree and we assert that below.
const LITERAL_PATTERN = /explainerMetric="([a-zA-Z][a-zA-Z0-9]*)"/g;
const DYNAMIC_PATTERN = /explainerMetric=\{/;
function collectSites(): { sites: PropSite[]; dynamic: PropSite[] } {
const files = [...walk(INSIGHTS_DIR), HEALTHKIT_PAGE];
const sites: PropSite[] = [];
const dynamic: PropSite[] = [];
for (const file of files) {
const lines = readFileSync(file, "utf8").split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// The scaffold declares + forwards the prop; ignore the type
// declaration + the pass-through (`explainerMetric={explainerMetric}`)
// — those are not call sites that pin a concrete key.
if (file === HEALTHKIT_PAGE) continue;
let m: RegExpExecArray | null;
LITERAL_PATTERN.lastIndex = 0;
while ((m = LITERAL_PATTERN.exec(line)) !== null) {
sites.push({ value: m[1], file: file.slice(ROOT.length + 1), line: i + 1 });
}
if (DYNAMIC_PATTERN.test(line)) {
dynamic.push({ value: line.trim(), file: file.slice(ROOT.length + 1), line: i + 1 });
}
}
}
return { sites, dynamic };
}
function hasLeaf(obj: unknown, dotted: string): boolean {
let cur: unknown = obj;
for (const part of dotted.split(".")) {
if (cur && typeof cur === "object" && part in (cur as Record<string, unknown>)) {
cur = (cur as Record<string, unknown>)[part];
} else {
return false;
}
}
return typeof cur === "string";
}
describe("insights explainerMetric key coverage", () => {
const en = JSON.parse(readFileSync(EN_BUNDLE_PATH, "utf8"));
const { sites, dynamic } = collectSites();
it("finds explainerMetric props across the insights pages", () => {
// Guards against the walker silently matching nothing (e.g. a refactor
// that renames the prop). The category surface carries dozens of pages.
expect(sites.length).toBeGreaterThan(20);
});
it("uses only string-literal explainerMetric props (no dynamic expressions)", () => {
// A dynamic value can't be statically verified against the bundle, so
// the contract is literal-only. If this ever fails, either inline the
// literal or extend this guard to resolve the expression.
expect(dynamic).toEqual([]);
});
it("every explainerMetric value resolves a Title + Body leaf in messages/en.json", () => {
const missing: string[] = [];
for (const site of sites) {
const titleKey = `insights.subPage.explainer.${site.value}Title`;
const bodyKey = `insights.subPage.explainer.${site.value}Body`;
if (!hasLeaf(en, titleKey)) {
missing.push(` ❌ ${titleKey} (${site.file}:${site.line})`);
}
if (!hasLeaf(en, bodyKey)) {
missing.push(` ❌ ${bodyKey} (${site.file}:${site.line})`);
}
}
if (missing.length > 0) {
throw new Error(
`Found ${missing.length} explainerMetric key(s) missing from messages/en.json:\n${missing.join("\n")}`,
);
}
});
});
@@ -5,7 +5,7 @@ import { Flame } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.4.32 — `/insights/aktive-energie`.
* v1.4.32 — `/insights/active-energy`.
*
* Active-energy-burned sub-page. The MeasurementType is cumulative
* (kcal per day, per R-A Option A); the v1.4.30 server-side daily-
@@ -20,6 +20,7 @@ export default function InsightsActiveEnergyPage() {
insightMetric="ACTIVE_ENERGY_BURNED"
chartKey="activeEnergy"
i18nPrefix="insights.activeEnergy"
explainerMetric="activeEnergy"
color="#ffb86c"
unit="kcal"
yAxisUnit="kcal"
@@ -5,7 +5,7 @@ import { Volume2 } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/laermereignisse`.
* v1.7.0 — `/insights/audio-events`.
*
* AUDIO_EXPOSURE_EVENT sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsLaermereignissePage() {
insightMetric="AUDIO_EXPOSURE_EVENT"
chartKey="audioExposureEvent"
i18nPrefix="insights.audioExposureEvent"
explainerMetric="audioEvents"
color="#ff79c6"
unit=""
yAxisUnit=""
@@ -5,7 +5,7 @@ import { Droplet } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/blutzucker`.
* v1.7.0 — `/insights/blood-glucose`.
*
* BLOOD_GLUCOSE sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsBlutzuckerPage() {
insightMetric="BLOOD_GLUCOSE"
chartKey="bloodGlucose"
i18nPrefix="insights.bloodGlucose"
explainerMetric="bloodGlucose"
color="#ff79c6"
unit="mg/dL"
yAxisUnit="mg/dL"
@@ -13,11 +13,12 @@ import { HealthChartDynamic } from "@/components/charts/health-chart-dynamic";
import { CoachLaunchButton } from "@/components/insights/coach-launch-button";
import { InsightStatusCard } from "@/components/insights/insight-status-card";
import { MetricEmptyState } from "@/components/insights/metric-empty-state";
import { MetricTargetSummary } from "@/components/insights/metric-target-summary";
import { SubPageShell } from "@/components/insights/sub-page-shell";
import { getBpTargets } from "@/lib/analytics/bp-targets";
/**
* v1.4.25 W4 — `/insights/blutdruck`.
* v1.4.25 W4 — `/insights/blood-pressure`.
*
* Routed Blood-Pressure sub-page. The mother page hosts the overview
* (hero + briefing + advisor); this page concentrates on BP-only depth:
@@ -51,6 +52,7 @@ export default function InsightsBlutdruckPage() {
<SubPageShell
title={t("insights.bloodPressureSectionTitle")}
description={t("insights.subPage.blutdruckDescription")}
explainerMetric="bloodPressure"
>
<MetricEmptyState
icon={<HeartPulse className="size-6" />}
@@ -98,6 +100,7 @@ export default function InsightsBlutdruckPage() {
<SubPageShell
title={t("insights.bloodPressureSectionTitle")}
description={t("insights.subPage.blutdruckDescription")}
explainerMetric="bloodPressure"
>
<HealthChartDynamic
chartKey="bp"
@@ -111,6 +114,8 @@ export default function InsightsBlutdruckPage() {
userTimezone={user?.timezone}
/>
<MetricTargetSummary slug="blood-pressure" />
<InsightStatusCard
title={t("insights.assessmentTitle")}
icon={<HeartPulse className="h-5 w-5" />}
@@ -119,6 +124,7 @@ export default function InsightsBlutdruckPage() {
cached={status?.cached ?? false}
updatedAt={status?.updatedAt ?? null}
loading={isStatusLoading}
preparing={status?.preparing ?? false}
/>
<CoachLaunchButton />
+7
View File
@@ -14,6 +14,7 @@ import { HealthChartDynamic } from "@/components/charts/health-chart-dynamic";
import { CoachLaunchButton } from "@/components/insights/coach-launch-button";
import { InsightStatusCard } from "@/components/insights/insight-status-card";
import { MetricEmptyState } from "@/components/insights/metric-empty-state";
import { MetricTargetSummary } from "@/components/insights/metric-target-summary";
import { SubPageShell } from "@/components/insights/sub-page-shell";
/**
@@ -58,6 +59,7 @@ export default function InsightsBmiPage() {
<SubPageShell
title={t("insights.bmiSectionTitle")}
description={t("insights.subPage.bmiDescription")}
explainerMetric="bmi"
>
<MetricEmptyState
icon={<Ruler className="size-6" />}
@@ -81,6 +83,7 @@ export default function InsightsBmiPage() {
<SubPageShell
title={t("insights.bmiSectionTitle")}
description={t("insights.subPage.bmiDescription")}
explainerMetric="bmi"
>
<EmptyState
icon={<Ruler className="size-6" />}
@@ -106,6 +109,7 @@ export default function InsightsBmiPage() {
<SubPageShell
title={t("insights.bmiSectionTitle")}
description={t("insights.subPage.bmiDescription")}
explainerMetric="bmi"
>
<HealthChartDynamic
chartKey="bmi"
@@ -119,6 +123,8 @@ export default function InsightsBmiPage() {
userTimezone={user?.timezone}
/>
<MetricTargetSummary slug="bmi" />
<InsightStatusCard
title={t("insights.assessmentTitle")}
icon={<Ruler className="h-5 w-5" />}
@@ -127,6 +133,7 @@ export default function InsightsBmiPage() {
cached={status?.cached ?? false}
updatedAt={status?.updatedAt ?? null}
loading={isStatusLoading}
preparing={status?.preparing ?? false}
/>
<CoachLaunchButton />
@@ -5,7 +5,7 @@ import { Thermometer } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.4.32 — `/insights/koerpertemperatur`.
* v1.4.32 — `/insights/body-temperature`.
*
* Body-temperature sub-page. Canonical storage is Celsius. Distinct
* from skin temperature (Withings ScanWatch dermal reading) — surface
@@ -19,6 +19,7 @@ export default function InsightsBodyTemperaturePage() {
insightMetric="BODY_TEMPERATURE"
chartKey="bodyTemperature"
i18nPrefix="insights.bodyTemperature"
explainerMetric="bodyTemperature"
color="#ff79c6"
unit="°C"
yAxisUnit="°C"
@@ -5,7 +5,7 @@ import { Droplet } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/koerperwasser`.
* v1.7.0 — `/insights/body-water`.
*
* TOTAL_BODY_WATER sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsKoerperwasserPage() {
insightMetric="TOTAL_BODY_WATER"
chartKey="totalBodyWater"
i18nPrefix="insights.totalBodyWater"
explainerMetric="bodyWater"
color="#8be9fd"
unit="kg"
yAxisUnit="kg"
@@ -5,7 +5,7 @@ import { Bone } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/knochenmasse`.
* v1.7.0 — `/insights/bone-mass`.
*
* BONE_MASS sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsKnochenmassePage() {
insightMetric="BONE_MASS"
chartKey="boneMass"
i18nPrefix="insights.boneMass"
explainerMetric="boneMass"
color="#ffb86c"
unit="kg"
yAxisUnit="kg"
@@ -5,7 +5,7 @@ import { Sun } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/tageslicht`.
* v1.7.0 — `/insights/daylight`.
*
* TIME_IN_DAYLIGHT sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsTageslichtPage() {
insightMetric="TIME_IN_DAYLIGHT"
chartKey="timeInDaylight"
i18nPrefix="insights.timeInDaylight"
explainerMetric="daylight"
color="#50fa7b"
unit="min"
yAxisUnit="min"
@@ -5,7 +5,7 @@ import { Footprints } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/doppelstandphase`.
* v1.7.0 — `/insights/double-support-time`.
*
* WALKING_DOUBLE_SUPPORT sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsDoppelstandphasePage() {
insightMetric="WALKING_DOUBLE_SUPPORT"
chartKey="walkingDoubleSupport"
i18nPrefix="insights.walkingDoubleSupport"
explainerMetric="doubleSupportTime"
color="#50fa7b"
unit="%"
yAxisUnit="%"
@@ -5,7 +5,7 @@ import { Volume2 } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/laermbelastung`.
* v1.7.0 — `/insights/environmental-audio`.
*
* AUDIO_EXPOSURE_ENV sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsLaermbelastungPage() {
insightMetric="AUDIO_EXPOSURE_ENV"
chartKey="audioExposureEnv"
i18nPrefix="insights.audioExposureEnv"
explainerMetric="environmentalAudio"
color="#ff79c6"
unit="dBA"
yAxisUnit="dBA"
@@ -5,7 +5,7 @@ import { Scale } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/fettfreie-masse`.
* v1.7.0 — `/insights/fat-free-mass`.
*
* FAT_FREE_MASS sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsFettfreieMassePage() {
insightMetric="FAT_FREE_MASS"
chartKey="fatFreeMass"
i18nPrefix="insights.fatFreeMass"
explainerMetric="fatFreeMass"
color="#bd93f9"
unit="kg"
yAxisUnit="kg"
@@ -5,7 +5,7 @@ import { Droplets } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/fettmasse`.
* v1.7.0 — `/insights/fat-mass`.
*
* FAT_MASS sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsFettmassePage() {
insightMetric="FAT_MASS"
chartKey="fatMass"
i18nPrefix="insights.fatMass"
explainerMetric="fatMass"
color="#ffb86c"
unit="kg"
yAxisUnit="kg"
@@ -5,7 +5,7 @@ import { TrendingUp } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/stockwerke`.
* v1.7.0 — `/insights/flights-climbed`.
*
* FLIGHTS_CLIMBED sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsStockwerkePage() {
insightMetric="FLIGHTS_CLIMBED"
chartKey="flightsClimbed"
i18nPrefix="insights.flightsClimbed"
explainerMetric="flightsClimbed"
color="#50fa7b"
unit="flights"
yAxisUnit="flights"
@@ -5,7 +5,7 @@ import { Headphones } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/kopfhoererpegel`.
* v1.7.0 — `/insights/headphone-audio`.
*
* AUDIO_EXPOSURE_HEADPHONE sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsKopfhoererpegelPage() {
insightMetric="AUDIO_EXPOSURE_HEADPHONE"
chartKey="audioExposureHeadphone"
i18nPrefix="insights.audioExposureHeadphone"
explainerMetric="headphoneAudio"
color="#ff79c6"
unit="dBA"
yAxisUnit="dBA"
+1
View File
@@ -20,6 +20,7 @@ export default function InsightsHrvPage() {
insightMetric="HEART_RATE_VARIABILITY"
chartKey="hrv"
i18nPrefix="insights.hrv"
explainerMetric="hrv"
color="#bd93f9"
unit="ms"
yAxisUnit="ms"
@@ -5,7 +5,7 @@ import { Scale } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/magermasse`.
* v1.7.0 — `/insights/lean-body-mass`.
*
* LEAN_BODY_MASS sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsMagermassePage() {
insightMetric="LEAN_BODY_MASS"
chartKey="leanBodyMass"
i18nPrefix="insights.leanBodyMass"
explainerMetric="leanBodyMass"
color="#bd93f9"
unit="kg"
yAxisUnit="kg"
+37
View File
@@ -0,0 +1,37 @@
/**
* v1.8.3 — route-level loading skeleton for every `/insights/*` segment.
*
* Defense-in-depth for the navigation-freeze class: any RSC await on an
* insights route (now or in a future refactor) streams this skeleton
* instead of blocking the transition. The geometry mirrors `SubPageShell`
* (heading + chart card + assessment card) so the post-load swap reflows
* by less than a row. Pure server component — no client hooks, no data
* fetch; Next.js renders it instantly while the segment streams.
*/
export default function InsightsLoading() {
return (
<div data-slot="insights-subpage-loading" className="space-y-6">
<header className="space-y-2">
<div className="bg-muted h-7 w-48 animate-pulse rounded motion-reduce:animate-none" />
<div className="bg-muted/70 h-4 w-72 animate-pulse rounded motion-reduce:animate-none" />
</header>
{/* Chart card */}
<div className="bg-card rounded-xl border p-4">
<div className="bg-muted mb-4 h-4 w-32 animate-pulse rounded motion-reduce:animate-none" />
<div className="bg-muted/60 h-56 w-full animate-pulse rounded-lg motion-reduce:animate-none" />
</div>
{/* Assessment card */}
<div className="bg-card space-y-2 rounded-xl border p-4">
<div className="flex items-center gap-2">
<div className="bg-muted h-5 w-5 animate-pulse rounded motion-reduce:animate-none" />
<div className="bg-muted h-4 w-40 animate-pulse rounded motion-reduce:animate-none" />
</div>
<div className="bg-muted h-3.5 w-full animate-pulse rounded motion-reduce:animate-none" />
<div className="bg-muted h-3.5 w-11/12 animate-pulse rounded motion-reduce:animate-none" />
<div className="bg-muted h-3.5 w-9/12 animate-pulse rounded motion-reduce:animate-none" />
</div>
</div>
);
}
@@ -5,6 +5,7 @@ import Link from "next/link";
import { Loader2, Pill } from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { nextStatusPollInterval } from "@/hooks/use-insight-status";
import { queryKeys } from "@/lib/query-keys";
import { useTranslations } from "@/lib/i18n/context";
import { Badge } from "@/components/ui/badge";
@@ -15,12 +16,13 @@ import { Progress } from "@/components/ui/progress";
import { ComplianceHeatmap } from "@/components/charts/compliance-heatmap";
import { CoachLaunchButton } from "@/components/insights/coach-launch-button";
import { InsightStatusCard } from "@/components/insights/insight-status-card";
import { MetricTargetSummary } from "@/components/insights/metric-target-summary";
import { SubPageShell } from "@/components/insights/sub-page-shell";
import { TherapyTimeline } from "@/components/insights/therapy-timeline";
import { MedicationCardHeader } from "@/components/medications/MedicationCardHeader";
/**
* v1.4.25 W4 — `/insights/medikamente`.
* v1.4.25 W4 — `/insights/medications`.
*
* Routed Medication-Compliance sub-page. Mirrors the per-medication
* grid from the v1.4.24 mother page (compliance bars + heatmap +
@@ -57,8 +59,18 @@ interface MedicationComplianceStatusData {
medications: Array<{ medicationId: string; text: string }>;
cached: boolean;
updatedAt: string | null;
// v1.8.3 — read-only route returns preparing:true with summary:null on a
// cache miss while the worker warms the assessment; the card polls until
// it lands. See `use-insight-status.ts` for the shared rationale.
preparing?: boolean;
}
// v1.8.3 — client ceiling on the round-trip, mirroring the shared
// `use-insight-status` hook so the medication-compliance card never awaits
// an uncapped LLM round-trip on navigation. The preparing-poll cadence and
// its attempt ceiling come from the shared `nextStatusPollInterval` helper.
const MED_STATUS_TIMEOUT_MS = 8_000;
interface MedicationDailyData {
expected: number;
taken: number;
@@ -90,15 +102,34 @@ export default function InsightsMedikamentePage() {
const { data: status, isLoading: isStatusLoading } = useQuery({
queryKey: queryKeys.insightsMedicationComplianceStatus(locale),
queryFn: async () => {
const res = await fetch(
`/api/insights/medication-compliance-status?locale=${locale}`,
const controller = new AbortController();
const timeoutHandle = setTimeout(
() => controller.abort(),
MED_STATUS_TIMEOUT_MS,
);
if (!res.ok) throw new Error("Failed");
const json = await res.json();
return json.data as MedicationComplianceStatusData;
try {
const res = await fetch(
`/api/insights/medication-compliance-status?locale=${locale}`,
{ signal: controller.signal },
);
if (!res.ok) throw new Error("Failed");
const json = await res.json();
return json.data as MedicationComplianceStatusData;
} finally {
clearTimeout(timeoutHandle);
}
},
enabled: isAuthenticated,
staleTime: 60 * 1000,
retry: 0,
// v1.8.4 — bounded preparing poll: stop after the shared attempt
// ceiling so a persistently failing generation can't poll an open
// page forever.
refetchInterval: (query) =>
nextStatusPollInterval(
query.state.data?.preparing,
query.state.dataUpdateCount,
),
});
const medications = comprehensive?.medications ?? [];
@@ -111,7 +142,10 @@ export default function InsightsMedikamentePage() {
if (isComprehensiveLoading) {
return (
<SubPageShell title={t("insights.medicationCompliance")}>
<SubPageShell
title={t("insights.medicationCompliance")}
explainerMetric="medications"
>
<div className="flex items-center justify-center py-12">
<Loader2 className="text-primary h-6 w-6 animate-spin motion-reduce:animate-none" />
</div>
@@ -124,7 +158,10 @@ export default function InsightsMedikamentePage() {
// gate reads `medications.length > 0`. CTA targets `/medications`
// (the dedicated medication-management surface).
return (
<SubPageShell title={t("insights.medicationCompliance")}>
<SubPageShell
title={t("insights.medicationCompliance")}
explainerMetric="medications"
>
<EmptyState
icon={<Pill className="size-6" />}
title={t("insights.emptyState.medication.title")}
@@ -149,6 +186,7 @@ export default function InsightsMedikamentePage() {
<SubPageShell
title={t("insights.medicationCompliance")}
description={t("insights.subPage.medikamenteDescription")}
explainerMetric="medications"
>
<div
className={
@@ -158,7 +196,7 @@ export default function InsightsMedikamentePage() {
{medications.map((med) => {
const medicationSummary = medicationSummaryById.get(med.id);
// UI-H3 — route every medication-list row (medications page
// + insights/medikamente) through `<MedicationCardHeader>`
// + insights/medications) through `<MedicationCardHeader>`
// so the surface stays one shape: `{name} {dose}` on line 1
// + outline category badge on line 2. The streak chip rides
// the `stateBadges` slot so a strong streak still surfaces.
@@ -235,6 +273,8 @@ export default function InsightsMedikamentePage() {
})}
</div>
<MetricTargetSummary slug="medications" />
<InsightStatusCard
title={t("insights.assessmentTitle")}
icon={<Pill className="h-5 w-5" />}
@@ -243,6 +283,7 @@ export default function InsightsMedikamentePage() {
cached={status?.cached ?? false}
updatedAt={status?.updatedAt ?? null}
loading={isStatusLoading}
preparing={status?.preparing ?? false}
/>
{/* v1.4.25 W4d — GLP-1 therapy timeline. Self-hides for users
@@ -15,10 +15,11 @@ import { ChartSkeleton } from "@/components/charts/chart-skeleton";
import { CoachLaunchButton } from "@/components/insights/coach-launch-button";
import { InsightStatusCard } from "@/components/insights/insight-status-card";
import { MetricEmptyState } from "@/components/insights/metric-empty-state";
import { MetricTargetSummary } from "@/components/insights/metric-target-summary";
import { SubPageShell } from "@/components/insights/sub-page-shell";
/**
* v1.4.25 W4 — `/insights/stimmung`.
* v1.4.25 W4 — `/insights/mood`.
*
* Routed Mood sub-page. Unlike the mother page (which hid the mood
* section entirely when no mood data existed), a dedicated sub-page
@@ -75,6 +76,7 @@ export default function InsightsStimmungPage() {
<SubPageShell
title={t("insights.moodSectionTitle")}
description={t("insights.subPage.stimmungDescription")}
explainerMetric="mood"
>
<MetricEmptyState
icon={<Smile className="size-6" />}
@@ -95,6 +97,7 @@ export default function InsightsStimmungPage() {
<SubPageShell
title={t("insights.moodSectionTitle")}
description={t("insights.subPage.stimmungDescription")}
explainerMetric="mood"
>
<MoodChart
chartKey="mood"
@@ -102,6 +105,8 @@ export default function InsightsStimmungPage() {
userTimezone={user?.timezone}
/>
<MetricTargetSummary slug="mood" />
<InsightStatusCard
title={t("insights.assessmentTitle")}
icon={<Smile className="h-5 w-5" />}
@@ -110,6 +115,7 @@ export default function InsightsStimmungPage() {
cached={status?.cached ?? false}
updatedAt={status?.updatedAt ?? null}
loading={isStatusLoading}
preparing={status?.preparing ?? false}
/>
<CoachLaunchButton />
@@ -5,7 +5,7 @@ import { Dumbbell } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/muskelmasse`.
* v1.7.0 — `/insights/muscle-mass`.
*
* MUSCLE_MASS sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsMuskelmassePage() {
insightMetric="MUSCLE_MASS"
chartKey="muscleMass"
i18nPrefix="insights.muscleMass"
explainerMetric="muscleMass"
color="#bd93f9"
unit="kg"
yAxisUnit="kg"
@@ -5,7 +5,7 @@ import { Wind } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.4.32 — `/insights/sauerstoff`.
* v1.4.32 — `/insights/oxygen`.
*
* Oxygen-saturation (SpO₂) sub-page. Canonical storage is percent
* (0..100); the chart axis runs 85..100 because clinical normal is
@@ -21,6 +21,7 @@ export default function InsightsOxygenSaturationPage() {
insightMetric="OXYGEN_SATURATION"
chartKey="oxygenSaturation"
i18nPrefix="insights.oxygenSaturation"
explainerMetric="oxygenSaturation"
color="#8be9fd"
unit="%"
yAxisUnit="%"
@@ -5,7 +5,7 @@ import { Activity } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/pulswellengeschwindigkeit`.
* v1.7.0 — `/insights/pulse-wave-velocity`.
*
* PULSE_WAVE_VELOCITY sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsPulswellengeschwindigkeitPage() {
insightMetric="PULSE_WAVE_VELOCITY"
chartKey="pulseWaveVelocity"
i18nPrefix="insights.pulseWaveVelocity"
explainerMetric="pulseWaveVelocity"
color="#ff5555"
unit="m/s"
yAxisUnit="m/s"
@@ -13,6 +13,7 @@ import { HealthChartDynamic } from "@/components/charts/health-chart-dynamic";
import { CoachLaunchButton } from "@/components/insights/coach-launch-button";
import { InsightStatusCard } from "@/components/insights/insight-status-card";
import { MetricEmptyState } from "@/components/insights/metric-empty-state";
import { MetricTargetSummary } from "@/components/insights/metric-target-summary";
import { SubPageShell } from "@/components/insights/sub-page-shell";
import { Vo2MaxChartRow } from "@/components/insights/vo2-max-chart-row";
import {
@@ -21,7 +22,7 @@ import {
} from "@/lib/analytics/pulse-targets";
/**
* v1.4.25 W4 — `/insights/puls`.
* v1.4.25 W4 — `/insights/pulse`.
*
* Routed Pulse sub-page. Renders the pulse chart with the personalized
* Karvonen-derived target band plus the per-section AI assessment.
@@ -61,6 +62,7 @@ export default function InsightsPulsPage() {
<SubPageShell
title={t("insights.pulseSectionTitle")}
description={t("insights.subPage.pulsDescription")}
explainerMetric="pulse"
>
<MetricEmptyState
icon={<Heart className="size-6" />}
@@ -111,6 +113,7 @@ export default function InsightsPulsPage() {
<SubPageShell
title={t("insights.pulseSectionTitle")}
description={t("insights.subPage.pulsDescription")}
explainerMetric="pulse"
>
<HealthChartDynamic
chartKey="pulse"
@@ -123,6 +126,8 @@ export default function InsightsPulsPage() {
userTimezone={user?.timezone}
/>
<MetricTargetSummary slug="pulse" />
<InsightStatusCard
title={t("insights.assessmentTitle")}
icon={<Heart className="h-5 w-5" />}
@@ -131,6 +136,7 @@ export default function InsightsPulsPage() {
cached={status?.cached ?? false}
updatedAt={status?.updatedAt ?? null}
loading={isStatusLoading}
preparing={status?.preparing ?? false}
/>
{/* v1.4.25 W16a — VO2 max sits on the cardio sub-page because it
@@ -5,7 +5,7 @@ import { Wind } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/atemfrequenz`.
* v1.7.0 — `/insights/respiratory-rate`.
*
* RESPIRATORY_RATE sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsAtemfrequenzPage() {
insightMetric="RESPIRATORY_RATE"
chartKey="respiratoryRate"
i18nPrefix="insights.respiratoryRate"
explainerMetric="respiratoryRate"
color="#8be9fd"
unit="breaths/min"
yAxisUnit="breaths/min"
@@ -5,9 +5,9 @@ import { Heart } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.4.32 — `/insights/ruhepuls`.
* v1.4.32 — `/insights/resting-pulse`.
*
* Resting-heart-rate sub-page. Distinct from `/insights/puls` — Apple
* Resting-heart-rate sub-page. Distinct from `/insights/pulse` — Apple
* Health splits the steady-state daily `restingHeartRate` value from
* the spot `PULSE` samples logged manually or by Withings. The split
* here mirrors that distinction so the user has a "daily floor"
@@ -20,6 +20,7 @@ export default function InsightsRestingHrPage() {
insightMetric="RESTING_HEART_RATE"
chartKey="restingHr"
i18nPrefix="insights.restingHr"
explainerMetric="restingHr"
color="#ff5555"
unit="bpm"
yAxisUnit="bpm"
@@ -5,7 +5,7 @@ import { Thermometer } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/hauttemperatur`.
* v1.7.0 — `/insights/skin-temperature`.
*
* SKIN_TEMPERATURE sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsHauttemperaturPage() {
insightMetric="SKIN_TEMPERATURE"
chartKey="skinTemperature"
i18nPrefix="insights.skinTemperature"
explainerMetric="skinTemperature"
color="#ffb86c"
unit="°C"
yAxisUnit="°C"
@@ -8,11 +8,12 @@ import { useTranslations } from "@/lib/i18n/context";
import { Button } from "@/components/ui/button";
import { CoachLaunchButton } from "@/components/insights/coach-launch-button";
import { MetricEmptyState } from "@/components/insights/metric-empty-state";
import { MetricTargetSummary } from "@/components/insights/metric-target-summary";
import { SleepOverview } from "@/components/insights/sleep-overview";
import { SubPageShell } from "@/components/insights/sub-page-shell";
/**
* v1.4.25 W4c — `/insights/schlaf`.
* v1.4.25 W4c — `/insights/sleep`.
*
* The Sleep sub-page surfaces the per-stage breakdown + duration trend
* the v1.4.23 schema gained but never rendered. All charts live inside
@@ -37,6 +38,7 @@ export default function InsightsSchlafPage() {
<SubPageShell
title={t("insights.sleep.title")}
description={t("insights.sleep.description")}
explainerMetric="sleep"
>
<MetricEmptyState
icon={<Moon className="size-6" />}
@@ -59,9 +61,12 @@ export default function InsightsSchlafPage() {
<SubPageShell
title={t("insights.sleep.title")}
description={t("insights.sleep.description")}
explainerMetric="sleep"
>
<SleepOverview />
<MetricTargetSummary slug="sleep" />
{/*
v1.4.28 (BK-UI-StatusSchlaf) — the six sibling sub-pages all
mount `<InsightStatusCard>` underneath the chart so the user
@@ -5,7 +5,7 @@ import { Footprints } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/schrittlaenge`.
* v1.7.0 — `/insights/step-length`.
*
* WALKING_STEP_LENGTH sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsSchrittlaengePage() {
insightMetric="WALKING_STEP_LENGTH"
chartKey="walkingStepLength"
i18nPrefix="insights.walkingStepLength"
explainerMetric="stepLength"
color="#50fa7b"
unit="m"
yAxisUnit="m"
@@ -5,7 +5,7 @@ import { HeartPulse } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/gefaessalter`.
* v1.7.0 — `/insights/vascular-age`.
*
* VASCULAR_AGE sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsGefaessalterPage() {
insightMetric="VASCULAR_AGE"
chartKey="vascularAge"
i18nPrefix="insights.vascularAge"
explainerMetric="vascularAge"
color="#ff79c6"
unit="years"
yAxisUnit="years"
@@ -5,7 +5,7 @@ import { Droplets } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/viszeralfett`.
* v1.7.0 — `/insights/visceral-fat`.
*
* VISCERAL_FAT sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsViszeralfettPage() {
insightMetric="VISCERAL_FAT"
chartKey="visceralFat"
i18nPrefix="insights.visceralFat"
explainerMetric="visceralFat"
color="#ffb86c"
unit=""
yAxisUnit=""
@@ -5,7 +5,7 @@ import { Footprints } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/gangasymmetrie`.
* v1.7.0 — `/insights/walking-asymmetry`.
*
* WALKING_ASYMMETRY sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsGangasymmetriePage() {
insightMetric="WALKING_ASYMMETRY"
chartKey="walkingAsymmetry"
i18nPrefix="insights.walkingAsymmetry"
explainerMetric="walkingAsymmetry"
color="#50fa7b"
unit="%"
yAxisUnit="%"
@@ -5,7 +5,7 @@ import { Footprints } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/gehstrecke`.
* v1.7.0 — `/insights/walking-distance`.
*
* WALKING_RUNNING_DISTANCE sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsGehstreckePage() {
insightMetric="WALKING_RUNNING_DISTANCE"
chartKey="walkingRunningDistance"
i18nPrefix="insights.walkingRunningDistance"
explainerMetric="walkingDistance"
color="#50fa7b"
unit="km"
yAxisUnit="km"
@@ -5,7 +5,7 @@ import { HeartPulse } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/gehpuls`.
* v1.7.0 — `/insights/walking-heart-rate`.
*
* WALKING_HEART_RATE_AVERAGE sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsGehpulsPage() {
insightMetric="WALKING_HEART_RATE_AVERAGE"
chartKey="walkingHeartRateAverage"
i18nPrefix="insights.walkingHeartRateAverage"
explainerMetric="walkingHeartRate"
color="#ff5555"
unit="bpm"
yAxisUnit="bpm"
@@ -5,7 +5,7 @@ import { Gauge } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/gehgeschwindigkeit`.
* v1.7.0 — `/insights/walking-speed`.
*
* WALKING_SPEED sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsGehgeschwindigkeitPage() {
insightMetric="WALKING_SPEED"
chartKey="walkingSpeed"
i18nPrefix="insights.walkingSpeed"
explainerMetric="walkingSpeed"
color="#50fa7b"
unit="km/h"
yAxisUnit="km/h"
@@ -5,7 +5,7 @@ import { Gauge } from "lucide-react";
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
/**
* v1.7.0 — `/insights/gangstabilitaet`.
* v1.7.0 — `/insights/walking-steadiness`.
*
* WALKING_STEADINESS sub-page. Reuses the generic HealthKitMetricPage scaffold;
* the chart daily-aggregates through the rollup read path. Empty-state
@@ -19,6 +19,7 @@ export default function InsightsGangstabilitaetPage() {
insightMetric="WALKING_STEADINESS"
chartKey="walkingSteadiness"
i18nPrefix="insights.walkingSteadiness"
explainerMetric="walkingSteadiness"
color="#50fa7b"
unit="%"
yAxisUnit="%"
@@ -13,11 +13,12 @@ import { HealthChartDynamic } from "@/components/charts/health-chart-dynamic";
import { CoachLaunchButton } from "@/components/insights/coach-launch-button";
import { InsightStatusCard } from "@/components/insights/insight-status-card";
import { MetricEmptyState } from "@/components/insights/metric-empty-state";
import { MetricTargetSummary } from "@/components/insights/metric-target-summary";
import { SubPageShell } from "@/components/insights/sub-page-shell";
import { buildWeightBandsFromHeight } from "@/lib/analytics/value-bands";
/**
* v1.4.25 W4 — `/insights/gewicht`.
* v1.4.25 W4 — `/insights/weight`.
*
* Routed Weight sub-page. Renders the weight chart with the user's
* height-derived green/orange/red bands plus the per-section AI
@@ -43,6 +44,7 @@ export default function InsightsGewichtPage() {
<SubPageShell
title={t("insights.weightSectionTitle")}
description={t("insights.subPage.gewichtDescription")}
explainerMetric="weight"
>
<MetricEmptyState
icon={<Scale className="size-6" />}
@@ -72,6 +74,7 @@ export default function InsightsGewichtPage() {
<SubPageShell
title={t("insights.weightSectionTitle")}
description={t("insights.subPage.gewichtDescription")}
explainerMetric="weight"
>
<HealthChartDynamic
chartKey="weight"
@@ -84,6 +87,8 @@ export default function InsightsGewichtPage() {
userTimezone={user?.timezone}
/>
<MetricTargetSummary slug="weight" />
<InsightStatusCard
title={t("insights.assessmentTitle")}
icon={<Scale className="h-5 w-5" />}
@@ -92,6 +97,7 @@ export default function InsightsGewichtPage() {
cached={status?.cached ?? false}
updatedAt={status?.updatedAt ?? null}
loading={isStatusLoading}
preparing={status?.preparing ?? false}
/>
<CoachLaunchButton />
+1
View File
@@ -35,6 +35,7 @@ export default function InsightsWorkoutsPage() {
<SubPageShell
title={t("insights.workouts.title")}
description={t("insights.workouts.description")}
explainerMetric="workouts"
>
{isLoading ? (
<div data-slot="workouts-loading" className="space-y-2">
+24
View File
@@ -0,0 +1,24 @@
/**
* v1.8.3 — root-level loading skeleton (dashboard segment + any top-level
* route without its own `loading.tsx`).
*
* Defense-in-depth for the navigation-freeze class: a segment that streams
* paints this tile-grid skeleton instead of a blank frame. Pure server
* component — no client hooks, no data fetch. More specific segments (e.g.
* `/insights`) provide their own skeleton and take precedence.
*/
export default function RootLoading() {
return (
<div data-slot="dashboard-loading" className="space-y-6 p-4">
<div className="bg-muted h-7 w-44 animate-pulse rounded motion-reduce:animate-none" />
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="bg-card rounded-xl border p-4">
<div className="bg-muted mb-3 h-4 w-24 animate-pulse rounded motion-reduce:animate-none" />
<div className="bg-muted/60 h-24 w-full animate-pulse rounded-lg motion-reduce:animate-none" />
</div>
))}
</div>
</div>
);
}
+6
View File
@@ -48,6 +48,12 @@ interface Medication {
notificationsEnabled: boolean;
pausedAt: string | null;
lastTakenAt: string | null;
/**
* v1.8.4 — server-computed next due instant (canonical recurrence
* engine). Threaded straight through to both card variants, which render
* it instead of re-deriving the timestamp client-side.
*/
nextDueAt?: string | null;
/** v1.5 — medication-level course start date (ISO string). */
startsOn?: string | null;
/** v1.5 — medication-level course end date (ISO string). */
@@ -0,0 +1,151 @@
import { describe, it, expect } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider, useTranslations } from "@/lib/i18n/context";
import { MetricExplainer } from "../metric-explainer";
/**
* v1.8.0 — `<MetricExplainer>` unit tests.
*
* The explainer is the `?` glyph next to a metric sub-page heading that
* opens a static "What is X?" read on tap / Enter / Space. Tests run
* through SSR so they don't depend on a browser surface: the trigger
* button is always present, the popover / sheet body mounts only after
* the user activates it. The load-bearing constraints pinned here are
* the a11y contract (real button, labelled, disclosure semantics, 44 px
* hit surface) and that every locale ships the title + body copy.
*/
function ssr(node: React.ReactNode, locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
);
}
/**
* Probe that resolves the explainer keys through the same `t()` calls
* the component uses, so a dropped locale key fails here at the call
* site instead of silently rendering the literal key path on the page.
*/
function KeyProbe({ metric }: { metric: string }) {
const { t } = useTranslations();
return (
<div>
<span data-slot="probe-title">
{t(`insights.subPage.explainer.${metric}Title`)}
</span>
<span data-slot="probe-body">
{t(`insights.subPage.explainer.${metric}Body`)}
</span>
</div>
);
}
// v1.8.0 — English key segments (ADR-0001). Every routed insights
// category page now passes one of these; the explainer copy ships in
// all six locales.
const METRICS = [
"bloodPressure",
"pulse",
"weight",
"bmi",
"sleep",
"mood",
"medications",
"restingHr",
"hrv",
"oxygenSaturation",
"bodyTemperature",
"activeEnergy",
"workouts",
"respiratoryRate",
"bodyWater",
"boneMass",
"fatFreeMass",
"fatMass",
"muscleMass",
"visceralFat",
"leanBodyMass",
"flightsClimbed",
"walkingDistance",
"walkingSteadiness",
"walkingHeartRate",
"walkingAsymmetry",
"doubleSupportTime",
"stepLength",
"walkingSpeed",
"pulseWaveVelocity",
"vascularAge",
"environmentalAudio",
"headphoneAudio",
"audioEvents",
"daylight",
"bloodGlucose",
"skinTemperature",
] as const;
describe("<MetricExplainer>", () => {
it("renders an icon-only trigger button with a metric-specific accessible label (EN)", () => {
const html = ssr(<MetricExplainer metric="bloodPressure" />);
const trigger = html.match(
/<button[^>]*data-slot="metric-explainer-trigger"[^>]*>/,
);
expect(trigger).not.toBeNull();
expect(trigger?.[0]).toContain('aria-label="What is Blood pressure?"');
});
it("lifts the tap target to the 44 px WCAG 2.5.5 floor", () => {
// The glyph stays 14 px but the click surface inflates to 44 px via
// `min-h-11 min-w-11`; the surrounding heading row keeps its stride
// because `-my-3 -mx-2` swallows the extra reach. Pinned so a future
// refactor can't collapse the hit surface back to the visual chip.
const html = ssr(<MetricExplainer metric="pulse" />);
const trigger = html.match(
/<button[^>]*data-slot="metric-explainer-trigger"[^>]*>/,
);
expect(trigger?.[0]).toContain("min-h-11");
expect(trigger?.[0]).toContain("min-w-11");
});
it("threads disclosure semantics onto the trigger button", () => {
const html = ssr(<MetricExplainer metric="hrv" />);
const trigger = html.match(
/<button[^>]*data-slot="metric-explainer-trigger"[^>]*>/,
);
expect(trigger?.[0]).toContain("aria-expanded");
expect(trigger?.[0]).toContain("aria-controls");
});
it("does not paint the popover/sheet body on the initial SSR snapshot", () => {
// Closed-by-default: the body lives in a portal that mounts after
// the user activates the trigger. Pinning the negative keeps a
// future "open on render" refactor from leaking copy into the
// static markup.
const html = ssr(<MetricExplainer metric="weight" />);
expect(html).not.toContain('data-slot="metric-explainer-body"');
expect(html).not.toContain('data-slot="metric-explainer-title"');
});
it("localises the trigger label in German", () => {
const html = ssr(<MetricExplainer metric="sleep" />, "de");
const trigger = html.match(
/<button[^>]*data-slot="metric-explainer-trigger"[^>]*>/,
);
expect(trigger?.[0]).toContain('aria-label="Was ist Schlaf?"');
});
it("ships the title + body copy for every category metric in every locale", () => {
for (const locale of ["en", "de", "fr", "es", "it", "pl"] as const) {
for (const metric of METRICS) {
const html = renderToStaticMarkup(
<I18nProvider initialLocale={locale}>
<KeyProbe metric={metric} />
</I18nProvider>,
);
// A missing key surfaces as the literal `insights.subPage…`
// path, which never contains a space.
expect(html).not.toContain(`insights.subPage.explainer.${metric}`);
}
}
});
});
@@ -0,0 +1,128 @@
import { describe, it, expect, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
/**
* v1.8.0 — `<MetricTargetSummary>` unit tests.
*
* The card surfaces the numeric target range + the in-target share on
* each insights category page, reading the same `/api/insights/targets`
* payload that powers `/targets`. The component depends on `useAuth`
* (gate) and TanStack Query (`useQuery`) for the payload, so both are
* mocked here and the assertions run through SSR — the load-bearing
* behaviour is the range/share rendering + the slug→type mapping, not
* the live fetch.
*/
vi.mock("@/hooks/use-auth", () => ({
useAuth: vi.fn(() => ({ isAuthenticated: true, user: null })),
}));
const useQueryMock = vi.fn();
vi.mock("@tanstack/react-query", () => ({
useQuery: (opts: unknown) => useQueryMock(opts),
}));
const { MetricTargetSummary } = await import("../metric-target-summary");
interface TargetsFixture {
targets: Array<{
type: string;
current: number | null;
unit: string;
range: { min: number; max: number } | null;
daysInRange30d: number;
daysLogged30d: number;
insufficientData: boolean;
}>;
bpDiastolic: { current: number | null; range: { min: number; max: number } | null };
}
function renderWith(slug: string, data: TargetsFixture | undefined) {
useQueryMock.mockReturnValue({ data });
return renderToStaticMarkup(
<I18nProvider initialLocale="en">
<MetricTargetSummary slug={slug} />
</I18nProvider>,
);
}
const WEIGHT_DATA: TargetsFixture = {
targets: [
{
type: "WEIGHT",
current: 72,
unit: "kg",
range: { min: 60.1, max: 80.9 },
daysInRange30d: 18,
daysLogged30d: 24,
insufficientData: false,
},
],
bpDiastolic: { current: null, range: null },
};
const BP_DATA: TargetsFixture = {
targets: [
{
type: "BLOOD_PRESSURE",
current: 124,
unit: "mmHg",
range: { min: 120, max: 129 },
daysInRange30d: 10,
daysLogged30d: 20,
insufficientData: false,
},
],
bpDiastolic: { current: 78, range: { min: 70, max: 79 } },
};
describe("<MetricTargetSummary>", () => {
it("renders the numeric range + in-target share for a simple metric", () => {
const html = renderWith("weight", WEIGHT_DATA);
// Trailing `.0` trimmed, single-decimal kept.
expect(html).toContain("Target: 60.1–80.9 kg");
// round(18/24*100) = 75
expect(html).toContain("75% of logged days within target");
});
it("stitches the systolic + diastolic bands for blood pressure", () => {
const html = renderWith("blood-pressure", BP_DATA);
expect(html).toContain("Target: 120–129 / 70–79 mmHg");
expect(html).toContain("50% of logged days within target");
});
it("renders the adjust-target link to /targets", () => {
const html = renderWith("weight", WEIGHT_DATA);
expect(html).toContain('href="/targets"');
expect(html).toContain("Adjust target range");
});
it("suppresses the share when the route flags insufficient data", () => {
const html = renderWith("weight", {
...WEIGHT_DATA,
targets: [{ ...WEIGHT_DATA.targets[0], insufficientData: true }],
});
expect(html).toContain("Target: 60.1–80.9 kg");
expect(html).not.toContain("of logged days within target");
});
it("renders nothing for a slug without a numeric target", () => {
const html = renderWith("hrv", undefined);
expect(html).toBe("");
});
it("renders nothing before the payload resolves", () => {
const html = renderWith("weight", undefined);
expect(html).toBe("");
});
it("renders nothing when the matching target has no range", () => {
const html = renderWith("weight", {
...WEIGHT_DATA,
targets: [{ ...WEIGHT_DATA.targets[0], range: null }],
});
expect(html).toBe("");
});
});
@@ -47,7 +47,30 @@ describe("<SubPageShell>", () => {
</SubPageShell>,
);
// The shell uses a `<p>` for the description; no `<p>` appears when
// the description prop is absent.
// neither a description nor an explainer metric is supplied.
expect(html).not.toMatch(/<p[^>]*class="text-muted-foreground/);
});
it("renders the explainer body inline beneath the heading", () => {
const html = render(
<SubPageShell title="Blood pressure" explainerMetric="bloodPressure">
<span />
</SubPageShell>,
);
// The inline caption reuses the same body string the `?` popover reads.
expect(html).toMatch(/data-slot="metric-explainer-inline"/);
expect(html).toContain(
"Blood pressure is the force your blood exerts on the artery walls",
);
});
it("keeps the explainer trigger glyph when explainerMetric is set", () => {
const html = render(
<SubPageShell title="Blood pressure" explainerMetric="bloodPressure">
<span />
</SubPageShell>,
);
// The `?` glyph stays available alongside the inline caption.
expect(html).toMatch(/data-slot="metric-explainer-trigger"/);
});
});
+8 -8
View File
@@ -39,23 +39,23 @@ import type {
* through to `null` and render as a plain row (no link wrap).
*/
const METRIC_HREF: Record<DailyBriefingKeyFinding["sourceMetric"], string | null> = {
bp: "/insights/blutdruck",
weight: "/insights/gewicht",
pulse: "/insights/puls",
mood: "/insights/stimmung",
compliance: "/insights/medikamente",
bp: "/insights/blood-pressure",
weight: "/insights/weight",
pulse: "/insights/pulse",
mood: "/insights/mood",
compliance: "/insights/medications",
// Apple Health / GLP-1 additive metrics — no dedicated sub-page yet.
// They render as static rows; v1.4.28 can wire each as they ship.
hrv: null,
sleep: "/insights/schlaf",
sleep: "/insights/sleep",
resting_hr: null,
steps: null,
active_energy: null,
flights: null,
distance: null,
vo2_max: "/insights/puls",
vo2_max: "/insights/pulse",
body_temp: null,
glp1_plateau: "/insights/medikamente",
glp1_plateau: "/insights/medications",
};
/**
@@ -80,6 +80,12 @@ export interface HealthKitMetricPageProps {
* (identity) so every existing page renders unchanged.
*/
valueScale?: number;
/**
* v1.8.0 — metric key threaded into `<SubPageShell explainerMetric>`
* so the `?` heading glyph opens the static "What is X?" explainer.
* Resolves `insights.subPage.explainer.<explainerMetric>{Title,Body}`.
*/
explainerMetric?: string;
}
export function HealthKitMetricPage({
@@ -95,6 +101,7 @@ export function HealthKitMetricPage({
emptyStateIcon,
coachPrefill,
valueScale,
explainerMetric,
}: HealthKitMetricPageProps) {
const { user, isAuthenticated } = useAuth();
const { t } = useTranslations();
@@ -115,7 +122,11 @@ export function HealthKitMetricPage({
</Button>
) : null;
return (
<SubPageShell title={title} description={description}>
<SubPageShell
title={title}
description={description}
explainerMetric={explainerMetric}
>
<MetricEmptyState
icon={emptyStateIcon}
title={t(`${i18nPrefix}.emptyState.title`)}
@@ -128,7 +139,11 @@ export function HealthKitMetricPage({
}
return (
<SubPageShell title={title} description={description}>
<SubPageShell
title={title}
description={description}
explainerMetric={explainerMetric}
>
<HealthChartDynamic
chartKey={chartKey}
types={[measurementType]}
@@ -18,6 +18,13 @@ interface InsightStatusCardProps {
cached: boolean;
updatedAt: string | null;
loading?: boolean;
/**
* v1.8.3 — the read-only status route enqueued an out-of-band generation
* and the assessment isn't warm yet. Render the same skeleton geometry as
* `loading` but with a "preparing" caption so the user understands the
* card is being assembled, not stuck. The client polls until text lands.
*/
preparing?: boolean;
}
// ─── Main Component ───────────────────────────────────────
@@ -30,6 +37,7 @@ export function InsightStatusCard({
cached,
updatedAt,
loading = false,
preparing = false,
}: InsightStatusCardProps) {
const { t } = useTranslations();
const flags = useFeatureFlags();
@@ -38,6 +46,36 @@ export function InsightStatusCard({
// suppressed in full so the layout collapses naturally.
if (!flags.insightStatus) return null;
// v1.8.3 — preparing: the read-only route enqueued a generation and the
// client is polling. Render the loading skeleton geometry with a
// preparing caption so the card reads as "assembling", not stuck. Only
// shown when a provider is configured (the route returns the no-key
// fallback otherwise).
if (preparing && hasProvider && !text) {
return (
<Card
aria-busy="true"
aria-live="polite"
data-testid="insight-status-card-preparing"
>
<CardHeader className="pb-2">
<div className="flex items-center gap-2">
{icon}
<CardTitle className="text-base">{title}</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-2">
<div className="bg-muted h-3.5 w-full animate-pulse rounded motion-reduce:animate-none" />
<div className="bg-muted h-3.5 w-11/12 animate-pulse rounded motion-reduce:animate-none" />
<div className="bg-muted h-3.5 w-9/12 animate-pulse rounded motion-reduce:animate-none" />
<p className="text-muted-foreground text-xs">
{t("insights.assessmentPreparing")}
</p>
</CardContent>
</Card>
);
}
if (loading) {
// v1.4.37 — structured skeleton over the centred spinner. When the
// per-metric status route had to fall back to the 20 s provider
+36 -36
View File
@@ -31,7 +31,7 @@ import {
* v1.4.25 W4 — routed tab strip for `/insights`.
*
* Behaviour evolved from the v1.4.25 W3 scroll-anchor version: each pill
* is now a `<Link>` to a routed sub-page (`/insights/blutdruck` …),
* is now a `<Link>` to a routed sub-page (`/insights/blood-pressure` …),
* `usePathname()` decides the active pill, and the strip is mounted in
* `src/app/insights/layout.tsx` so it persists across navigation
* without re-rendering. The CoachDrawer is NOT mounted in this layout —
@@ -116,47 +116,47 @@ const SUB_PAGE_TABS: Record<
{ labelKey: string; metric: InsightMetric }
> = {
// ── vitals ──
blutdruck: {
"blood-pressure": {
labelKey: "insights.navBloodPressure",
metric: "BLOOD_PRESSURE_SYS",
},
puls: { labelKey: "insights.navPulse", metric: "PULSE" },
sauerstoff: {
pulse: { labelKey: "insights.navPulse", metric: "PULSE" },
oxygen: {
labelKey: "insights.navOxygenSaturation",
metric: "OXYGEN_SATURATION",
},
koerpertemperatur: {
"body-temperature": {
labelKey: "insights.navBodyTemperature",
metric: "BODY_TEMPERATURE",
},
atemfrequenz: {
"respiratory-rate": {
labelKey: "insights.navRespiratoryRate",
metric: "RESPIRATORY_RATE",
},
// ── body composition ──
gewicht: { labelKey: "insights.navWeight", metric: "WEIGHT" },
weight: { labelKey: "insights.navWeight", metric: "WEIGHT" },
bmi: { labelKey: "insights.navBmi", metric: "BMI" },
koerperwasser: {
"body-water": {
labelKey: "insights.navTotalBodyWater",
metric: "TOTAL_BODY_WATER",
},
knochenmasse: { labelKey: "insights.navBoneMass", metric: "BONE_MASS" },
"fettfreie-masse": {
"bone-mass": { labelKey: "insights.navBoneMass", metric: "BONE_MASS" },
"fat-free-mass": {
labelKey: "insights.navFatFreeMass",
metric: "FAT_FREE_MASS",
},
fettmasse: { labelKey: "insights.navFatMass", metric: "FAT_MASS" },
muskelmasse: { labelKey: "insights.navMuscleMass", metric: "MUSCLE_MASS" },
viszeralfett: {
"fat-mass": { labelKey: "insights.navFatMass", metric: "FAT_MASS" },
"muscle-mass": { labelKey: "insights.navMuscleMass", metric: "MUSCLE_MASS" },
"visceral-fat": {
labelKey: "insights.navVisceralFat",
metric: "VISCERAL_FAT",
},
magermasse: {
"lean-body-mass": {
labelKey: "insights.navLeanBodyMass",
metric: "LEAN_BODY_MASS",
},
// ── activity ──
"aktive-energie": {
"active-energy": {
labelKey: "insights.navActiveEnergy",
metric: "ACTIVE_ENERGY_BURNED",
},
@@ -164,85 +164,85 @@ const SUB_PAGE_TABS: Record<
// availability helper reads `inputs.hasWorkouts` rather than a
// `summaries[…].count`.
workouts: { labelKey: "insights.navWorkouts", metric: "WORKOUTS" },
stockwerke: {
"flights-climbed": {
labelKey: "insights.navFlightsClimbed",
metric: "FLIGHTS_CLIMBED",
},
gehstrecke: {
"walking-distance": {
labelKey: "insights.navWalkingRunningDistance",
metric: "WALKING_RUNNING_DISTANCE",
},
gangstabilitaet: {
"walking-steadiness": {
labelKey: "insights.navWalkingSteadiness",
metric: "WALKING_STEADINESS",
},
gehpuls: {
"walking-heart-rate": {
labelKey: "insights.navWalkingHeartRateAverage",
metric: "WALKING_HEART_RATE_AVERAGE",
},
gangasymmetrie: {
"walking-asymmetry": {
labelKey: "insights.navWalkingAsymmetry",
metric: "WALKING_ASYMMETRY",
},
doppelstandphase: {
"double-support-time": {
labelKey: "insights.navWalkingDoubleSupport",
metric: "WALKING_DOUBLE_SUPPORT",
},
schrittlaenge: {
"step-length": {
labelKey: "insights.navWalkingStepLength",
metric: "WALKING_STEP_LENGTH",
},
gehgeschwindigkeit: {
"walking-speed": {
labelKey: "insights.navWalkingSpeed",
metric: "WALKING_SPEED",
},
// ── sleep ──
schlaf: { labelKey: "insights.navSleep", metric: "SLEEP_DURATION" },
sleep: { labelKey: "insights.navSleep", metric: "SLEEP_DURATION" },
// ── cardiovascular ──
ruhepuls: {
"resting-pulse": {
labelKey: "insights.navRestingHr",
metric: "RESTING_HEART_RATE",
},
hrv: { labelKey: "insights.navHrv", metric: "HEART_RATE_VARIABILITY" },
pulswellengeschwindigkeit: {
"pulse-wave-velocity": {
labelKey: "insights.navPulseWaveVelocity",
metric: "PULSE_WAVE_VELOCITY",
},
gefaessalter: {
"vascular-age": {
labelKey: "insights.navVascularAge",
metric: "VASCULAR_AGE",
},
// ── hearing ──
laermbelastung: {
"environmental-audio": {
labelKey: "insights.navAudioExposureEnv",
metric: "AUDIO_EXPOSURE_ENV",
},
kopfhoererpegel: {
"headphone-audio": {
labelKey: "insights.navAudioExposureHeadphone",
metric: "AUDIO_EXPOSURE_HEADPHONE",
},
laermereignisse: {
"audio-events": {
labelKey: "insights.navAudioExposureEvent",
metric: "AUDIO_EXPOSURE_EVENT",
},
// ── environment ──
tageslicht: {
daylight: {
labelKey: "insights.navTimeInDaylight",
metric: "TIME_IN_DAYLIGHT",
},
// ── metabolic ──
blutzucker: {
"blood-glucose": {
labelKey: "insights.navBloodGlucose",
metric: "BLOOD_GLUCOSE",
},
hauttemperatur: {
"skin-temperature": {
labelKey: "insights.navSkinTemperature",
metric: "SKIN_TEMPERATURE",
},
// ── mood ──
stimmung: { labelKey: "insights.navMood", metric: "MOOD" },
mood: { labelKey: "insights.navMood", metric: "MOOD" },
// ── events ──
medikamente: { labelKey: "insights.navMedication", metric: "MEDICATION" },
medications: { labelKey: "insights.navMedication", metric: "MEDICATION" },
};
/**
@@ -409,7 +409,7 @@ function InsightsTabStripImpl({
if (tab.kind === "link") {
// The overview pill matches the mother page exactly; the
// sub-page pills match a prefix so future nested routes
// (e.g. `/insights/schlaf/2026-05-11`) still highlight the
// (e.g. `/insights/sleep/2026-05-11`) still highlight the
// parent tab.
const isActive =
tab.href === INSIGHTS_OVERVIEW_PATH
@@ -0,0 +1,123 @@
"use client";
import { useId, useState } from "react";
import { HelpCircle } from "lucide-react";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
import { useIsMobile } from "@/hooks/use-is-mobile";
import { useTranslations } from "@/lib/i18n/context";
import { cn } from "@/lib/utils";
/**
* v1.8.0 — per-category "What is X?" explainer.
*
* A question-mark glyph that sits next to a metric sub-page heading and,
* on tap / Enter / Space, surfaces one to two layperson sentences that
* define the metric. The copy is static — there is no network call — so
* the explainer paints instantly and works offline. Each metric resolves
* its title + body off a stable i18n key pair:
*
* insights.subPage.explainer.<metric>Title
* insights.subPage.explainer.<metric>Body
*
* The surface choice mirrors `<HealthScoreDeltaExplainer>`: a popover on
* `md+`, a bottom-sheet on phone-class viewports. Both branches share the
* same body copy so the read is identical regardless of viewport.
*
* a11y: the trigger is a real `<button>` (Enter / Space activate it
* natively) carrying a descriptive `aria-label`, `aria-expanded`, and
* `aria-controls` pointing at the body. The optical glyph stays 14 px so
* it reads at the heading's height, but the hit surface lifts to the
* 44 px WCAG 2.5.5 floor via `min-h-11 min-w-11`; negative margins
* collapse the surrounding row back to its natural stride so the chip
* stays visually small while the reach is full-size.
*/
interface MetricExplainerProps {
/**
* The metric key. Drives the title + body lookup under
* `insights.subPage.explainer.<metric>{Title,Body}`.
*/
metric: string;
/** Optional className forwarded to the trigger button. */
className?: string;
}
export function MetricExplainer({ metric, className }: MetricExplainerProps) {
const { t } = useTranslations();
const isMobile = useIsMobile();
const [open, setOpen] = useState(false);
const bodyId = useId();
const title = t(`insights.subPage.explainer.${metric}Title`);
const body = t(`insights.subPage.explainer.${metric}Body`);
const triggerLabel = t("insights.subPage.explainer.trigger", { title });
const trigger = (
<button
type="button"
data-slot="metric-explainer-trigger"
aria-label={triggerLabel}
aria-expanded={open}
aria-controls={bodyId}
className={cn(
"text-muted-foreground hover:text-foreground focus-visible:ring-ring/50",
"inline-flex min-h-11 min-w-11 shrink-0 items-center justify-center rounded-full",
"-my-3 -mx-2",
"transition-colors focus-visible:ring-2 focus-visible:outline-none",
className,
)}
onClick={() => setOpen(true)}
>
<HelpCircle className="h-3.5 w-3.5" aria-hidden="true" />
</button>
);
if (isMobile) {
return (
<>
{trigger}
<ResponsiveSheet open={open} onOpenChange={setOpen} title={title}>
<p
id={bodyId}
data-slot="metric-explainer-body"
className="text-muted-foreground text-sm leading-relaxed"
>
{body}
</p>
</ResponsiveSheet>
</>
);
}
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>{trigger}</PopoverTrigger>
<PopoverContent
data-slot="metric-explainer-popover"
align="start"
sideOffset={6}
className="max-w-xs space-y-1.5"
>
<p
data-slot="metric-explainer-title"
className="text-foreground text-xs font-semibold"
>
{title}
</p>
<p
id={bodyId}
data-slot="metric-explainer-body"
className="text-muted-foreground text-xs leading-snug"
>
{body}
</p>
</PopoverContent>
</Popover>
);
}
@@ -0,0 +1,173 @@
"use client";
import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { Target } from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { queryKeys } from "@/lib/query-keys";
import { useTranslations } from "@/lib/i18n/context";
import { Card, CardContent } from "@/components/ui/card";
/**
* v1.8.0 — surface the numeric target range + in-target share on each
* insights category page, directly beneath the chart / assessment.
*
* The data is the same `/api/insights/targets` payload that powers the
* `/targets` editing surface — this component reads the shared
* `queryKeys.insightsTargets()` cache, so on a session that has already
* visited `/targets` the read is free, and on a cold sub-page it warms a
* cache the `/targets` page then reuses. We never recompute the ranges
* here: the route is the single source of truth for the age-based ESH
* blood-pressure band, the WHO weight / BMI band, the Karvonen pulse
* band, the AASM sleep band, and the medication / mood / step targets.
*
* Each insights slug maps to one target `type`. Blood pressure is the one
* composite case: the route emits the systolic band on the
* `BLOOD_PRESSURE` target and the diastolic band on the top-level
* `bpDiastolic` slot, so we stitch them back into a `S/D` range string.
*
* The "in target" share reads `daysInRange30d / daysLogged30d` — the
* fraction of logged days over the last 30 whose mean reading landed in
* the green band. We hide the share alone when the route flags
* `insufficientData`; the range stays visible so the band is always
* legible. This matches the `/targets` consistency strip so the two
* surfaces never disagree.
*
* A discreet "Adjust target range" link routes to `/targets`, which
* stays the canonical place to view / tune the bands.
*/
interface TargetRange {
min: number;
max: number;
}
interface TargetItem {
type: string;
current: number | null;
unit: string;
range: TargetRange | null;
daysInRange30d: number;
daysLogged30d: number;
insufficientData: boolean;
}
interface TargetsResponse {
targets: TargetItem[];
bpDiastolic: {
current: number | null;
range: TargetRange | null;
};
}
/**
* Map each insights category slug to the target `type` the route emits.
* Slugs without a numeric target (HRV, oxygen saturation, body
* temperature, active energy, workouts, resting HR) are absent — the
* component renders nothing for them, so the sub-page collapses cleanly.
*/
const SLUG_TO_TARGET_TYPE: Record<string, string> = {
"blood-pressure": "BLOOD_PRESSURE",
weight: "WEIGHT",
bmi: "BMI",
pulse: "PULSE",
sleep: "SLEEP_DURATION",
mood: "MOOD_SCORE",
medications: "MEDICATION_COMPLIANCE",
};
interface MetricTargetSummaryProps {
/** Insights category slug, e.g. `"blood-pressure"`. */
slug: string;
}
/** Trim a trailing `.0` so whole-number bands read `120` not `120.0`. */
function fmt(value: number): string {
return Number.isInteger(value) ? String(value) : value.toFixed(1);
}
export function MetricTargetSummary({ slug }: MetricTargetSummaryProps) {
const { t } = useTranslations();
const { isAuthenticated } = useAuth();
const targetType = SLUG_TO_TARGET_TYPE[slug];
const { data } = useQuery({
queryKey: queryKeys.insightsTargets(),
queryFn: async () => {
const res = await fetch("/api/insights/targets");
if (!res.ok) throw new Error("Failed");
const json = await res.json();
return json.data as TargetsResponse;
},
enabled: isAuthenticated && targetType != null,
});
// No numeric target for this slug, or the payload hasn't resolved yet.
if (!targetType || !data) return null;
const target = data.targets.find((entry) => entry.type === targetType);
if (!target || !target.range) return null;
const { range, unit } = target;
// Compose the range string. Blood pressure stitches the systolic band
// (on this target) with the diastolic band (on `bpDiastolic`) so the
// user reads the familiar `S/D` pair.
let rangeLabel: string;
if (targetType === "BLOOD_PRESSURE" && data.bpDiastolic.range) {
const dia = data.bpDiastolic.range;
rangeLabel = t("insights.subPage.target.bpRange", {
sysMin: fmt(range.min),
sysMax: fmt(range.max),
diaMin: fmt(dia.min),
diaMax: fmt(dia.max),
unit,
});
} else {
rangeLabel = t("insights.subPage.target.range", {
min: fmt(range.min),
max: fmt(range.max),
unit,
});
}
// In-target share: fraction of logged days in the green band over the
// last 30. Suppressed when the route flagged insufficient data so the
// sub-page mirrors the `/targets` strip exactly.
const showShare =
!target.insufficientData && target.daysLogged30d > 0;
const sharePct = showShare
? Math.round((target.daysInRange30d / target.daysLogged30d) * 100)
: null;
return (
<Card data-slot="metric-target-summary">
<CardContent className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 py-3">
<div className="flex items-center gap-2.5">
<Target
className="text-dracula-green size-4 shrink-0"
aria-hidden="true"
/>
<div className="space-y-0.5">
<p className="text-sm font-medium">{rangeLabel}</p>
{sharePct != null ? (
<p className="text-muted-foreground text-xs">
{t("insights.subPage.target.inTargetShare", {
pct: sharePct,
})}
</p>
) : null}
</div>
</div>
<Link
href="/targets"
className="text-muted-foreground hover:text-foreground focus-visible:ring-ring/50 inline-flex min-h-11 items-center rounded-sm px-1 text-xs font-medium underline-offset-4 transition-colors hover:underline focus-visible:ring-2 focus-visible:outline-none"
>
{t("insights.subPage.target.adjustLink")}
</Link>
</CardContent>
</Card>
);
}
@@ -3,7 +3,9 @@
import { useEffect, useRef, type ReactNode } from "react";
import { Badge } from "@/components/ui/badge";
import { MetricExplainer } from "@/components/insights/metric-explainer";
import { useScrollResetOnRoute } from "@/hooks/use-scroll-reset-on-route";
import { useTranslations } from "@/lib/i18n/context";
import { cn } from "@/lib/utils";
/**
@@ -34,6 +36,21 @@ export interface SubPageShellProps {
* page does not pass it; sub-pages use it to anchor the surface.
*/
description?: string;
/**
* v1.8.0 — when set, a `?` glyph next to the heading opens a static
* "What is X?" explainer (popover on desktop, bottom-sheet on phones).
* The value is the metric key feeding
* `insights.subPage.explainer.<metric>{Title,Body}`. Omitted on the
* mother page; every routed metric sub-page passes its key.
*
* v1.8.4 — the same explainer body also renders inline as a muted
* caption directly beneath the heading, so the one- to two-sentence
* definition is visible without opening the popover. The `?` glyph
* stays as the always-available pointer for the same copy. Both the
* inline caption and the popover read the identical
* `insights.subPage.explainer.<metric>Body` string — no duplicated copy.
*/
explainerMetric?: string;
/**
* v1.4.27 MB7 / CF-35 — opt-in programmatic focus on mount.
*
@@ -56,9 +73,11 @@ export function SubPageShell({
title,
badge,
description,
explainerMetric,
focusOnMount = false,
children,
}: SubPageShellProps) {
const { t } = useTranslations();
// a11y: focus the heading on mount so a tab-strip navigation actually
// moves screen-reader focus into the sub-page body. v1.4.27 MB7 /
// CF-35 made the focus call opt-in via `focusOnMount` — the
@@ -99,12 +118,27 @@ export function SubPageShell({
>
{title}
</h1>
{explainerMetric ? (
<MetricExplainer metric={explainerMetric} />
) : null}
{badge ? (
<Badge variant="outline" className="border text-xs">
{badge}
</Badge>
) : null}
</div>
{explainerMetric ? (
// v1.8.4 — surface the explainer definition inline, reusing the
// exact body string the `?` popover reads. Muted caption styling
// matches the description paragraph below so the under-heading
// band reads as one calm block.
<p
data-slot="metric-explainer-inline"
className="text-muted-foreground text-sm leading-relaxed"
>
{t(`insights.subPage.explainer.${explainerMetric}Body`)}
</p>
) : null}
{description ? (
<p className="text-muted-foreground text-sm">{description}</p>
) : null}
+1 -1
View File
@@ -11,7 +11,7 @@ import {
} from "@/lib/medications/injection-sites";
/**
* v1.4.25 W4d — therapy-timeline view for /insights/medikamente.
* v1.4.25 W4d — therapy-timeline view for /insights/medications.
*
* Renders a chronological list of GLP-1 therapy events: dose changes,
* injections (with site if recorded), inventory events, side-effect tag
@@ -1,5 +1,6 @@
"use client";
import { useCallback } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { InsightResult } from "@/lib/ai/types";
import {
@@ -176,12 +177,20 @@ export function useInsightsAdvisorQuery(
},
});
// v1.8.3 — stabilise the `regenerate` callback so the memoised
// `<InsightsTabStrip>` (which receives it as `onRegenerate`) is not
// re-rendered on every shell render by a fresh arrow reference. A
// status-query flip on a sub-page that re-renders the shell would
// otherwise re-reconcile the whole strip mid-gesture and eat taps.
const { mutate } = mutation;
const regenerate = useCallback(() => mutate(), [mutate]);
return {
payload: query.data ?? null,
isLoading: query.isLoading,
isError: query.isError,
error: (query.error as Error | null) ?? null,
regenerate: () => mutation.mutate(),
regenerate,
isRegenerating: mutation.isPending,
regenerateError: (mutation.error as Error | null) ?? null,
};
@@ -9,7 +9,7 @@ import { cn } from "@/lib/utils";
import { HealthChartDynamic } from "@/components/charts/health-chart-dynamic";
/**
* v1.4.25 W16a — VO2 max chart-row card for `/insights/puls`.
* v1.4.25 W16a — VO2 max chart-row card for `/insights/pulse`.
*
* The dashboard already carries an opt-in VO2 max trend tile (W8d.5);
* this is the deeper Insights surface. Renders one HealthChart for the
@@ -143,8 +143,8 @@ describe("<IntakeHistoryListV2> — populated rows", () => {
const html = render(<IntakeHistoryListV2 medicationId="med-1" />, client);
expect(html).toContain("Taken");
expect(html).toContain("Skipped");
expect(html).toContain("Website");
expect(html).toContain("Telegram / Reminder");
expect(html).toContain("via Web");
expect(html).toContain("via Reminder");
});
it("renders the taken row with a green Check chip and the skipped row with an outline SkipForward chip", () => {
@@ -49,11 +49,14 @@ const med7p5: Glp1Medication = {
// not "today/yesterday" — keeps the SSR string deterministic-ish
// across local clocks while still exercising the with-site branch.
lastTakenAt: "2026-05-08T08:00:00.000Z",
// v1.8.4 — the card now reads the server-computed next-due instant
// directly instead of re-deriving it client-side. A far-future fixed
// date keeps the "in N days" branch deterministic across host clocks.
nextDueAt: "2099-05-09T08:00:00.000Z",
schedules: [
{
id: "s1",
// Saturday only — one entry triggers the weekly-preset branch
// in `predictNextWeeklyDate()`.
// Saturday only.
windowStart: "08:00",
windowEnd: "20:00",
label: null,
@@ -0,0 +1,202 @@
import { describe, expect, it } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
import { MedicationCard } from "@/components/medications/medication-card";
/**
* v1.8.4 — the generic medication card must render the server-computed
* `nextDueAt` (canonical recurrence engine, anchored on the last intake)
* as the "next intake" timestamp, NOT a client-side daysOfWeek walker.
*
* The legacy walker only read `daysOfWeek` + `windowStart` and ignored
* rolling / RRULE / one-shot cadences, so a rolling medication (e.g.
* `rollingIntervalDays = 35`) wrongly read "tomorrow" and never
* re-anchored after an intake. These tests pin that the card now
* surfaces the server value, while the day-label / window-range
* rendering for ordinary single-time schedules is unchanged.
*/
function makeClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: { retry: false, gcTime: 0, staleTime: Infinity },
},
});
}
function render(node: React.ReactNode, client: QueryClient) {
return renderToStaticMarkup(
<I18nProvider initialLocale="en">
<QueryClientProvider client={client}>{node}</QueryClientProvider>
</I18nProvider>,
);
}
function seedCompliance(client: QueryClient, medId: string) {
client.setQueryData(["medications", medId, "compliance"], {
compliance7: { rate: 90, streak: 0, totalExpected: 7, taken: 6 },
compliance30: { rate: 88 },
});
}
// A schedule whose window has already passed for today (01:00–02:00) so
// the card surfaces the "next intake" line rather than the take-now
// pill, regardless of host clock.
const pastWindow = {
windowStart: "01:00",
windowEnd: "02:00",
label: null,
daysOfWeek: null,
dose: null,
};
describe("<MedicationCard> — next-due reads from server nextDueAt", () => {
it("renders the server nextDueAt date for a rolling medication, not a today/tomorrow walker value", () => {
// Rolling cadence: server anchors the next dose 35 days out. The
// card must surface that calendar date — the legacy walker would
// have produced "tomorrow" off the schedule window alone.
const now = new Date();
const due = new Date(now);
due.setDate(due.getDate() + 35);
// Midday so the Berlin display can't cross a day boundary regardless
// of the host timezone.
due.setHours(12, 0, 0, 0);
const rollingMed = {
id: "med-rolling-1",
name: "Mounjaro",
dose: "7.5 mg",
category: "OTHER",
treatmentClass: undefined as string | undefined,
active: true,
notificationsEnabled: true,
pausedAt: null,
lastTakenAt: null,
todayEventCount: 0,
nextDueAt: due.toISOString(),
schedules: [{ id: "s-rolling-1", ...pastWindow }],
};
const client = makeClient();
seedCompliance(client, rollingMed.id);
const html = render(
<MedicationCard
medication={rollingMed}
onEdit={() => {}}
onOpenHistory={() => {}}
onOpenAdvanced={() => {}}
/>,
client,
);
// The next-intake line surfaces.
expect(html).toContain("Next intake:");
// 35 days out is past the 5-day threshold, so the card renders the
// full weekday-anchored short date (e.g. "Mon, 07/06") derived from
// the SERVER instant — NOT a today/tomorrow walker value. Pin the
// day-of-month + month of the SERVER date (Berlin-rendered), proving
// the date tracks `nextDueAt` rather than the schedule window alone.
const berlin = new Intl.DateTimeFormat("en", {
timeZone: "Europe/Berlin",
weekday: "short",
day: "2-digit",
month: "2-digit",
}).format(due);
expect(html).toContain(berlin);
expect(html).not.toContain("Next intake: Today,");
expect(html).not.toContain("Next intake: Tomorrow,");
});
it("falls back to the schedule window range when nextDueAt is absent", () => {
// A medication with no server next-due (e.g. ended course) still
// renders the window-range line off its first schedule; it just
// omits the day label.
const med = {
id: "med-nodue-1",
name: "Ramipril",
dose: "5 mg",
category: "BLOOD_PRESSURE",
treatmentClass: undefined as string | undefined,
active: true,
notificationsEnabled: true,
pausedAt: null,
lastTakenAt: null,
todayEventCount: 0,
nextDueAt: null,
schedules: [{ id: "s-nodue-1", ...pastWindow }],
};
const client = makeClient();
seedCompliance(client, med.id);
const html = render(
<MedicationCard
medication={med}
onEdit={() => {}}
onOpenHistory={() => {}}
onOpenAdvanced={() => {}}
/>,
client,
);
expect(html).toContain("Next intake:");
// No day label is prepended when the server gave no instant — the
// line goes straight to the window range.
expect(html).not.toContain("Next intake: Today,");
expect(html).not.toContain("Next intake: Tomorrow,");
});
it("renders the day label for a single-time daysOfWeek medication due tomorrow", () => {
// A daily / weekly medication whose server next-due is tomorrow
// still renders the relative "tomorrow" label — proving the ordinary
// single-time path keeps working.
const now = new Date();
const due = new Date(now);
due.setDate(due.getDate() + 1);
due.setHours(8, 0, 0, 0);
const med = {
id: "med-daily-1",
name: "Ramipril",
dose: "5 mg",
category: "BLOOD_PRESSURE",
treatmentClass: undefined as string | undefined,
active: true,
notificationsEnabled: true,
pausedAt: null,
lastTakenAt: null,
todayEventCount: 0,
nextDueAt: due.toISOString(),
schedules: [
{
id: "s-daily-1",
windowStart: "08:00",
windowEnd: "09:00",
label: null,
daysOfWeek: null,
dose: "5 mg",
},
],
};
const client = makeClient();
seedCompliance(client, med.id);
const html = render(
<MedicationCard
medication={med}
onEdit={() => {}}
onOpenHistory={() => {}}
onOpenAdvanced={() => {}}
/>,
client,
);
expect(html).toContain("Next intake:");
// Relative day label from the server instant (capitalised "Tomorrow").
expect(html).toContain("Tomorrow,");
});
});
@@ -2,6 +2,7 @@
import { useEffect, useReducer, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Card, CardContent } from "@/components/ui/card";
import { MedicationCardHeader } from "@/components/medications/MedicationCardHeader";
@@ -79,6 +80,14 @@ export interface Glp1Medication {
pausedAt: string | null;
lastTakenAt: string | null;
todayEventCount?: number;
/**
* v1.8.4 — server-computed next due instant from `GET /api/medications`
* (the canonical recurrence engine anchored on the last intake). The card
* renders this directly so a rolling GLP-1 with an interval other than the
* weekly default re-anchors correctly; the old client-side predictor only
* walked a single hardcoded weekly day-of-week.
*/
nextDueAt?: string | null;
schedules: ScheduleLite[];
}
@@ -126,14 +135,6 @@ const DAY_KEYS = [
"medications.daysSat",
] as const;
function parseDayList(raw: string | null): number[] {
if (!raw) return [];
return raw
.split(",")
.map((p) => Number(p.trim()))
.filter((n) => Number.isInteger(n) && n >= 0 && n <= 6);
}
function diffDays(target: Date, from: Date): number {
const ms =
Date.UTC(target.getFullYear(), target.getMonth(), target.getDate()) -
@@ -141,26 +142,22 @@ function diffDays(target: Date, from: Date): number {
return Math.round(ms / (24 * 60 * 60 * 1000));
}
function predictNextWeeklyDate(
schedule: ScheduleLite | null,
lastTakenAt: string | null,
/**
* v1.8.4 — the next injection instant now comes from the server's
* `nextDueAt` (the canonical recurrence engine, anchored on the last
* intake). The legacy client-side predictor only handled a single
* hardcoded weekly day-of-week and re-anchored at +7 days, so a rolling
* GLP-1 with a non-weekly interval rendered the wrong date and never
* advanced after an injection.
*/
function nextInjectionFromServer(
nextDueAt: string | null | undefined,
now: Date,
): { date: Date; daysAway: number } | null {
if (!schedule) return null;
const dow = parseDayList(schedule.daysOfWeek);
if (dow.length !== 1) return null;
const target = dow[0];
const anchor = lastTakenAt ? new Date(lastTakenAt) : now;
const cursor = new Date(anchor);
cursor.setHours(0, 0, 0, 0);
for (let i = 1; i <= 14; i += 1) {
cursor.setDate(cursor.getDate() + 1);
if (cursor.getDay() === target) {
const days = diffDays(cursor, now);
return { date: cursor, daysAway: Math.max(0, days) };
}
}
return null;
if (!nextDueAt) return null;
const date = new Date(nextDueAt);
if (Number.isNaN(date.getTime())) return null;
return { date, daysAway: Math.max(0, diffDays(date, now)) };
}
export function Glp1MedicationCard({
@@ -234,6 +231,14 @@ export function Glp1MedicationCard({
body: JSON.stringify({ skipped }),
});
if (res.ok) {
toast.success(
t(
skipped
? "medications.intakeToastSkipped"
: "medications.intakeToastTaken",
{ name: medication.name },
),
);
await invalidateKeys(queryClient, medicationDependentKeys);
}
} finally {
@@ -243,7 +248,7 @@ export function Glp1MedicationCard({
const schedule = medication.schedules[0] ?? null;
const now = new Date();
const next = predictNextWeeklyDate(schedule, medication.lastTakenAt, now);
const next = nextInjectionFromServer(medication.nextDueAt, now);
const rate7 = compliance?.compliance7?.rate ?? 0;
const rate30 = compliance?.compliance30?.rate ?? 0;
const streak = compliance?.compliance7?.streak ?? 0;
@@ -65,8 +65,11 @@ import {
* - Status chip: green Check + "Eingenommen" for taken rows,
* outline SkipForward + "Übersprungen" for skipped rows. The
* component never labels a row both at once.
* - Source badge surfaces WEB / API / REMINDER / IMPORT using the
* existing `medications.source*` keys.
* - Source badge surfaces where the intake was logged — WEB → "Web",
* API → "iOS App", REMINDER → "Reminder", IMPORT → "Import" — wrapped
* in a muted "via {origin}" caption next to the status. The labels map
* the coarse `IntakeSource` enum to the practical client per the
* existing `medications.source*` keys; there is no finer client field.
* - Empty state copy + CTA back to the daily intake page.
* - No edit-in-row, no delete buttons.
*/
@@ -377,8 +380,13 @@ export function IntakeHistoryListV2({
) : null}
</TableCell>
<TableCell>
<Badge variant="outline" className="text-xs">
{sourceLabels[event.source] ?? event.source}
<Badge
variant="outline"
className="text-muted-foreground text-xs font-normal"
>
{t("medications.intakeSourceVia", {
origin: sourceLabels[event.source] ?? event.source,
})}
</Badge>
</TableCell>
{showRowActions && (
+29 -57
View File
@@ -2,6 +2,7 @@
import { useState, useEffect, useReducer } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Card, CardContent } from "@/components/ui/card";
import { MedicationCardHeader } from "@/components/medications/MedicationCardHeader";
import { MedicationCardMenu } from "@/components/medications/medication-card-menu";
@@ -9,12 +10,10 @@ import { MedicationStateBadges } from "@/components/medications/card-parts/medic
import { MedicationStatusPill } from "@/components/medications/card-parts/medication-status-pill";
import { MedicationComplianceBars } from "@/components/medications/card-parts/medication-compliance-bars";
import { MedicationIntakeActions } from "@/components/medications/card-parts/medication-intake-actions";
import { parseScheduleRecurrence } from "@/lib/medication-schedule";
import { formatTimeWindowRange } from "@/lib/time-window-format";
import { formatDateTime, formatTime } from "@/lib/format";
import { getMedicationCategoryLabel } from "@/lib/medications/category-label";
import {
parseTimeToMinutes,
reduceCurrentWindowStatus,
toBerlinDate,
} from "@/lib/medications/window-status";
@@ -52,6 +51,14 @@ interface Medication {
pausedAt: string | null;
lastTakenAt: string | null;
todayEventCount?: number;
/**
* v1.8.4 — server-computed next due instant from `GET /api/medications`
* (`computeNextDueAt` → the canonical recurrence engine, anchored on the
* last intake). The card renders this directly instead of re-deriving the
* timestamp client-side; the engine honours rolling / RRULE / one-shot
* cadences that the legacy daysOfWeek-only walker ignored.
*/
nextDueAt?: string | null;
schedules: Schedule[];
}
@@ -86,47 +93,6 @@ interface MedicationCardProps {
onOpenAdvanced: (med: Medication) => void;
}
function getNextOccurrenceTimestamp(
schedule: Schedule,
nowBerlin: Date,
): number | null {
const recurrence = parseScheduleRecurrence(schedule.daysOfWeek);
const baseDay = new Date(nowBerlin);
baseDay.setHours(0, 0, 0, 0);
const nowMinutes = nowBerlin.getHours() * 60 + nowBerlin.getMinutes();
const weekMs = 7 * 24 * 60 * 60 * 1000;
const baseWeekIndex = Math.floor(baseDay.getTime() / weekMs);
const startMinutes = parseTimeToMinutes(schedule.windowStart);
for (let offset = 0; offset <= 400; offset += 1) {
const candidate = new Date(baseDay);
candidate.setDate(baseDay.getDate() + offset);
const candidateWeekIndex = Math.floor(candidate.getTime() / weekMs);
const isAllowedWeek =
recurrence.intervalWeeks <= 1 ||
candidateWeekIndex % recurrence.intervalWeeks ===
baseWeekIndex % recurrence.intervalWeeks;
if (!isAllowedWeek) continue;
if (
recurrence.daysOfWeek.length > 0 &&
!recurrence.daysOfWeek.includes(candidate.getDay())
) {
continue;
}
if (offset === 0 && startMinutes <= nowMinutes) {
continue;
}
return candidate.getTime() + startMinutes * 60 * 1000;
}
return null;
}
export function MedicationCard({
medication,
onEdit,
@@ -177,6 +143,14 @@ export function MedicationCard({
body: JSON.stringify({ skipped }),
});
if (res.ok) {
toast.success(
t(
skipped
? "medications.intakeToastSkipped"
: "medications.intakeToastTaken",
{ name: medication.name },
),
);
await invalidateKeys(queryClient, medicationDependentKeys);
}
} finally {
@@ -194,19 +168,18 @@ export function MedicationCard({
a.windowEnd.localeCompare(b.windowEnd),
);
const nowBerlin = toBerlinDate(new Date());
const nextOccurrence =
sortedSchedules.length > 0
? (sortedSchedules
.map((schedule) => ({
schedule,
nextAt: getNextOccurrenceTimestamp(schedule, nowBerlin),
}))
.filter((entry): entry is { schedule: Schedule; nextAt: number } =>
Number.isFinite(entry.nextAt),
)
.sort((a, b) => a.nextAt - b.nextAt)[0] ?? null)
: null;
const nextSchedule = nextOccurrence?.schedule ?? sortedSchedules[0] ?? null;
// v1.8.4 — the next-due instant comes from the server (`nextDueAt`,
// computed by the canonical recurrence engine anchored on the last
// intake). The day label below derives from it; the window-range /
// dose / label still come from the earliest configured schedule. The
// legacy client-side daysOfWeek walker only ever read daysOfWeek +
// windowStart and silently mis-anchored rolling / RRULE / one-shot
// cadences, so it is gone.
const nextDueMs = medication.nextDueAt
? new Date(medication.nextDueAt).getTime()
: NaN;
const nextAt = Number.isFinite(nextDueMs) ? nextDueMs : undefined;
const nextSchedule = sortedSchedules[0] ?? null;
const lateMinutes = thresholds?.lateMinutes ?? 120;
const missedMinutes = thresholds?.missedMinutes ?? 240;
@@ -291,7 +264,6 @@ export function MedicationCard({
currentWindowStatus.status !== "in_window" &&
(() => {
const s = nextSchedule;
const nextAt = nextOccurrence?.nextAt;
// Format day label relative to today
let dayLabel = "";
@@ -97,7 +97,7 @@ function buildSelectionSections(s: SectionState) {
}
export function HealthRecordExportPanel() {
const { t } = useTranslations();
const { t, locale } = useTranslations();
const [format, setFormat] = useState<ExportFormat>("pdf");
const [days, setDays] = useState<number>(90);
const [practiceName, setPracticeName] = useState("");
@@ -140,6 +140,10 @@ export function HealthRecordExportPanel() {
credentials: "include",
body: JSON.stringify({
format,
// Carry the active in-app locale so the generated artefact matches
// the UI language instead of falling back to the browser's
// Accept-Language header on the server.
locale,
range: { days },
practiceName: practiceName.trim() || undefined,
includeCharts,
@@ -0,0 +1,45 @@
import { describe, it, expect } from "vitest";
import {
nextStatusPollInterval,
STATUS_POLL_MAX_ATTEMPTS,
} from "../use-insight-status";
/**
* v1.8.4 — the preparing poll must stop after a bounded number of
* attempts. A provider can be configured yet have generation fail
* persistently; without a ceiling the status card polls an open page
* forever (battery / network waste). `nextStatusPollInterval` is the
* shared decision both the hook and the inline medication-compliance
* query route through, so locking its contract covers both sites.
*/
describe("nextStatusPollInterval — v1.8.4 poll ceiling", () => {
it("does not poll a terminal payload (preparing absent/false)", () => {
expect(nextStatusPollInterval(undefined, 1)).toBe(false);
expect(nextStatusPollInterval(false, 1)).toBe(false);
// A terminal `no-provider` / settled payload never carries preparing,
// so it stops immediately regardless of attempt count.
expect(nextStatusPollInterval(false, 0)).toBe(false);
});
it("keeps polling while preparing and below the cap", () => {
expect(nextStatusPollInterval(true, 0)).toBeTypeOf("number");
expect(nextStatusPollInterval(true, 1)).toBeTypeOf("number");
expect(
nextStatusPollInterval(true, STATUS_POLL_MAX_ATTEMPTS - 1),
).toBeTypeOf("number");
});
it("stops polling once the attempt cap is reached", () => {
expect(nextStatusPollInterval(true, STATUS_POLL_MAX_ATTEMPTS)).toBe(false);
expect(
nextStatusPollInterval(true, STATUS_POLL_MAX_ATTEMPTS + 5),
).toBe(false);
});
it("returns a positive interval while it polls", () => {
const interval = nextStatusPollInterval(true, 0);
expect(interval).not.toBe(false);
expect(interval as number).toBeGreaterThan(0);
});
});
+86 -8
View File
@@ -23,6 +23,59 @@ export interface InsightStatusData {
text: string | null;
cached: boolean;
updatedAt: string | null;
/**
* v1.8.3 — the route is read-only: a cache miss enqueues an out-of-band
* generation and returns `preparing: true` with `text: null`. The card
* shows a preparing state and the hook polls (bounded) until the worker
* warms the cache. Absent / false means the payload is terminal.
*/
preparing?: boolean;
}
/**
* v1.8.3 — client-side ceiling on the status GET. The route is now
* read-only (sub-second cache read), so a slow response means the network
* itself is degraded, not the LLM. Mirror the advisor hook's 8 s
* `ADVISOR_TIMEOUT_MS`: abort and surface the empty / preparing state
* rather than letting a hung request pin the navigation. No user
* navigation may ever await an uncapped round-trip.
*/
const STATUS_TIMEOUT_MS = 8_000;
/**
* Poll interval while a card is `preparing`. Bounded by `staleTime` so a
* settled (terminal) payload never re-fetches on a timer; only the
* preparing state keeps polling, and it stops as soon as text lands.
*/
const STATUS_POLL_MS = 4_000;
/**
* v1.8.4 — hard ceiling on the preparing poll. The route is read-only and
* a worker warms the cache out of band; a healthy generation lands within
* a couple of intervals. If a provider is configured but generation
* persistently fails, `preparing` stays true forever and the open page
* would otherwise poll indefinitely (battery / network waste). Cap the
* poll at ~12 attempts (≈ 48 s at the 4 s cadence) and then fall back to
* the static empty / "no analysis yet" state. `dataUpdateCount` counts
* every settled fetch — initial load plus each poll round — so once it
* crosses the cap we stop scheduling the next interval.
*/
export const STATUS_POLL_MAX_ATTEMPTS = 12;
/**
* Decide whether a `preparing` card should schedule its next poll.
* Pure and shared between the `useInsightStatus` hook and the inline
* medication-compliance query so both sites enforce the identical
* ceiling. Returns the interval in ms while polling is warranted, or
* `false` once the payload is terminal OR the attempt cap is reached.
*/
export function nextStatusPollInterval(
preparing: boolean | undefined,
dataUpdateCount: number,
): number | false {
if (!preparing) return false;
if (dataUpdateCount >= STATUS_POLL_MAX_ATTEMPTS) return false;
return STATUS_POLL_MS;
}
/**
@@ -71,17 +124,42 @@ export function useInsightStatus(metric: InsightStatusMetric) {
return useQuery({
queryKey: QUERY_KEY_FACTORY[metric](locale),
queryFn: async (): Promise<InsightStatusData> => {
const res = await fetch(`/api/insights/${metric}-status?locale=${locale}`);
if (!res.ok) throw new Error("Failed");
const json = (await res.json()) as { data: InsightStatusData };
return json.data;
// v1.8.3 — bound the fetch on the client. AbortController + 8 s
// timeout so a degraded network can't pin the navigation thread.
// The card surfaces its preparing / empty state on abort exactly as
// it does for a `preparing` payload, and the bounded poll retries.
const controller = new AbortController();
const timeoutHandle = setTimeout(
() => controller.abort(),
STATUS_TIMEOUT_MS,
);
try {
const res = await fetch(
`/api/insights/${metric}-status?locale=${locale}`,
{ signal: controller.signal },
);
if (!res.ok) throw new Error("Failed");
const json = (await res.json()) as { data: InsightStatusData };
return json.data;
} finally {
clearTimeout(timeoutHandle);
}
},
enabled: isAuthenticated,
staleTime: 60 * 1000,
// v1.4.28 FB-D2 — the status route now returns a deterministic
// cached-style envelope on provider timeout. Retrying that response
// re-fires the same expensive upstream call and the user perceives
// a longer hang. Drop retries to surface the fallback immediately.
// v1.4.28 FB-D2 — the status route returns a deterministic envelope on
// a miss/timeout. Retrying inline re-fires work and lengthens the
// perceived hang; the bounded `preparing` poll below covers the warm-up.
retry: 0,
// v1.8.3 — poll only while the worker is preparing the assessment.
// Returns false (no timer) for any terminal payload so a settled card
// never re-fetches on an interval. v1.8.4 — also stop after the
// attempt ceiling so a persistently failing generation can't poll an
// open page forever.
refetchInterval: (query) =>
nextStatusPollInterval(
query.state.data?.preparing,
query.state.dataUpdateCount,
),
});
}
@@ -3,6 +3,7 @@ import { PDFParse } from "pdf-parse";
import {
buildDoctorReportPdfDocument,
renderDoctorReportPdfBytes,
sanitiseForPdf,
DOCTOR_REPORT_VITAL_TYPES,
DOCTOR_REPORT_TYPE_LABEL_KEYS,
DOCTOR_REPORT_TYPE_UNIT_KEYS,
@@ -183,6 +184,96 @@ describe("buildDoctorReportPdfDocument", () => {
});
});
// ── WinAnsi sanitiser ── the rendered Helvetica is WinAnsi-encoded; glyphs
// outside it (trend arrows, superscripts) resolve to the .notdef box at a
// fallback advance width and stretch the surrounding line. The sanitiser
// maps every offender the report can emit onto a WinAnsi-safe equivalent.
describe("sanitiseForPdf", () => {
it("maps trend arrows to ASCII equivalents", () => {
expect(sanitiseForPdf("↑")).toBe("^");
expect(sanitiseForPdf("↓")).toBe("v");
expect(sanitiseForPdf("→")).toBe("->");
});
it("maps the superscript-two in kg/m² to a plain 2", () => {
expect(sanitiseForPdf("kg/m²")).toBe("kg/m2");
});
it("leaves WinAnsi-safe glyphs (umlauts, ß, em-dash) untouched", () => {
expect(sanitiseForPdf("Müller — Größe")).toBe("Müller — Größe");
});
it("renders the GLP-1 weight summary without any non-WinAnsi glyph", async () => {
const data = makeData({
glp1: {
weightStartKg: 92,
weightEndKg: 86,
weightDeltaKg: -6,
medications: [],
sideEffects: [],
} as unknown as DoctorReportData["glp1"],
});
const bytes = renderDoctorReportPdfBytes(data, {
t: getServerTranslator("de").t,
locale: "de",
now: FIXED_NOW,
});
const text = await extractText(bytes);
// The arrow separator must have been folded to ASCII; no raw arrow in
// the document text layer.
expect(text).not.toMatch(/[↑↓→²]/);
expect(text).toContain("->");
});
});
// ── chart time axis ── the sparkline must anchor the trend in real time so a
// reader can tell whether the curve spans a week or a year.
describe("doctor-report sparkline time axis", () => {
it("prints the series start and end dates under the chart", async () => {
const data = makeData({
measurements: {
WEIGHT: [
{ value: 82, measuredAt: "2026-02-05T08:00:00.000Z" },
{ value: 81, measuredAt: "2026-03-10T08:00:00.000Z" },
{ value: 79.5, measuredAt: "2026-04-28T08:00:00.000Z" },
],
},
});
const bytes = renderDoctorReportPdfBytes(data, {
t: getServerTranslator("de").t,
locale: "de",
includeCharts: true,
now: FIXED_NOW,
});
const text = await extractText(bytes);
// dd.mm short labels (Berlin tz). First + last sample dates.
expect(text).toContain("05.02.");
expect(text).toContain("28.04.");
});
});
// ── page-break discipline ── a long table must not orphan its heading or
// collide with the footer; the renderer paginates without throwing.
describe("doctor-report pagination", () => {
it("paginates a long compliance table across pages without throwing", () => {
const compliance: DoctorReportData["compliance"] = {};
for (let i = 0; i < 60; i++) {
compliance[`Medication ${i}`] = {
total: 90,
taken: 80,
skipped: 5,
missed: 5,
};
}
const doc = buildDoctorReportPdfDocument(makeData({ compliance }), {
t: getServerTranslator("de").t,
locale: "de",
now: FIXED_NOW,
});
expect(doc.getNumberOfPages()).toBeGreaterThan(1);
});
});
// Audit-2026-05-07 / phase P0 / closes audit C-9: server-side PDF used a
// stale type map and silently dropped body composition while the browser
// PDF rendered them. These tests pin the contract.
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff. Show more