Salud: a card opens onto the day, hour by hour, and onto the days before it
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Reported as "le doy a cualquier actividad y solo me presenta los pasos de hoy… debiera presentarme una medida por hora, y no me da el histórico". Two separate things, and only one of them was the app's fault. **The history was the automation's setting.** With Date Range on its default (`Today`) every sync carries today and nothing else, so there is exactly one day in the file to draw. That is why a card looked frozen: not a rendering bug, a range that was never sent. The setup steps now say `Previous 7 Days` and say why. **The hours were thrown away by us.** Even when the phone sends 288 readings a day, the receiver folded every one of them into a single day aggregate, so "8,123 steps today" was all there could ever be — a number you cannot look into. Worse, the recommended setting was Time Grouping `Days`, which sends one point per metric per day: the intraday detail never arrived in the first place. The recommendation is now `Hours`, and the storage keeps the hours. The merge rule for them is the same shape as the day rule, for the same reason: a payload whose datapoints all sit on the hour is HAE's own hour grouping, and the hour *in progress* grows on every run of a five-minute automation, so it is replaced and never unioned — 500 + 900 + 1,340 steps in one hour is a number no watch recorded. The day is then recomputed as the sum of its hours, which is what keeps the card and the detail from ever disagreeing, and which also makes switching an automation from Days to Hours mid-day converge instead of double-count. Raw samples (real timestamps) still union by instant plus numbers, and they now land in their own hour, which is where intraday detail comes from when nothing is grouped. Three things that would have been silent bugs, caught while writing it: - The hour rule is decided from the **whole payload**, never from one timestamp. A five-minute automation produces samples that sit exactly on the hour, and reading one of those as an hour total wipes the hour it belongs to. There is a test with a 09:00:00 and a 09:05:00 sample in one payload, and it fails against the per-point version of the rule. - A day that arrived as a day total keeps its hours beside it, and a day stored before this existed keeps its aggregate when the first hour shows up — recomputing it from hours it does not have would delete 2,000 steps. Both are mutation-checked (removing either guard fails a test). - A payload grouped by hour writes the ledger row anyway, because a later payload with real minutes can describe the same instant and the union path can only see the ledger. Without it the raw-sample route test double-counts a single sample. The hours are the bulky part of this data, so they are kept for a week (the day aggregates still live the full 400 days), pruned when the night's file is written, and fetched one metric and one day at a time — `GET /api/vitals/hours`. A screen listing forty cards downloads none of them; the day view carries only a count per day, which is what tells the sheet whether it is worth asking. The sheet draws the hours, the days before it (tapping one moves the hour list to that day), and every field the watch sent; when the automation groups by Days it says so instead of leaving a gap where a chart should be. Coverage: 6 new tests in `api/test/vitals.test.js` (19 total) and a route test in `api/test/server-vitals.test.js` (5), the hour/history model in `vitals-view.test.js` (31), three render tests through the real sheet, the route documented in `api/openapi.yaml` and `website/api.html`, and `docs/HEALTH.md` with the settings, the new merge row and the two symptoms now in Troubleshooting.
This commit is contained in:
1 parent
34d28fa5c5
commit
aa6ec8ef22
14 files changed
+839
-63
No files matched your search
+18
-3
@@ -23,11 +23,26 @@ is re-sent), while real samples are identified by instant plus numbers and store
|
||||
every five minutes, hourly, or once a day all land the same way. `docs/HEALTH.md` has the settings,
|
||||
the merge table and the one configuration that is merely approximate rather than wrong.
|
||||
|
||||
The other half of that problem is **granularity**. "8,123 steps today" is a number you cannot look
|
||||
into, and the phone that sent it sent 288 readings to build it. With *Time Grouping: Hours* each
|
||||
hour arrives as its own bucket, and the receiver replaces that hour exactly the way it replaces a
|
||||
day (the hour in progress grows on every run), then recomputes the day as the sum of its hours — so
|
||||
the day total and the hourly detail can never disagree, and switching an automation from Days to
|
||||
Hours mid-day converges instead of double-counting. Tapping a card now opens the day **hour by
|
||||
hour**, the days before it, and every field the watch sent; when the automation still groups by
|
||||
Days, the sheet says so rather than drawing an empty chart. The hours are kept for a week (the day
|
||||
aggregates keep the full 400 days) and are fetched one metric and one day at a time, so a screen
|
||||
showing forty cards does not download 24 buckets × forty metrics to draw a grid. `Date range` is
|
||||
the setting that decides whether history exists at all: with HAE's default `Today`, yesterday is
|
||||
never sent, which is exactly what a card frozen on a single day looks like — `Previous 7 Days` is
|
||||
what the setup steps now say.
|
||||
|
||||
Also here: the watch's workouts are shown **read-only** in Salud and deliberately kept out of the
|
||||
history — they carry no sets or weights, so folding them into progression, PRs and the recovery
|
||||
model would be inventing data. Coverage: `api/vitals.js` (13 tests), the routes against a real
|
||||
server (4), the card model (18), plus the endpoint documented in `api/openapi.yaml` and the new
|
||||
`docs/HEALTH.md` setup guide.
|
||||
model would be inventing data. Coverage: `api/vitals.js` (19 tests), the routes against a real
|
||||
server (5), the card model and its hour/history rows (31), the screen and its detail sheet (12
|
||||
render tests), plus the endpoints documented in `api/openapi.yaml` and the new `docs/HEALTH.md`
|
||||
setup guide.
|
||||
|
||||
<!-- Everything below this note is the **upstream** changelog, kept verbatim: the entries name the
|
||||
project as it was called then (openGym) and reference upstream issue and merge-request
|
||||
|
||||
@@ -85,7 +85,8 @@ would catch is a change nothing checks here.
|
||||
- `workout-model.js`, `supersetFlow.js` — in-session workout state machine, incl. supersets.
|
||||
- `exercises.js` / `exercises-data.js` — the exercise library (1,324 built-ins + user-defined).
|
||||
- `vitals-view.js` — the Apple Health metric catalogue and card model (labels, units, which
|
||||
aggregate a card shows, workout rows). The server stores numbers; this decides how they read.
|
||||
aggregate a card shows, the hour rows and day history behind a card, workout rows). The server
|
||||
stores numbers; this decides how they read.
|
||||
- `music.js` — reading and validating the Apple Music share links a profile keeps. Apple has no
|
||||
API for somebody else's public playlists, so a playlist here is a link, not an integration.
|
||||
- `api.js` — the only place that talks to the backend (`fetch` wrapper, session cookie flows).
|
||||
|
||||
+95
-5
@@ -658,7 +658,7 @@ paths:
|
||||
step_count:
|
||||
units: count
|
||||
sources: [Apple Watch]
|
||||
days: [{ day: "2026-09-03", n: 1, lastTs: 1756900000000, f: { qty: { n: 1, sum: 12481, min: 12481, max: 12481, last: 12481, avg: 12481 } } }]
|
||||
days: [{ day: "2026-09-03", n: 1, lastTs: 1756900000000, hours: 0, f: { qty: { n: 1, sum: 12481, min: 12481, max: 12481, last: 12481, avg: 12481 } } }]
|
||||
heart_rate:
|
||||
units: bpm
|
||||
sources: [Apple Watch]
|
||||
@@ -682,6 +682,84 @@ paths:
|
||||
properties: { ok: { type: boolean } }
|
||||
'401': { $ref: '#/components/responses/Unauthorized' }
|
||||
|
||||
/api/vitals/hours:
|
||||
get:
|
||||
tags: [health]
|
||||
operationId: vitalsHours
|
||||
summary: One metric's hours on one day
|
||||
description: |
|
||||
The detail behind a card: the hourly buckets the phone sent for a single metric on a single
|
||||
day, oldest first, each carrying the same per-field aggregates a day does.
|
||||
|
||||
This is a separate request on purpose. The hours are the bulky part of health data (24
|
||||
buckets per metric per day), and they are only interesting once somebody taps a card, so a
|
||||
screen listing forty metrics fetches none of them.
|
||||
|
||||
A day the automation grouped by Day has no hours and comes back as an empty list rather
|
||||
than a fabricated one: the honest answer to "what did the hours look like" for a payload
|
||||
that never carried hours is that the automation does not send them. Set Time Grouping to
|
||||
**Hours** in Health Auto Export to keep them — the day remains the sum of its hours, so
|
||||
nothing is counted twice.
|
||||
|
||||
Session only, like `GET /api/vitals`: the ingest key is write-only.
|
||||
parameters:
|
||||
- name: metric
|
||||
in: query
|
||||
required: true
|
||||
schema: { type: string }
|
||||
description: The metric name exactly as HAE wrote it (`step_count`, `heart_rate`…).
|
||||
- name: day
|
||||
in: query
|
||||
required: true
|
||||
schema: { type: string, example: "2026-09-03" }
|
||||
description: A calendar day, in the phone's own date, as `YYYY-MM-DD`.
|
||||
responses:
|
||||
'200':
|
||||
description: The hours stored for that metric and day (empty when there are none).
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
ok: { type: boolean }
|
||||
metric:
|
||||
type: string
|
||||
nullable: true
|
||||
description: Echoed when the profile has that metric, null otherwise.
|
||||
day:
|
||||
type: string
|
||||
nullable: true
|
||||
description: Echoed when the day exists for that metric, null otherwise.
|
||||
units: { type: string }
|
||||
hours:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
h:
|
||||
type: string
|
||||
description: "The hour as the phone wrote it: `00`–`23`."
|
||||
n: { type: integer, description: Samples folded into this hour. }
|
||||
ts: { type: integer, description: Epoch ms of the hour's newest sample. }
|
||||
f:
|
||||
type: object
|
||||
additionalProperties: { $ref: '#/components/schemas/VitalsField' }
|
||||
example:
|
||||
ok: true
|
||||
metric: step_count
|
||||
day: "2026-09-03"
|
||||
units: count
|
||||
hours:
|
||||
- h: "08"
|
||||
n: 12
|
||||
ts: 1756900000000
|
||||
f: { qty: { n: 12, sum: 512, min: 3, max: 120, last: 44, avg: 42.7 } }
|
||||
- h: "09"
|
||||
n: 12
|
||||
ts: 1756903600000
|
||||
f: { qty: { n: 12, sum: 1340, min: 8, max: 310, last: 96, avg: 111.7 } }
|
||||
'401': { $ref: '#/components/responses/Unauthorized' }
|
||||
|
||||
/api/vitals/ingest:
|
||||
post:
|
||||
tags: [health]
|
||||
@@ -691,16 +769,21 @@ paths:
|
||||
The endpoint an iOS automation posts to. In Health Auto Export: Automation Type **REST
|
||||
API**, URL = this endpoint, header `Authorization: Bearer <ingest key>` (from
|
||||
`POST /api/vitals/key`), Export Format **JSON**, Export Version **2**, Summarize Data
|
||||
**On**, Time Grouping **Days**.
|
||||
**On**, Time Grouping **Hours** (or **Days** for totals with nothing behind them), Date
|
||||
Range **Previous 7 Days** — with the default range every sync carries today only, and the
|
||||
past is never in the file.
|
||||
|
||||
The merge is idempotent, which is what makes a five-minute cadence safe:
|
||||
|
||||
* A payload whose datapoints all sit on midnight is HAE's own day grouping, and a day total
|
||||
*replaces* the day it names — so the same day re-sent all afternoon converges on the
|
||||
day's total instead of adding up.
|
||||
* Anything else is a real sample (or an hour/minute grouping): a sample is identified by its
|
||||
instant plus its numbers and is counted once, so overlapping and disjoint windows both
|
||||
come out right. Repeats come back as `duplicates`.
|
||||
* A payload whose datapoints all sit on the hour is its hour grouping: the *hour* is
|
||||
replaced for the same reason (the hour in progress grows on every run), and the day is
|
||||
recomputed as the sum of its hours, so the day and the hourly detail can never disagree.
|
||||
* Anything else is a real sample: it is identified by its instant plus its numbers and is
|
||||
counted once, and it also lands in its own hour, which is where intraday detail comes
|
||||
from. Repeats come back as `duplicates`.
|
||||
|
||||
CSRF-exempt: the request carries its own credential in a header and has no session to
|
||||
borrow.
|
||||
@@ -1749,6 +1832,13 @@ components:
|
||||
day: { type: string, example: "2026-09-03" }
|
||||
n: { type: integer, description: Samples stored for this day. }
|
||||
lastTs: { type: integer, description: Epoch ms of the day's newest sample. }
|
||||
hours:
|
||||
type: integer
|
||||
description: >-
|
||||
How many hourly buckets this day has (0 or 1 when the automation grouped by Day, or
|
||||
when the samples arrived without an hour of their own). The buckets themselves are not
|
||||
in this response — `GET /api/vitals/hours` answers one metric and one day, because 24
|
||||
buckets × every metric × every day is not something a grid of cards should download.
|
||||
f:
|
||||
type: object
|
||||
description: Field name as HAE wrote it — `qty`, `Avg`, `asleep`, `systolic`…
|
||||
|
||||
+13
-1
@@ -19,7 +19,7 @@ import { startCadence } from './coach/cadence.js';
|
||||
import { startWarmup } from './coach/warmup.js';
|
||||
import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';
|
||||
import { verifyError } from './verify-error.js';
|
||||
import { parsePayload, mergeVitals, vitalsSeries, emptyVitals, RETENTION_DAYS } from './vitals.js';
|
||||
import { parsePayload, mergeVitals, vitalsSeries, vitalsHours, emptyVitals, RETENTION_DAYS } from './vitals.js';
|
||||
import { hostAllowed, readCapped, parseMusicPage } from './music.js';
|
||||
|
||||
const PORT = +(process.env.PORT || 3000);
|
||||
@@ -1070,6 +1070,18 @@ const routes = {
|
||||
json(res, 200, { ok: true, days, key: user.healthKey || null, ...vitalsSeries(doc || emptyVitals(), { days }) });
|
||||
},
|
||||
|
||||
// One metric's hours on one day — the detail sheet, and only the detail sheet. It is a separate
|
||||
// request because the hours are the bulky part of this data (24 buckets per metric per day) and
|
||||
// a screen that lists forty cards needs none of it until somebody taps one. Session-only, like
|
||||
// the day view: the ingest key is write-only.
|
||||
'GET /api/vitals/hours': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
const q = new URL(req.url, 'http://x').searchParams;
|
||||
const doc = readVitals(user.id);
|
||||
json(res, 200, { ok: true, ...vitalsHours(doc || emptyVitals(), { metric: q.get('metric'), day: q.get('day') }) });
|
||||
},
|
||||
|
||||
// Mint the ingest key on first use; a second call returns the one that exists rather than
|
||||
// silently invalidating the phone's configuration on a page reload.
|
||||
'POST /api/vitals/key': async (req, res) => {
|
||||
|
||||
@@ -211,6 +211,46 @@ test('a raw-sample automation accumulates a day without double counting, and a f
|
||||
assert.deepEqual(narrow.metrics.step_count.days.map(d => d.day), [today]);
|
||||
});
|
||||
|
||||
test('GET /api/vitals/hours opens one metric\'s day, and only with a session', async t => {
|
||||
const h = await startServer(t);
|
||||
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key;
|
||||
const read = async q => (await (await fetch(`${h.api}/api/vitals/hours?${q}`, { headers: cookie('u_h1') }))).json();
|
||||
|
||||
// Signed out, and with the write-only ingest key, there is nothing to read here either.
|
||||
assert.equal((await fetch(`${h.api}/api/vitals/hours?metric=step_count&day=${today}`)).status, 401);
|
||||
assert.equal((await fetch(`${h.api}/api/vitals/hours?metric=step_count&day=${today}`, { headers: { Authorization: `Bearer ${key}` } })).status, 401);
|
||||
|
||||
// "Time Grouping: Hours" beside a metric the phone totals by day.
|
||||
await ingest(h, key, { data: { metrics: [
|
||||
{ name: 'step_count', units: 'count', data: [
|
||||
{ qty: 500, date: `${today} 08:00:00 +0000` },
|
||||
{ qty: 900, date: `${today} 09:00:00 +0000` }
|
||||
] },
|
||||
{ name: 'weight_body_mass', units: 'kg', data: [{ qty: 80.5, date: `${today} 00:00:00 +0000` }] }
|
||||
] } });
|
||||
|
||||
const hours = await read(`metric=step_count&day=${today}`);
|
||||
assert.equal(hours.ok, true);
|
||||
assert.deepEqual(hours.hours.map(x => x.h), ['08', '09'], 'oldest hour first');
|
||||
assert.deepEqual(hours.hours.map(x => x.f.qty.sum), [500, 900]);
|
||||
assert.equal(hours.units, 'count');
|
||||
|
||||
// The day view still reads a day as one number, and now says whether there is anything behind it.
|
||||
const day = (await (await fetch(`${h.api}/api/vitals?days=1`, { headers: cookie('u_h1') })).json()).metrics.step_count.days[0];
|
||||
assert.equal(day.f.qty.sum, 1400);
|
||||
assert.equal(day.hours, 2);
|
||||
|
||||
// A metric the phone grouped by day has no hours, and neither does a day nobody sent.
|
||||
assert.deepEqual((await read(`metric=weight_body_mass&day=${today}`)).hours, []);
|
||||
assert.deepEqual((await read(`metric=step_count&day=2000-01-01`)).hours, []);
|
||||
assert.equal((await read(`metric=step_count&day=2000-01-01`)).day, null);
|
||||
// A day that is not a date is not looked up at all (nothing here builds a path from input).
|
||||
const bogus = await read('metric=step_count&day=not-a-day');
|
||||
assert.equal(bogus.day, null);
|
||||
assert.deepEqual(bogus.hours, []);
|
||||
assert.equal((await read('metric=nope&day=' + today)).metric, null);
|
||||
});
|
||||
|
||||
test('DELETE /api/vitals wipes the health file and leaves the account, the key and the workouts alone', async t => {
|
||||
const h = await startServer(t);
|
||||
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key;
|
||||
|
||||
+138
-5
@@ -9,8 +9,8 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
parsePayload, mergeVitals, vitalsSeries, emptyVitals, parseHaeDate, normalizeDoc,
|
||||
RETENTION_DAYS, LEDGER_MS
|
||||
parsePayload, mergeVitals, vitalsSeries, vitalsHours, emptyVitals, parseHaeDate, normalizeDoc,
|
||||
RETENTION_DAYS, LEDGER_MS, HOURS_KEPT_DAYS
|
||||
} from '../vitals.js';
|
||||
|
||||
const NOW = Date.parse('2026-05-01T23:30:00Z');
|
||||
@@ -230,17 +230,150 @@ test('workouts dedupe on name+start+end, newest first, and a re-send adds nothin
|
||||
assert.equal(again.doc.workouts.length, 2);
|
||||
});
|
||||
|
||||
/* ---------- hours: the detail a day total throws away ---------- */
|
||||
|
||||
test('an hourly payload keeps its hours, and the day is exactly their sum', () => {
|
||||
// "Time Grouping: Hours": every datapoint sits on the hour, so each one is that hour's total.
|
||||
const hours = qty9 => metric('step_count', 'count', [
|
||||
{ qty: 500, date: at('2026-05-01', '08:00:00') },
|
||||
{ qty: qty9, date: at('2026-05-01', '09:00:00') }
|
||||
]);
|
||||
const day = d => d.metrics.step_count.days['2026-05-01'];
|
||||
|
||||
const first = merge(emptyVitals(), parsePayload(hours(800)));
|
||||
assert.equal(day(first.doc).f.qty.sum, 1300, 'the day is the sum of its hours');
|
||||
assert.equal(day(first.doc).h['08'].f.qty.sum, 500);
|
||||
assert.equal(day(first.doc).h['09'].f.qty.sum, 800);
|
||||
assert.equal(day(first.doc).h['09'].f.qty.n, 1);
|
||||
|
||||
// The hour in progress grows on every run of a five-minute automation: replaced, never added,
|
||||
// because 500 + 900 + 1,340 steps in one hour is a number the watch never recorded.
|
||||
const grown = merge(first.doc, parsePayload(hours(1500)));
|
||||
assert.equal(day(grown.doc).h['09'].f.qty.sum, 1500);
|
||||
assert.equal(day(grown.doc).f.qty.sum, 2000, 'and the day moves with it');
|
||||
assert.equal(grown.stats.duplicates, 1, 'the finished hour was an exact repeat');
|
||||
assert.equal(grown.stats.points, 1);
|
||||
|
||||
const again = merge(grown.doc, parsePayload(hours(1500)));
|
||||
assert.equal(again.stats.points, 0);
|
||||
assert.equal(again.stats.duplicates, 2);
|
||||
assert.equal(day(again.doc).f.qty.sum, 2000);
|
||||
});
|
||||
|
||||
test('a raw sample that happens to sit on the hour does not wipe that hour', () => {
|
||||
// Both stamps are real samples ("Since Last Sync" at a 5-minute cadence), and the first one is
|
||||
// exactly on the hour. Reading that timestamp as an hour *total* would delete the samples
|
||||
// already stored in 09 — which is why the rule is decided from the payload, not the point.
|
||||
const doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
|
||||
{ qty: 300, date: at('2026-05-01', '09:00:00') },
|
||||
{ qty: 700, date: at('2026-05-01', '09:05:00') }
|
||||
]))).doc;
|
||||
const day = doc.metrics.step_count.days['2026-05-01'];
|
||||
assert.equal(day.h['09'].f.qty.sum, 1000);
|
||||
assert.equal(day.h['09'].f.qty.n, 2);
|
||||
assert.equal(day.f.qty.sum, 1000);
|
||||
|
||||
// ...and the same payload again is a no-op, on both levels.
|
||||
const again = merge(doc, parsePayload(metric('step_count', 'count', [
|
||||
{ qty: 300, date: at('2026-05-01', '09:00:00') },
|
||||
{ qty: 700, date: at('2026-05-01', '09:05:00') }
|
||||
])));
|
||||
assert.equal(again.stats.duplicates, 2);
|
||||
assert.equal(again.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1000);
|
||||
});
|
||||
|
||||
test('a day total and an hour total for the same day agree on which number is the day', () => {
|
||||
const hours = metric('step_count', 'count', [
|
||||
{ qty: 500, date: at('2026-05-01', '08:00:00') },
|
||||
{ qty: 900, date: at('2026-05-01', '09:00:00') }
|
||||
]);
|
||||
let doc = merge(emptyVitals(), parsePayload(hours)).doc;
|
||||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1400);
|
||||
|
||||
// A second automation grouped by Days sends the day itself: it is the better day number, and
|
||||
// the hours are a shape the total cannot contradict, so they stay for the sheet to draw.
|
||||
const total = merge(doc, parsePayload(metric('step_count', 'count', [{ qty: 1500, date: at('2026-05-01') }])));
|
||||
doc = total.doc;
|
||||
assert.equal(total.stats.points, 1);
|
||||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1500);
|
||||
assert.equal(Object.keys(doc.metrics.step_count.days['2026-05-01'].h).length, 2, 'the hours rode along');
|
||||
|
||||
// Then the hourly automation sends the next hour: it re-sends the whole day, so from here the
|
||||
// day is the hours again — the two rules converge instead of drifting apart.
|
||||
doc = merge(doc, parsePayload(metric('step_count', 'count', [
|
||||
{ qty: 500, date: at('2026-05-01', '08:00:00') },
|
||||
{ qty: 900, date: at('2026-05-01', '09:00:00') },
|
||||
{ qty: 200, date: at('2026-05-01', '10:00:00') }
|
||||
]))).doc;
|
||||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1600);
|
||||
});
|
||||
|
||||
test('a day stored before hours existed keeps its samples when the first hour arrives', () => {
|
||||
// A document written by an older version: the day has an aggregate and no hours, so its samples
|
||||
// cannot be placed in an hour. Rebuilding the day from the hours it does not have would throw
|
||||
// 2,000 steps away; the sample is added to the day the old way and the hour is what it is.
|
||||
const legacy = normalizeDoc({
|
||||
metrics: { step_count: { days: { '2026-05-01': { n: 4, lastTs: 0, f: { qty: { n: 4, sum: 2000, min: 100, max: 900, last: 900 } } } } } }
|
||||
});
|
||||
const r = merge(legacy, parsePayload(metric('step_count', 'count', [{ qty: 300, date: at('2026-05-01', '09:05:00') }])));
|
||||
const day = r.doc.metrics.step_count.days['2026-05-01'];
|
||||
assert.equal(day.f.qty.sum, 2300, 'nothing already stored was lost');
|
||||
assert.equal(day.f.qty.n, 5);
|
||||
assert.equal(day.h['09'].f.qty.sum, 300, 'and the hour holds only what has a time of its own');
|
||||
});
|
||||
|
||||
test('vitalsHours answers for one metric and one day, and invents nothing', () => {
|
||||
const doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
|
||||
{ qty: 500, date: at('2026-05-01', '08:00:00') },
|
||||
{ qty: 900, date: at('2026-05-01', '09:00:00') }
|
||||
]))).doc;
|
||||
const got = vitalsHours(doc, { metric: 'step_count', day: '2026-05-01' });
|
||||
assert.deepEqual(got.hours.map(x => x.h), ['08', '09'], 'oldest hour first');
|
||||
assert.equal(got.units, 'count');
|
||||
assert.equal(got.hours[0].f.qty.sum, 500);
|
||||
assert.equal(got.hours[0].f.qty.avg, 500);
|
||||
assert.ok(got.hours[0].ts > 0);
|
||||
|
||||
// A day the automation never grouped by hour — a day total, or a day that does not exist — is
|
||||
// an empty list rather than a fabricated one; the screen says why instead of drawing zeros.
|
||||
const grouped = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 1500, date: at('2026-05-01') }]))).doc;
|
||||
assert.deepEqual(vitalsHours(grouped, { metric: 'step_count', day: '2026-05-01' }).hours, []);
|
||||
assert.deepEqual(vitalsHours(doc, { metric: 'step_count', day: '2026-04-01' }).hours, []);
|
||||
assert.deepEqual(vitalsHours(doc, { metric: 'not_a_metric', day: '2026-05-01' }).hours, []);
|
||||
assert.equal(vitalsHours(doc, { metric: 'step_count', day: 'not-a-day' }).day, null);
|
||||
assert.equal(vitalsHours(emptyVitals(), { metric: 'step_count', day: '2026-05-01' }).metric, null);
|
||||
});
|
||||
|
||||
test('the hourly detail is pruned after a week while the day aggregates live on', () => {
|
||||
const start = Date.parse('2026-05-06T12:00:00Z');
|
||||
const doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
|
||||
{ qty: 100, date: at('2026-05-05', '08:00:00') },
|
||||
{ qty: 200, date: at('2026-05-06', '08:00:00') }
|
||||
])), start).doc;
|
||||
assert.ok(doc.metrics.step_count.days['2026-05-05'].h, 'hours are stored while they are recent');
|
||||
|
||||
// A week later the sheet can still ask for today and yesterday, and nothing it could show is
|
||||
// older than this: 24 buckets × every metric × every day of the year is what this avoids.
|
||||
const later = merge(doc, parsePayload(metric('step_count', 'count', [{ qty: 300, date: at('2026-05-13', '08:00:00') }])), Date.parse('2026-05-13T12:00:00Z')).doc;
|
||||
assert.equal(later.metrics.step_count.days['2026-05-05'].h, undefined, 'the hours of an old day are gone');
|
||||
assert.equal(later.metrics.step_count.days['2026-05-05'].f.qty.sum, 100, 'the day itself stays');
|
||||
assert.ok(later.metrics.step_count.days['2026-05-06'].h, 'and a day inside the window keeps its own');
|
||||
assert.ok(HOURS_KEPT_DAYS >= 2 && HOURS_KEPT_DAYS <= RETENTION_DAYS);
|
||||
});
|
||||
|
||||
/* ---------- housekeeping ---------- */
|
||||
|
||||
test('the dedupe ledger and the day buckets are both pruned, so the file stays bounded', () => {
|
||||
const first = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-01', '09:00:00') }])), NOW);
|
||||
// Five past the hour on purpose: a sample that sits exactly on the hour is indistinguishable
|
||||
// from an hour bucket HAE grouped itself, and that shape has no ledger (see the hour tests).
|
||||
const first = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-01', '09:05:00') }])), NOW);
|
||||
const seen = first.doc.metrics.step_count.seen;
|
||||
assert.equal(Object.keys(seen).length, 1);
|
||||
assert.equal(seen[Object.keys(seen)[0]], Date.parse('2026-05-01T09:00:00Z'));
|
||||
assert.equal(seen[Object.keys(seen)[0]], Date.parse('2026-05-01T09:05:00Z'));
|
||||
|
||||
// A sync a week later: last week's sample can no longer be a repeat, so its ledger row goes
|
||||
// while the day it belongs to stays.
|
||||
const later = merge(first.doc, parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-08', '09:00:00') }])), Date.parse('2026-05-08T12:00:00Z')).doc;
|
||||
const later = merge(first.doc, parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-08', '09:05:00') }])), Date.parse('2026-05-08T12:00:00Z')).doc;
|
||||
assert.equal(Object.keys(later.metrics.step_count.seen).length, 1, 'the stale ledger row is gone');
|
||||
assert.deepEqual(Object.keys(later.metrics.step_count.days), ['2026-05-01', '2026-05-08']);
|
||||
|
||||
|
||||
+169
-16
@@ -22,7 +22,13 @@
|
||||
* right here: the newer, larger total is the better answer, and re-sending the same
|
||||
* number is a no-op. Idempotent by construction, no ledger needed.
|
||||
*
|
||||
* otherwise real timestamps (raw samples, or grouped by hour/minute/second)
|
||||
* hourAggregated() every datapoint sits exactly on the hour ("Time Grouping: Hours")
|
||||
* → the *hour* bucket is replaced, for the same reason a day total is: the hour in progress
|
||||
* is re-sent with a larger value on every run, so union would count 512 steps as
|
||||
* 512 + 900 + 1340. The day is then recomputed as the sum of its hours (deriveDay), which
|
||||
* is what keeps the day number and the hourly detail from ever disagreeing.
|
||||
*
|
||||
* otherwise real timestamps (raw samples, or grouped by minute/second)
|
||||
* → union: a sample is identified by its instant plus its numbers and seen once. A repeat
|
||||
* is skipped, a genuinely new sample is added. Overlapping and disjoint windows both
|
||||
* come out right, because "have I seen this exact sample" is the question that does not
|
||||
@@ -32,8 +38,18 @@
|
||||
* overlapping window: the minute still in progress is re-sent with a larger value each time, so
|
||||
* it is a new sample by the union rule and its value is added twice. The error is bounded by one
|
||||
* partial minute of the cheapest metric (a handful of steps, a few hundredths of a kcal) and the
|
||||
* setup steps in docs/HEALTH.md say to group by Days. Being explicit about that beats a "smart"
|
||||
* rule that silently miscounts a whole day.
|
||||
* setup steps in docs/HEALTH.md say to group by Days or Hours. Being explicit about that beats a
|
||||
* "smart" rule that silently miscounts a whole day.
|
||||
*
|
||||
* ── Why the hours are kept at all ────────────────────────────────────────────────────────────
|
||||
*
|
||||
* A day total is the number people quote and the one thing a day is worth here, but it is also a
|
||||
* dead end: "8,123 steps today" is a figure you cannot look into, and the phone that sent it sent
|
||||
* 288 readings to build it. Grouping by Hours is the setting that keeps that shape — each hour
|
||||
* arrives as its own bucket with a real instant — and the buckets are stored beside the day, so
|
||||
* tapping a card can show the day hour by hour. Days grouping sends one point per metric per day
|
||||
* and there is no intraday detail in the payload to keep; that is a property of the automation,
|
||||
* not of this file, and the Salud screen says so rather than showing an empty hour list.
|
||||
*
|
||||
* ── What a stored document looks like ────────────────────────────────────────────────────────
|
||||
*
|
||||
@@ -49,7 +65,8 @@
|
||||
* step_count: {
|
||||
* units: 'count', sources: ['iPhone'],
|
||||
* days: { '2026-05-01': { n: 288, lastTs: 1699999999999,
|
||||
* f: { qty: { sum, min, max, last, n } } } },
|
||||
* f: { qty: { sum, min, max, last, n } },
|
||||
* h: { '13': { n: 12, lastTs: …, f: { qty: {…} } } } } },
|
||||
* seen: { '2026-05-01 13:05:00 +0200|qty:12': 1699999999999 }
|
||||
* }
|
||||
* },
|
||||
@@ -70,6 +87,13 @@ export const LEDGER_MS = 72 * 3600 * 1000;
|
||||
/** Days kept per metric. A little over a year, so "same day last year" still exists. */
|
||||
export const RETENTION_DAYS = 400;
|
||||
export const MAX_WORKOUTS = 300;
|
||||
/**
|
||||
* Days whose *hourly* buckets are kept. Detail is what makes a file grow (24 buckets × every
|
||||
* metric × every day), and it is only interesting for the last few days: "what did this morning
|
||||
* look like" is a question about today and yesterday, never about March. The day aggregates
|
||||
* survive this and live RETENTION_DAYS.
|
||||
*/
|
||||
export const HOURS_KEPT_DAYS = 7;
|
||||
/** Sources remembered per metric — decorative, but it answers "which watch sent this?" */
|
||||
const MAX_SOURCES = 4;
|
||||
const MAX_LEDGER_KEYS = 20000; // hard ceiling; the time-based prune is the real bound
|
||||
@@ -138,6 +162,8 @@ export function parseHaeDate(value) {
|
||||
|
||||
/** True when HAE grouped this datapoint onto a boundary rather than sampling it in real time. */
|
||||
const isMidnight = t => t.time === '00:00:00';
|
||||
/** ...and onto an hour: the shape "Time Grouping: Hours" produces, so each bucket is a total. */
|
||||
const onTheHour = t => t.time.slice(3) === '00:00';
|
||||
|
||||
// Fields on a datapoint that are not measurements. Everything else numeric is kept, so a metric
|
||||
// this file has never seen still stores its numbers instead of being dropped.
|
||||
@@ -255,6 +281,21 @@ function dayGrouped(points) {
|
||||
return points.length > 0 && points.every(p => isMidnight(p.at));
|
||||
}
|
||||
|
||||
/**
|
||||
* ...and does it look like its hour-by-hour one? Decided from the whole payload, never from a
|
||||
* single timestamp, because a raw 5-minute automation also has samples that sit exactly on the
|
||||
* hour: treating one of those as an hour *total* would wipe the hour it belongs to. Homogeneity
|
||||
* is the tell — HAE stamps every point the way its Time Grouping says, so a payload where the
|
||||
* minutes and seconds are all zero is grouping by hour, and one with a single stray minute is not.
|
||||
*
|
||||
* A raw payload that happens to be entirely on the hour is read as grouped, and that is benign:
|
||||
* for an hour being sent for the first time the two rules agree, and for one already stored HAE
|
||||
* would only re-send it identically.
|
||||
*/
|
||||
function hourGrouped(points) {
|
||||
return points.length > 0 && points.every(p => onTheHour(p.at));
|
||||
}
|
||||
|
||||
const dayKeyOk = k => /^\d{4}-\d{2}-\d{2}$/.test(k);
|
||||
|
||||
function addFields(bucket, fields) {
|
||||
@@ -274,6 +315,34 @@ const bucketFrom = (fields, ts) => {
|
||||
return b;
|
||||
};
|
||||
|
||||
/**
|
||||
* Recompute a day from its hours.
|
||||
*
|
||||
* A day with hours is not a bucket anybody increments — it is a *projection* of them, so the two
|
||||
* can never disagree: fourteen hourly buckets of 500 steps and "7,000 today" are the same number
|
||||
* by construction, and a partial hour replaced by a fuller one moves both. Aggregates are per
|
||||
* field the way the reading side wants them (`sum` for a counter, `n` so a rate averages), and
|
||||
* `last` comes from the newest hour that carried the field, because the hours are walked in order.
|
||||
*/
|
||||
function deriveDay(day) {
|
||||
const f = {};
|
||||
let n = 0;
|
||||
for (const hh of Object.keys(day.h || {}).sort()) {
|
||||
const hb = day.h[hh];
|
||||
n += hb.n || 0;
|
||||
for (const [k, v] of Object.entries(hb.f || {})) {
|
||||
const cur = f[k] || (f[k] = { n: 0, sum: 0, min: null, max: null, last: null });
|
||||
cur.n += v.n || 0;
|
||||
cur.sum += v.sum || 0;
|
||||
if (v.min != null && (cur.min == null || v.min < cur.min)) cur.min = v.min;
|
||||
if (v.max != null && (cur.max == null || v.max > cur.max)) cur.max = v.max;
|
||||
cur.last = v.last;
|
||||
}
|
||||
}
|
||||
day.f = f;
|
||||
day.n = n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold one parsed payload into a stored document. Pure: the input document is not modified.
|
||||
*
|
||||
@@ -289,6 +358,9 @@ export function mergeVitals(doc, payload, now = Date.now()) {
|
||||
const cur = out.metrics[m.name] || { units: '', sources: [], days: {}, seen: {} };
|
||||
if (m.units) cur.units = m.units;
|
||||
const replace = dayGrouped(m.points);
|
||||
// The hour rule only applies when the payload is not a day total: a day-grouped point is
|
||||
// midnight-stamped and would otherwise also read as "on the hour".
|
||||
const byHour = !replace && hourGrouped(m.points);
|
||||
// The ledger is only consulted by the union path, and only for instants recent enough to be
|
||||
// re-sent by the next automation run — anything older is pruned and can no longer be a repeat.
|
||||
pruneLedger(cur.seen, now);
|
||||
@@ -305,15 +377,53 @@ export function mergeVitals(doc, payload, now = Date.now()) {
|
||||
// every run after the first). `f` is compared as a whole because a day total and a
|
||||
// once-a-day gauge both live in it.
|
||||
if (prev && prev.n === 1 && sameFields(prev.f, p.fields)) { stats.duplicates++; continue; }
|
||||
cur.days[key] = bucketFrom(p.fields, p.at.ms);
|
||||
// The hours already stored for that day ride along: the phone's own total is the better
|
||||
// day number, but it says nothing about the shape of the day and the hourly view is
|
||||
// built from what does. `own` records exactly that — this day's number is the phone's,
|
||||
// not the sum of its hours (see below).
|
||||
cur.days[key] = { ...bucketFrom(p.fields, p.at.ms), h: prev?.h || {}, own: true };
|
||||
stats.points++;
|
||||
continue;
|
||||
}
|
||||
const id = sampleId(p);
|
||||
if (cur.seen[id] != null) { stats.duplicates++; continue; }
|
||||
cur.seen[id] = p.at.ms;
|
||||
addFields(cur.days[key] || (cur.days[key] = { n: 0, lastTs: p.at.ms, f: {} }), p.fields);
|
||||
cur.days[key].lastTs = Math.max(cur.days[key].lastTs, p.at.ms);
|
||||
const day = cur.days[key] || (cur.days[key] = { n: 0, lastTs: p.at.ms, f: {}, h: {} });
|
||||
const hours = day.h || (day.h = {});
|
||||
const hh = p.at.time.slice(0, 2);
|
||||
if (byHour) {
|
||||
// An hour the phone grouped itself: replaced, never unioned, because the hour in progress
|
||||
// grows on every run of a five-minute automation.
|
||||
const prev = hours[hh];
|
||||
if (prev && sameFields(prev.f, p.fields)) { stats.duplicates++; continue; }
|
||||
hours[hh] = bucketFrom(p.fields, p.at.ms);
|
||||
// The exact datapoint is remembered anyway: a payload grouped by hour and a later one
|
||||
// carrying real minutes can describe the same instant — the automation was reconfigured,
|
||||
// or two of them write to one profile — and the union path can only see the ledger, so
|
||||
// without this row it would count that instant a second time.
|
||||
cur.seen[sampleId(p)] = p.at.ms;
|
||||
} else {
|
||||
const id = sampleId(p);
|
||||
if (cur.seen[id] != null) { stats.duplicates++; continue; }
|
||||
cur.seen[id] = p.at.ms;
|
||||
addFields(hours[hh] || (hours[hh] = { n: 0, lastTs: p.at.ms, f: {} }), p.fields);
|
||||
hours[hh].lastTs = Math.max(hours[hh].lastTs, p.at.ms);
|
||||
}
|
||||
day.lastTs = Math.max(day.lastTs, p.at.ms);
|
||||
/* Recompute the day from its hours, which keeps this idempotent: the same hour arriving
|
||||
three times, or a partial hour replaced by a fuller one, leaves the same number behind.
|
||||
Two days are the exceptions, and both are days whose aggregate is not "the hours so far":
|
||||
own — the phone totalled this day itself (Days grouping). The hourly automation that
|
||||
then takes over re-sends the whole day, so its hours supersede the total and
|
||||
the day is derived from here on.
|
||||
!hc — a day stored by an older version of this file, whose samples have no hour
|
||||
attribution. Summing its (empty, or partly filled) hours would delete what is
|
||||
already there, so the new sample is added to the day the old way and the hours
|
||||
beside it stay what they honestly are: the part that has a time of its own. */
|
||||
if (day.own || day.hc || day.n === 0) {
|
||||
delete day.own;
|
||||
day.hc = true;
|
||||
deriveDay(day);
|
||||
} else {
|
||||
addFields(day, p.fields);
|
||||
}
|
||||
stats.points++;
|
||||
}
|
||||
pruneLedger(cur.seen, now, true);
|
||||
@@ -368,17 +478,43 @@ function pruneLedger(seen, now, enforceCap = false) {
|
||||
|
||||
function pruneDays(doc, now) {
|
||||
const oldest = new Date(now - RETENTION_DAYS * 86400000).toISOString().slice(0, 10);
|
||||
// Hours are the detail, and detail is what makes a file grow: 24 buckets × every metric × every
|
||||
// day of a year is a document nobody wants to load. A week of them is what "what did today look
|
||||
// like" needs — the day aggregates underneath are untouched and live out the full year.
|
||||
const hoursOldest = new Date(now - HOURS_KEPT_DAYS * 86400000).toISOString().slice(0, 10);
|
||||
for (const m of Object.values(doc.metrics)) {
|
||||
for (const day of Object.keys(m.days)) if (day < oldest) delete m.days[day];
|
||||
for (const [day, b] of Object.entries(m.days)) {
|
||||
if (day < oldest) { delete m.days[day]; continue; }
|
||||
if (b && b.h && day < hoursOldest) {
|
||||
// `hc` goes with them: it means "this day is the sum of its hours", and with the hours
|
||||
// gone that claim would make the next sample for that day rebuild it from nothing.
|
||||
delete b.h;
|
||||
delete b.hc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- reading ---------- */
|
||||
|
||||
/** One bucket's fields, as the client wants them: the count, the total, and the mean it implies. */
|
||||
function projectFields(f) {
|
||||
const out = {};
|
||||
for (const [k, v] of Object.entries(f || {})) {
|
||||
out[k] = { n: v.n, sum: v.sum, min: v.min, max: v.max, last: v.last, avg: v.n ? v.sum / v.n : null };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Project a stored document into the compact series the view renders, oldest day first.
|
||||
* Aggregates are per *field* — `qty.sum` for a counter, `Avg.last` for a rate — so the client
|
||||
* never has to know how HAE grouped things.
|
||||
*
|
||||
* Each day also says how many hourly buckets it has. That count is the difference between a card
|
||||
* whose detail is a single number and one you can open up, and sending the number instead of the
|
||||
* buckets keeps this response the size of a card list: the hours themselves are one metric and
|
||||
* one day per request (vitalsHours below), fetched when somebody actually taps in.
|
||||
*/
|
||||
export function vitalsSeries(doc, { days = 90, now = Date.now() } = {}) {
|
||||
const d = normalizeDoc(doc);
|
||||
@@ -393,13 +529,30 @@ export function vitalsSeries(doc, { days = 90, now = Date.now() } = {}) {
|
||||
for (const day of Object.keys(m.days).sort()) {
|
||||
if (day < from) continue;
|
||||
const b = m.days[day];
|
||||
const f = {};
|
||||
for (const [k, v] of Object.entries(b.f || {})) {
|
||||
f[k] = { n: v.n, sum: v.sum, min: v.min, max: v.max, last: v.last, avg: v.n ? v.sum / v.n : null };
|
||||
}
|
||||
out.push({ day, n: b.n, lastTs: b.lastTs, f });
|
||||
out.push({ day, n: b.n, lastTs: b.lastTs, hours: Object.keys(b.h || {}).length, f: projectFields(b.f) });
|
||||
}
|
||||
if (out.length) metrics[name] = { units: m.units, sources: m.sources, days: out };
|
||||
}
|
||||
return { updatedAt: d.updatedAt, last: d.last, metrics, workouts: d.workouts };
|
||||
}
|
||||
|
||||
/**
|
||||
* One metric's hours on one day, oldest first — what the detail sheet opens.
|
||||
*
|
||||
* A day that HAE grouped itself (Days grouping) has no hours and comes back empty rather than
|
||||
* invented: the honest answer to "what did the hours look like" for a payload that never carried
|
||||
* hours is "the automation does not send them", and the screen says that instead.
|
||||
*/
|
||||
export function vitalsHours(doc, { metric, day } = {}) {
|
||||
const d = normalizeDoc(doc);
|
||||
const name = String(metric || '');
|
||||
const m = Object.prototype.hasOwnProperty.call(d.metrics, name) ? d.metrics[name] : null;
|
||||
const key = String(day || '');
|
||||
const b = m && dayKeyOk(key) ? m.days[key] : null;
|
||||
const hours = [];
|
||||
for (const hh of Object.keys((b && b.h) || {}).sort()) {
|
||||
const hb = b.h[hh];
|
||||
hours.push({ h: hh, n: hb.n, ts: hb.lastTs, f: projectFields(hb.f) });
|
||||
}
|
||||
return { metric: m ? name : null, day: b ? key : null, units: m ? m.units : '', hours };
|
||||
}
|
||||
+28
-16
@@ -30,8 +30,8 @@ so), open **Salud → ⚙**, and:
|
||||
- **Export Version**: `2`
|
||||
- **Data Type**: `Health Metrics` (add `Workouts` as a second automation, or include both)
|
||||
- **Summarize Data**: `On`
|
||||
- **Time Grouping**: `Days`
|
||||
- **Date Range**: `Previous 7 Days` (or `Default`)
|
||||
- **Time Grouping**: `Hours` (or `Days` if you only ever want one number a day)
|
||||
- **Date Range**: `Previous 7 Days` (not `Today` — see below)
|
||||
- **Sync Cadence**: whatever you like — 5 minutes, hourly, once a day.
|
||||
4. **Manual Sync → Export** once, to prove it works. It runs in the foreground, so it works even
|
||||
while iOS is being cautious about background time.
|
||||
@@ -43,9 +43,9 @@ neither can see the other's, and the URL is the only thing they share.
|
||||
|
||||
| Setting | Value | Why |
|
||||
| --- | --- | --- |
|
||||
| Summarize Data | On | Sends day aggregates instead of every sample. Smaller payloads, and the numbers on the cards are the ones Apple already summarised. |
|
||||
| Time Grouping | Days | Makes each sync carry the **whole day's total**, which the receiver can then replace rather than add up (see §2). Raw samples work too, at more bytes and the same result. |
|
||||
| Date Range | Previous 7 Days / Default | Always re-sends the last few days, so a sync missed while the phone was locked or in Low Power Mode is filled in by the next one. |
|
||||
| Summarize Data | On | Sends aggregates instead of every sample. Smaller payloads, and the numbers on the cards are the ones Apple already summarised. |
|
||||
| Time Grouping | Hours | Each sync carries the hours of the day, so the day is the **sum of its hours** and the detail sheet can draw the day hour by hour. Every hour is replaced by the next report of it, so a five-minute cadence is still safe (see §2). `Days` is the smaller option: one total per day, exact, and with nothing behind it to look into. |
|
||||
| Date Range | Previous 7 Days | How much history exists at all. With `Today` (the default) every sync carries today only, and yesterday is never in the file — the cards then have a single day to draw. `Previous 7 Days` re-sends the last week every time, which also fills in a sync missed while the phone was locked or in Low Power Mode. |
|
||||
| Export Version | 2 | The current payload shape (`{"data":{"metrics":[…]}}`). Version 1 is also accepted. |
|
||||
|
||||
Apple's own limits apply and cannot be worked around: HAE cannot read Health data while the phone
|
||||
@@ -67,7 +67,12 @@ configured for, so the rule is chosen per payload, from the payload's own shape:
|
||||
| The payload looks like | What the receiver does | Safe with |
|
||||
| --- | --- | --- |
|
||||
| Every datapoint sits exactly on midnight (`00:00:00`) — HAE's **Days** grouping, i.e. a **total** per day | The day it names is **replaced** by it, in full. A day total only ever supersedes another day total, so re-sending the same day all afternoon converges on the day's total instead of accumulating. | Overlapping windows, disjoint windows, manual re-exports, first sync of a year of history. |
|
||||
| Anything else (real sample timestamps, or Hour/Minute grouping) | Each sample is identified by its **instant plus its numbers** and stored once. A repeat is skipped and reported back as `duplicates`; a genuinely new sample is added. | Overlapping windows (repeats detected) and disjoint ones (new samples add). |
|
||||
| Every datapoint sits exactly on the hour (`HH:00:00`) — HAE's **Hours** grouping, i.e. a **total** per hour | That **hour** is replaced, for the same reason: the hour in progress grows on every run. The day is then recomputed as the sum of its hours, so the day total and the hourly detail can never disagree. The hours are what the detail sheet draws (kept for 7 days; the day aggregates live on). | Overlapping windows, disjoint windows, and switching an automation from `Days` to `Hours` mid-day. |
|
||||
| Anything else — real sample timestamps, or Minute grouping | Each sample is identified by its **instant plus its numbers** and stored once, in its own hour. A repeat is skipped and reported back as `duplicates`; a genuinely new sample is added. | Overlapping windows (repeats detected) and disjoint ones (new samples add). |
|
||||
|
||||
The hour rule is decided from the **whole payload**, never from a single timestamp: a five-minute
|
||||
automation also produces samples that land exactly on the hour, and reading one of those as an hour
|
||||
total would wipe the hour it belongs to.
|
||||
|
||||
Day keys come from the date **the phone wrote**, never from the server's clock. HAE stamps each
|
||||
sample with its own local offset, so grouping by a server-local date would slide every evening's
|
||||
@@ -76,8 +81,9 @@ steps into the next day for anyone not on UTC.
|
||||
The one configuration neither rule rescues is **Minute** grouping with an overlapping window: the
|
||||
minute still in progress is re-sent with a larger value each time, so it is a new sample by the
|
||||
union rule and gets added twice. The error is bounded by one partial minute of the cheapest metric —
|
||||
a handful of steps, a few hundredths of a kcal — and grouping by `Days` removes it entirely. Being
|
||||
explicit about that is better than a cleverer rule that silently miscounts a whole day.
|
||||
a handful of steps, a few hundredths of a kcal — and grouping by `Days` (or `Hours`) removes it
|
||||
entirely. Being explicit about that is better than a cleverer rule that silently miscounts a whole
|
||||
day.
|
||||
|
||||
What every sync answers with is the receipt: how many points arrived, how many were recognised as
|
||||
already stored, and what the profile holds now.
|
||||
@@ -108,8 +114,10 @@ Inside, numbers are kept **per day and per field, generically**:
|
||||
"last": { "ts": 1756900000000, "metrics": 12, "points": 40, "duplicates": 288, "workouts": 1 },
|
||||
"metrics": {
|
||||
"heart_rate": { "units": "bpm", "sources": ["Apple Watch"],
|
||||
"days": { "2026-09-03": { "n": 288, "lastTs": 1756900000000,
|
||||
"f": { "Avg": { "n": 288, "sum": 20000, "min": 55, "max": 96, "last": 72, "avg": 69.4 } } } },
|
||||
"days": { "2026-09-03": { "n": 24, "lastTs": 1756900000000,
|
||||
"f": { "Avg": { "n": 24, "sum": 1665.6, "min": 55, "max": 96, "last": 72, "avg": 69.4 } },
|
||||
"h": { "08": { "n": 1, "lastTs": 1756900400000,
|
||||
"f": { "Avg": { "n": 1, "sum": 62, "min": 62, "max": 62, "last": 62 } } } } } },
|
||||
"seen": { "2026-09-03 09:05:00 +0200|Avg:70": 1756900000000 } } },
|
||||
"workouts": [ { "name": "Walking", "start": 1756900000000, "durMin": 60, "avgHr": 128, "fields": {} } ] }
|
||||
```
|
||||
@@ -125,6 +133,7 @@ Bounds, all enforced on write:
|
||||
| Kept | Limit | Why |
|
||||
| --- | --- | --- |
|
||||
| Days per metric | 400 | A little over a year, so "this time last year" still exists. |
|
||||
| Hours per day | 7 days | Detail is what makes the file grow (24 buckets × every metric × every day of a year); it is also only interesting for the last few days, which is what the detail sheet opens. The day aggregates underneath keep the full 400. |
|
||||
| Dedupe ledger per metric | 72 h | A repeat can only be recent — the next automation run is minutes away, not days. |
|
||||
| Workouts | newest 300 | A wrist that records every walk produces thousands a year; nobody scrolls past the last few hundred. |
|
||||
| Request body | 32 MB | A full-history export with Summarize off is tens of megabytes. Over it: `413` with a readable message. The bundled web container allows this **one route** the bigger body (`web/nginx.conf.template`); every other `/api` path stays at 5 MB. Behind your own reverse proxy, raise `client_max_body_size` there too, or it is your proxy's 413 the phone sees. |
|
||||
@@ -164,9 +173,11 @@ and you have backed up your health file too.
|
||||
| --- | --- |
|
||||
| `401 invalid ingest key` | Wrong key, a revoked one, or the header is missing `Bearer `. The key is shown in Salud → ⚙; re-copy it rather than retyping. A disabled account also answers 401. |
|
||||
| `400 not a Health Auto Export JSON export` | Export Format is set to **CSV**, or the URL points at something else. Set JSON. |
|
||||
| `413 body too large` | A first sync with everything selected and Summarize off. Turn Summarize Data on, group by Days, or split the metrics across two automations. Behind your own reverse proxy (Caddy, Cloudflare, a second nginx), raise its body limit for this path as well — the bundled stack already does. |
|
||||
| `413 body too large` | A first sync with everything selected and Summarize off. Turn Summarize Data on, group by Days or Hours, or split the metrics across two automations. Behind your own reverse proxy (Caddy, Cloudflare, a second nginx), raise its body limit for this path as well — the bundled stack already does. |
|
||||
| `200` with `received.points: 0` every time | Working, with nothing to add: bring your phone to Health Auto Export → Manual Sync → Export, and check Date Range covers a day that has data. |
|
||||
| Nothing on the screen | Salud fetches 30 days by default — widen the range. A metric HAE has no samples for is skipped rather than shown as a zero. |
|
||||
| A card shows one day, and its sheet has nothing before it | The automation's **Date Range** is `Today`, so yesterday was never sent. Set it to `Previous 7 Days`; the past cannot be invented server-side. |
|
||||
| The detail sheet says "arrived as one total a day", with no hour list | **Time Grouping** is `Days`: the payload has one number per day and no hours to draw. Set it to `Hours` — the day stays the sum of its hours, so nothing is double-counted, and the hour list appears from the next sync on. |
|
||||
| Steps look half a day behind | HAE cannot read Health while the phone is locked. Open the app (or tap the Automations widget) and the day fills in. |
|
||||
| A metric shows under **Other** | Marketing-free behaviour: the catalogue in `vitals-view.js` covers ~50 metrics by name. Anything else is still stored and still charted — humanised, with every field HAE sent listed in its detail sheet. Add a line to `METRICS` to give it a better label, unit and aggregate. |
|
||||
| Workouts do not appear in History | By design. They are read-only in Salud; see the top of this file. |
|
||||
@@ -174,13 +185,14 @@ and you have backed up your health file too.
|
||||
## 6. For developers
|
||||
|
||||
- `api/vitals.js` — parsing, the merge rules of §2, retention. Pure; tests in `api/test/vitals.test.js`
|
||||
cover the merge under overlapping, disjoint, day-grouped, raw, heart-rate, sleep and
|
||||
blood-pressure payloads, plus pruning and timezone handling.
|
||||
- `api/server.js` — the five routes and the ingest key. Route tests in `api/test/server-vitals.test.js`
|
||||
cover the merge under overlapping, disjoint, day-grouped, hour-grouped, raw, heart-rate, sleep
|
||||
and blood-pressure payloads, plus pruning (days and hours), the day-from-hours projection and
|
||||
timezone handling.
|
||||
- `api/server.js` — the six routes and the ingest key. Route tests in `api/test/server-vitals.test.js`
|
||||
run the real server and check isolation between profiles, that the key cannot read, and that ten
|
||||
re-sends of the same window change nothing.
|
||||
- `frontend/src/lib/vitals-view.js` — the metric catalogue, the card model, the units and the
|
||||
workout rows. Tests beside it.
|
||||
- `frontend/src/lib/vitals-view.js` — the metric catalogue, the card model, the units, the hour
|
||||
rows and the day history the detail sheet lists. Tests beside it.
|
||||
- `frontend/src/views/Health.jsx` — the screen and its two sheets.
|
||||
- Endpoints are documented in `api/openapi.yaml` (tag `health`); rebuild `website/api.html` after
|
||||
changing them.
|
||||
@@ -162,27 +162,32 @@ export function specOf(name) {
|
||||
}
|
||||
|
||||
/**
|
||||
* One day's number for one metric.
|
||||
* The number to show for one set of per-field aggregates.
|
||||
*
|
||||
* A known metric uses its catalogue rule. An unknown one shows the field with the most samples
|
||||
* that day — the number the watch actually measured most often — falling back to whichever field
|
||||
* is there, so nothing is hidden just because nobody wrote a rule for it.
|
||||
*/
|
||||
export function valueOfDay(day, s) {
|
||||
const f = (day && day.f) || {}
|
||||
const keys = Object.keys(f)
|
||||
export function valueOfFields(f, s) {
|
||||
const src = f || {}
|
||||
const keys = Object.keys(src)
|
||||
if (!keys.length) return null
|
||||
if (s.fields) {
|
||||
const field = s.fields.find(k => f[k] && (AGG[s.agg] || AGG.sum)(f[k]) != null)
|
||||
if (field) return (AGG[s.agg] || AGG.sum)(f[field])
|
||||
const field = s.fields.find(k => src[k] && (AGG[s.agg] || AGG.sum)(src[k]) != null)
|
||||
if (field) return (AGG[s.agg] || AGG.sum)(src[field])
|
||||
}
|
||||
if (s.unknown) {
|
||||
const best = keys.slice().sort((a, b) => (f[b].n || 0) - (f[a].n || 0))[0]
|
||||
return f[best].avg ?? f[best].last ?? f[best].sum ?? null
|
||||
const best = keys.slice().sort((a, b) => (src[b].n || 0) - (src[a].n || 0))[0]
|
||||
return src[best].avg ?? src[best].last ?? src[best].sum ?? null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** One day's number for one metric. */
|
||||
export function valueOfDay(day, s) {
|
||||
return valueOfFields((day && day.f) || {}, s)
|
||||
}
|
||||
|
||||
/** How many days of samples a metric's series covers, for the "n days" captions. */
|
||||
const pointsOf = series => series.reduce((n, p) => n + (p.n || 0), 0)
|
||||
|
||||
@@ -200,7 +205,7 @@ export function metricCards(data, { days = 90 } = {}) {
|
||||
for (const [name, m] of Object.entries(metrics)) {
|
||||
const s = specOf(name)
|
||||
const series = ((m && m.days) || [])
|
||||
.map(d => ({ day: d.day, v: valueOfDay(d, s), n: d.n || 0, lastTs: d.lastTs || null }))
|
||||
.map(d => ({ day: d.day, v: valueOfDay(d, s), n: d.n || 0, lastTs: d.lastTs || null, hours: d.hours || 0 }))
|
||||
.filter(p => p.v != null && Number.isFinite(p.v))
|
||||
if (!series.length) continue
|
||||
const latest = series[series.length - 1]
|
||||
@@ -221,6 +226,10 @@ export function metricCards(data, { days = 90 } = {}) {
|
||||
// When the newest reading actually landed. The phone pushes every few minutes, so this is
|
||||
// what makes "today's number" verifiable rather than a claim: a card can say "hace 12 min".
|
||||
lastTs: latest.lastTs,
|
||||
/* Whether the newest day has hours behind it. 0 or 1 means the automation grouped by day:
|
||||
there is one number for the day and nothing finer was ever sent, which the detail sheet
|
||||
says out loud instead of drawing an empty hour list. */
|
||||
hours: latest.hours || 0,
|
||||
delta: mean != null && mean !== 0 ? (latest.v - mean) / Math.abs(mean) : null,
|
||||
avg: mean,
|
||||
trendDays: prior.length,
|
||||
@@ -392,6 +401,58 @@ export function detailRows(card, day, m) {
|
||||
}))
|
||||
}
|
||||
|
||||
/* ---------- the hours behind a day, and the days behind a card ---------- */
|
||||
|
||||
/**
|
||||
* A metric's hours on one day, as the rows the detail sheet draws.
|
||||
*
|
||||
* `payload` is what `GET /api/vitals/hours` answers — one metric, one day — so this is never the
|
||||
* whole document: the hours are the bulky part of health data and they are fetched when somebody
|
||||
* taps a card, not when the screen loads forty of them.
|
||||
*
|
||||
* The value per hour uses the metric's own rule, exactly as a day does, so an hourly heart rate
|
||||
* reads as an average and an hourly step count reads as a total. A row with no readable value is
|
||||
* dropped rather than shown as a dash: an hour HAE sent without one of the fields a card needs is
|
||||
* not a reading, and a list of dashes is worse than a shorter list.
|
||||
*/
|
||||
export function hourRows(payload, card) {
|
||||
const s = specOf(card.name)
|
||||
return ((payload && payload.hours) || [])
|
||||
.map(h => ({
|
||||
key: h.h,
|
||||
h: h.h,
|
||||
label: h.h + ':00',
|
||||
value: valueOfFields(h.f, s),
|
||||
n: h.n || 0,
|
||||
ts: h.ts || null
|
||||
}))
|
||||
.filter(r => r.value != null && Number.isFinite(r.value))
|
||||
}
|
||||
|
||||
/** The hour rows as chart points: x is that hour on the day the phone wrote. */
|
||||
export function hourChartPoints(day, rows) {
|
||||
return (rows || []).map(r => ({ t: Date.parse(`${day}T${r.h}:00:00`), y: r.value, d: day }))
|
||||
}
|
||||
|
||||
/**
|
||||
* A card's own history, newest day first — what the detail sheet lists under the chart.
|
||||
*
|
||||
* The chart shows a shape; this shows the numbers the shape is made of, which is the difference
|
||||
* between "it went up" and "it went up on Tuesday". `hours` rides along so a row can say whether
|
||||
* that day can be opened hour by hour.
|
||||
*/
|
||||
export function historyRows(card, { limit = 14 } = {}) {
|
||||
const series = (card && card.series) || []
|
||||
return series.slice(-limit).reverse().map(p => ({
|
||||
key: p.day,
|
||||
day: p.day,
|
||||
label: dayLabel(p.day),
|
||||
value: p.v,
|
||||
n: p.n || 0,
|
||||
hours: p.hours || 0
|
||||
}))
|
||||
}
|
||||
|
||||
/* ---------- workouts ---------- */
|
||||
|
||||
// HAE names the activity the way Apple does, in Title Case and sometimes with a long tail.
|
||||
|
||||
@@ -2,7 +2,8 @@ import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
METRICS, specOf, humanize, valueOfDay, metricCards, sortCards, groupedCards, trendOf,
|
||||
chartPoints, workoutRows, hasVitals, activeDays, ingestUrl, unitLabel, fmtValue, agoLabel,
|
||||
detailRows, workoutIcon, GROUP_ORDER, tintOf, dayLabel, trendCards, seriesStats
|
||||
detailRows, workoutIcon, GROUP_ORDER, tintOf, dayLabel, trendCards, seriesStats,
|
||||
hourRows, hourChartPoints, historyRows
|
||||
} from './vitals-view.js'
|
||||
|
||||
/* The mapping from HAE's metric names to what a card shows. Worth testing because it is the one
|
||||
@@ -290,6 +291,82 @@ describe('days, units and captions', () => {
|
||||
expect(agoLabel(0, now)).toBe('')
|
||||
})
|
||||
|
||||
/* The hours. A card's number is a day; these are the rows that make the day readable, and the
|
||||
only thing that decides which of a metric's fields becomes one number an hour. */
|
||||
describe('the hours behind a day', () => {
|
||||
const card = name => metricCards(doc).find(c => c.name === name)
|
||||
const payload = hours => ({ ok: true, metric: 'step_count', day: '2026-05-03', hours })
|
||||
|
||||
it('reads one value per hour using the metric\'s own rule', () => {
|
||||
const steps = card('step_count')
|
||||
const rows = hourRows(payload([
|
||||
{ h: '08', n: 12, ts: 1, f: { qty: { n: 12, sum: 512, min: 1, max: 90, last: 40, avg: 42.6 } } },
|
||||
{ h: '09', n: 12, ts: 2, f: { qty: { n: 12, sum: 1340, min: 2, max: 300, last: 80, avg: 111.6 } } }
|
||||
]), steps)
|
||||
expect(rows.map(r => r.label)).toEqual(['08:00', '09:00'])
|
||||
// Steps are a counter: the hour is its total, not its average — the same rule a day uses.
|
||||
expect(rows.map(r => r.value)).toEqual([512, 1340])
|
||||
expect(rows[0].n).toBe(12)
|
||||
})
|
||||
|
||||
it('averages an hourly rate instead of adding it up', () => {
|
||||
const hr = card('heart_rate')
|
||||
const rows = hourRows({ hours: [{ h: '14', n: 60, ts: 1, f: { Avg: { n: 60, sum: 4200, min: 60, max: 90, last: 75, avg: 70 } } }] }, hr)
|
||||
expect(rows[0].value).toBe(70)
|
||||
})
|
||||
|
||||
it('drops an hour with nothing readable in it rather than showing a dash', () => {
|
||||
const steps = card('step_count')
|
||||
expect(hourRows(payload([{ h: '08', n: 1, ts: 1, f: { distance: bucket(2) } }]), steps)).toEqual([])
|
||||
expect(hourRows(null, steps)).toEqual([])
|
||||
expect(hourRows({ hours: [] }, steps)).toEqual([])
|
||||
})
|
||||
|
||||
it('charts the hours on the day the phone wrote them', () => {
|
||||
const rows = hourRows(payload([
|
||||
{ h: '08', n: 1, ts: 1, f: { qty: bucket(512) } },
|
||||
{ h: '09', n: 1, ts: 2, f: { qty: bucket(1340) } }
|
||||
]), card('step_count'))
|
||||
const pts = hourChartPoints('2026-05-03', rows)
|
||||
expect(pts.map(p => p.y)).toEqual([512, 1340])
|
||||
expect(new Date(pts[0].t).getHours()).toBe(8)
|
||||
expect(new Date(pts[1].t).getHours()).toBe(9)
|
||||
expect(hourChartPoints('2026-05-03', [])).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
it('lists a card\'s own history newest first, and says which days can be opened by the hour', () => {
|
||||
const withHours = {
|
||||
metrics: {
|
||||
step_count: {
|
||||
units: 'count',
|
||||
days: [
|
||||
{ ...day('2026-05-01', { qty: bucket(5000) }), hours: 0 },
|
||||
{ ...day('2026-05-02', { qty: bucket(7000) }), hours: 24 },
|
||||
{ ...day('2026-05-03', { qty: bucket(12000) }), hours: 5 }
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
const c = metricCards(withHours)[0]
|
||||
expect(c.hours).toBe(5, 'the card carries the newest day\'s hours, so the sheet knows to ask')
|
||||
const rows = historyRows(c)
|
||||
expect(rows.map(r => r.day)).toEqual(['2026-05-03', '2026-05-02', '2026-05-01'])
|
||||
expect(rows.map(r => r.value)).toEqual([12000, 7000, 5000])
|
||||
expect(rows.map(r => r.hours)).toEqual([5, 24, 0])
|
||||
expect(rows[0].label).toBeTruthy()
|
||||
// A limit keeps the sheet short on a metric with a year of history: the newest days win.
|
||||
expect(historyRows(c, { limit: 2 }).map(r => r.day)).toEqual(['2026-05-03', '2026-05-02'])
|
||||
expect(historyRows({ series: [] })).toEqual([])
|
||||
})
|
||||
|
||||
it('reports no hours at all when the document does not carry them', () => {
|
||||
// What an older server (or an automation grouping by Day) produces: no `hours` key anywhere.
|
||||
const cards = metricCards(doc)
|
||||
expect(cards.every(c => c.hours === 0)).toBe(true)
|
||||
expect(historyRows(cards[0]).every(r => r.hours === 0)).toBe(true)
|
||||
})
|
||||
|
||||
it('builds an absolute ingest URL that survives a subpath deployment', () => {
|
||||
expect(ingestUrl({ origin: 'https://gym.example.com', pathname: '/' })).toBe('https://gym.example.com/api/vitals/ingest')
|
||||
expect(ingestUrl({ origin: 'https://example.com', pathname: '/gym/' })).toBe('https://example.com/gym/api/vitals/ingest')
|
||||
|
||||
@@ -1367,6 +1367,9 @@ export default {
|
||||
'Read-only on purpose: these carry no sets or weights, so they stay out of your progression, your PRs and the recovery model.': 'Solo lectura a propósito: no traen series ni pesos, así que quedan fuera de tu progresión, tus PRs y el modelo de recuperación.',
|
||||
'vs your average': 'frente a tu media',
|
||||
'What the watch sent': 'Lo que envió el reloj',
|
||||
'Hour by hour': 'Hora por hora',
|
||||
'Day by day': 'Día por día',
|
||||
'This metric arrived as one total a day. Health Auto Export keeps the hours if you set Time grouping to Hours, and then this sheet draws the day hour by hour — the day total is the sum of them, so nothing is counted twice.': 'Esta métrica llegó como un solo total al día. Health Auto Export conserva las horas si pones Agrupación temporal en Horas, y entonces esta hoja dibuja el día hora por hora: el total del día es la suma de ellas, así que nada se cuenta dos veces.',
|
||||
'{0} samples': '{0} muestras',
|
||||
'{0} days with data in this range': '{0} días con datos en este rango',
|
||||
// setup
|
||||
@@ -1389,10 +1392,12 @@ export default {
|
||||
'Summarize data': 'Resumir datos',
|
||||
'Time grouping': 'Agrupación temporal',
|
||||
'Days': 'Días',
|
||||
'Hours': 'Horas',
|
||||
'Date range': 'Rango de fechas',
|
||||
'Previous 7 Days': 'Últimos 7 días',
|
||||
'Health Auto Export runs an automation on your iPhone and posts to this profile. The key below only works for your account, and only for this: it can add health data and cannot read anything back.': 'Health Auto Export ejecuta una automatización en tu iPhone y envía los datos a este perfil. La clave de aquí abajo solo funciona para tu cuenta y solo para esto: puede añadir datos de salud y no puede leer nada.',
|
||||
'Grouping by days is what makes a five-minute cadence safe: each sync carries the day\'s total and replaces the previous one, so nothing is ever counted twice. Raw samples work too — they are de-duplicated instead.': 'Agrupar por días es lo que hace segura una cadencia de cinco minutos: cada envío trae el total del día y reemplaza al anterior, así que nada se cuenta dos veces. Las muestras crudas también funcionan: esas se deduplican.',
|
||||
'Hours is the grouping that keeps the shape of a day: each hour arrives as its own total, the day is their sum, and a card can be read hour by hour. Days sends one number a day instead — exact, and with nothing behind it to look into. Either way a five-minute cadence is safe: a total replaces the total before it, it is never added to it.': 'Horas es la agrupación que conserva la forma del día: cada hora llega como su propio total, el día es la suma de ellas y una tarjeta se puede leer hora por hora. Días envía un solo número al día: exacto, pero sin nada detrás que mirar. En los dos casos una cadencia de cinco minutos es segura: un total reemplaza al total anterior, nunca se le suma.',
|
||||
'Date range decides how much history exists at all. With Today — the default — every sync carries today and yesterday is never in the file. Previous 7 Days carries the last week every time, and those hours land on the ones already stored instead of adding to them.': 'El rango de fechas decide cuánto histórico existe. Con Hoy —el valor por defecto— cada envío trae el día de hoy y ayer nunca está en el archivo. Últimos 7 días trae la última semana cada vez, y esas horas caen sobre las ya guardadas en lugar de sumarse.',
|
||||
'Pick a cadence that suits you — every 5 minutes, hourly, or once a day all land the same way.': 'Elige la cadencia que te sirva: cada 5 minutos, cada hora o una vez al día llegan igual de bien.',
|
||||
'Manage': 'Gestionar',
|
||||
'Replace the key': 'Reemplazar la clave',
|
||||
|
||||
@@ -26,7 +26,8 @@ import LineChart from '../components/LineChart.jsx'
|
||||
import { todayISO } from '../lib/format.js'
|
||||
import {
|
||||
groupedCards, metricCards, trendOf, chartPoints, workoutRows, hasVitals,
|
||||
fmtValue, unitLabel, agoLabel, ingestUrl, detailRows, dayLabel, trendCards, seriesStats
|
||||
fmtValue, unitLabel, agoLabel, ingestUrl, detailRows, dayLabel, trendCards, seriesStats,
|
||||
hourRows, hourChartPoints, historyRows
|
||||
} from '../lib/vitals-view.js'
|
||||
|
||||
/* The period filter, "Today" first and by default: a card's headline is always the newest
|
||||
@@ -118,9 +119,38 @@ function TrendSection({ cards, windowLabel, onOpen }) {
|
||||
* is what makes an unknown metric legible — the numbers under the names HAE used, rather than a
|
||||
* card that says "91" and nothing about what 91 was.
|
||||
*/
|
||||
/**
|
||||
* The detail sheet: the day's chart, the day hour by hour when the phone sent hours, the days
|
||||
* before it, and every field HAE sent for the newest day.
|
||||
*
|
||||
* The hour list is the reason this sheet is worth opening at all: "8,123 steps today" is a number,
|
||||
* and "08:00 → 512, 09:00 → 1,340" is a morning you can recognise. It is a second request, made
|
||||
* only when the day actually has hours (`hours` comes down with the card), so a profile whose
|
||||
* automation groups by Day never pays for it — and the sheet says why the list is missing instead
|
||||
* of leaving a gap where a chart should be.
|
||||
*/
|
||||
function MetricSheet({ card, metric, close }) {
|
||||
const rows = detailRows(card, undefined, metric)
|
||||
const tr = trendOf(card)
|
||||
const [day, setDay] = useState(card.day)
|
||||
const [hours, setHours] = useState(null)
|
||||
// Tapping a day in the history moves the hour list to that day, so the whole week the server
|
||||
// still keeps hours for can be read without leaving the sheet.
|
||||
const dayHours = (card.series || []).find(p => p.day === day)?.hours || 0
|
||||
|
||||
useEffect(() => {
|
||||
if (dayHours < 2) { setHours(null); return }
|
||||
let live = true
|
||||
api('/api/vitals/hours?metric=' + encodeURIComponent(card.name) + '&day=' + encodeURIComponent(day))
|
||||
.then(r => { if (live) setHours(r) })
|
||||
.catch(() => { if (live) setHours(null) })
|
||||
return () => { live = false }
|
||||
}, [card.name, day, dayHours])
|
||||
|
||||
const hourList = hourRows(hours, card)
|
||||
const history = historyRows(card)
|
||||
const val = r => fmtValue(r.value, card.dec) + (unitLabel(card.unit) ? ' ' + unitLabel(card.unit) : '')
|
||||
|
||||
return <>
|
||||
<h3>{card.label}</h3>
|
||||
<div className="vh-sheet-top" style={{ '--tint': card.tint }}>
|
||||
@@ -134,6 +164,33 @@ function MetricSheet({ card, metric, close }) {
|
||||
</div>
|
||||
</div>
|
||||
<div className="card vh-chart"><LineChart points={chartPoints(card)} h={160} unit={unitLabel(card.unit)} color={card.tint} /></div>
|
||||
|
||||
{hourList.length > 1 && <>
|
||||
<h4 className="sec">{t('Hour by hour')}<span className="vh-window"> · {dayLabel(day)}</span></h4>
|
||||
<div className="card vh-chart">
|
||||
<LineChart points={hourChartPoints(day, hourList)} h={120} unit={unitLabel(card.unit)} color={card.tint} />
|
||||
</div>
|
||||
<div className="list">
|
||||
{hourList.map(r => <Row key={r.key} title={r.label}
|
||||
subtitle={r.n > 1 ? t('{0} samples', r.n) : null} value={val(r)} />)}
|
||||
</div>
|
||||
</>}
|
||||
|
||||
{!(card.hours > 1) && <div className="small dim" style={{ marginTop: 10, lineHeight: 1.5 }}>
|
||||
{t('This metric arrived as one total a day. Health Auto Export keeps the hours if you set Time grouping to Hours, and then this sheet draws the day hour by hour — the day total is the sum of them, so nothing is counted twice.')}
|
||||
</div>}
|
||||
|
||||
{history.length > 1 && <>
|
||||
<h4 className="sec">{t('Day by day')}</h4>
|
||||
<div className="list">
|
||||
{history.map(r => <Row key={r.key} title={r.label}
|
||||
subtitle={r.n > 1 ? t('{0} samples', r.n) : null}
|
||||
value={val(r)}
|
||||
accessory={r.hours > 1 ? 'chevron' : null}
|
||||
onClick={r.hours > 1 ? () => setDay(r.day) : null} />)}
|
||||
</div>
|
||||
</>}
|
||||
|
||||
{rows.length > 0 && <>
|
||||
<h4 className="sec">{t('What the watch sent')}</h4>
|
||||
<div className="list">{rows.map(r => <Row key={r.key} title={r.label}
|
||||
@@ -192,11 +249,14 @@ function SetupSheet({ initialKey, onKey, onRotate, onDelete, close }) {
|
||||
<Row icon="calendar" title={t('Export format')} value="JSON" />
|
||||
<Row icon="list" title={t('Export version')} value="2" />
|
||||
<Row icon="check" title={t('Summarize data')} value={t('On')} />
|
||||
<Row icon="clock" title={t('Time grouping')} value={t('Days')} />
|
||||
<Row icon="clock" title={t('Time grouping')} value={t('Hours')} />
|
||||
<Row icon="history" title={t('Date range')} value={t('Previous 7 Days')} />
|
||||
</div>
|
||||
<div className="small dim" style={{ marginTop: 10, lineHeight: 1.5 }}>
|
||||
{t('Grouping by days is what makes a five-minute cadence safe: each sync carries the day\'s total and replaces the previous one, so nothing is ever counted twice. Raw samples work too — they are de-duplicated instead.')}
|
||||
{t('Hours is the grouping that keeps the shape of a day: each hour arrives as its own total, the day is their sum, and a card can be read hour by hour. Days sends one number a day instead — exact, and with nothing behind it to look into. Either way a five-minute cadence is safe: a total replaces the total before it, it is never added to it.')}
|
||||
</div>
|
||||
<div className="small dim" style={{ marginTop: 8, lineHeight: 1.5 }}>
|
||||
{t('Date range decides how much history exists at all. With Today — the default — every sync carries today and yesterday is never in the file. Previous 7 Days carries the last week every time, and those hours land on the ones already stored instead of adding to them.')}
|
||||
</div>
|
||||
<div className="small dim" style={{ marginTop: 8, lineHeight: 1.5 }}>
|
||||
{t('Pick a cadence that suits you — every 5 minutes, hourly, or once a day all land the same way.')}
|
||||
|
||||
@@ -9,6 +9,7 @@ import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
|
||||
const api = vi.fn()
|
||||
vi.mock('../lib/api.js', () => ({ api: (...args) => api(...args) }))
|
||||
@@ -50,7 +51,10 @@ beforeEach(() => {
|
||||
localStorage.removeItem('gym_guest')
|
||||
useStore.setState({ user: { id: 'u1', name: 'Test' } })
|
||||
})
|
||||
afterEach(() => { act(() => root.unmount()); host.remove() })
|
||||
/* A sheet lives in the UI store, not in the screen, so it outlives the screen's root: without
|
||||
clearing it the next test remounts yesterday's sheet, which is both a stray element in the DOM
|
||||
and a request nobody asked for. Tests are independent or they are not tests. */
|
||||
afterEach(() => { act(() => { useUI.setState({ sheets: [] }); root.unmount() }); host.remove() })
|
||||
|
||||
const mount = async () => {
|
||||
await act(async () => { root.render(<Health />) })
|
||||
@@ -171,6 +175,114 @@ describe('the Today filter', () => {
|
||||
})
|
||||
})
|
||||
|
||||
/* The detail sheet is where a number becomes a day. Tapping a card has to show the hours the
|
||||
phone actually sent, and it has to say so plainly when it sent none — a card whose automation
|
||||
groups by Day has no hours anywhere, and an empty chart there would read as a bug. The hours
|
||||
are a second request on purpose (a profile with forty cards should not download 24 buckets ×
|
||||
forty metrics to draw a grid), so this checks both the fetch and the drawing. */
|
||||
describe('the detail sheet', () => {
|
||||
const mountWithSheets = async () => {
|
||||
await act(async () => { root.render(<><Health /><Modals /></>) })
|
||||
await act(async () => {})
|
||||
}
|
||||
const click = el => act(() => { el.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
|
||||
// The sheet that is open right now: a previous test's sheet is still in the DOM (the Modals host
|
||||
// outlives the screen's root), so reading document.body would read somebody else's day.
|
||||
const sheetEl = () => [...document.querySelectorAll('.sheet')].pop()
|
||||
const sheet = () => sheetEl()?.textContent || ''
|
||||
const openSteps = () => click(entries().find(e => (e.querySelector('.l, .vh-tchart-t') || {}).textContent === 'Steps'))
|
||||
|
||||
const withHours = () => ({
|
||||
...VITALS,
|
||||
metrics: {
|
||||
step_count: {
|
||||
units: 'count', sources: ['Apple Watch'],
|
||||
days: [
|
||||
{ ...day('2026-09-02', { qty: bucket(11000) }), hours: 24 },
|
||||
{ ...day('2026-09-03', { qty: bucket(12481) }), hours: 3 }
|
||||
]
|
||||
}
|
||||
}
|
||||
})
|
||||
const HOURS = {
|
||||
ok: true, metric: 'step_count', day: '2026-09-03', units: 'count',
|
||||
hours: [
|
||||
{ h: '08', n: 1, ts: 1, f: { qty: bucket(512) } },
|
||||
{ h: '09', n: 1, ts: 2, f: { qty: bucket(1340) } },
|
||||
{ h: '10', n: 1, ts: 3, f: { qty: bucket(900) } }
|
||||
]
|
||||
}
|
||||
const route = (doc, hours) => api.mockImplementation(async path => {
|
||||
if (path.startsWith('/api/vitals/hours')) return hours
|
||||
if (path.startsWith('/api/vitals?')) return doc
|
||||
throw new Error('unexpected ' + path)
|
||||
})
|
||||
|
||||
it('draws the day hour by hour, and the days before it, when the phone sent hours', async () => {
|
||||
route(withHours(), HOURS)
|
||||
await mountWithSheets()
|
||||
openSteps()
|
||||
await act(async () => {})
|
||||
|
||||
// One metric, one day: never the whole document.
|
||||
expect(api).toHaveBeenCalledWith('/api/vitals/hours?metric=step_count&day=2026-09-03')
|
||||
expect(sheet()).toContain('Hour by hour')
|
||||
expect(sheet()).toContain('08:00')
|
||||
expect(sheet()).toContain('512')
|
||||
expect(sheet()).toContain('1,340')
|
||||
// The history the card is built from, so "it went up" can be read as "it went up on Tuesday".
|
||||
expect(sheet()).toContain('Day by day')
|
||||
expect(sheet()).toContain('11,000')
|
||||
expect(sheet()).toContain('12,481')
|
||||
expect(sheet()).not.toContain('This metric arrived as one total a day')
|
||||
})
|
||||
|
||||
it('says the automation groups by day instead of drawing an empty hour list', async () => {
|
||||
route(VITALS, HOURS)
|
||||
await mountWithSheets()
|
||||
openSteps()
|
||||
await act(async () => {})
|
||||
|
||||
expect(sheet()).toContain('This metric arrived as one total a day')
|
||||
expect(sheet()).not.toContain('Hour by hour')
|
||||
// ...and it never asks for hours it knows do not exist: the card said so.
|
||||
expect(api.mock.calls.map(c => c[0]).filter(p => p.startsWith('/api/vitals/hours'))).toEqual([])
|
||||
// The history is drawn anyway: three days of step totals are three rows.
|
||||
expect(sheet()).toContain('Day by day')
|
||||
expect(sheet()).toContain('9,000')
|
||||
})
|
||||
|
||||
it('moves the hour list to a day that has hours when that day is tapped', async () => {
|
||||
const byDay = {
|
||||
'2026-09-03': HOURS,
|
||||
'2026-09-02': { ...HOURS, day: '2026-09-02', hours: [
|
||||
{ h: '06', n: 1, ts: 1, f: { qty: bucket(500) } },
|
||||
{ h: '07', n: 1, ts: 2, f: { qty: bucket(777) } }
|
||||
] }
|
||||
}
|
||||
api.mockImplementation(async path => {
|
||||
if (path.startsWith('/api/vitals/hours')) return byDay[path.split('day=')[1]]
|
||||
if (path.startsWith('/api/vitals?')) return withHours()
|
||||
throw new Error('unexpected ' + path)
|
||||
})
|
||||
await mountWithSheets()
|
||||
openSteps()
|
||||
await act(async () => {})
|
||||
expect(sheet()).toContain('08:00')
|
||||
|
||||
// The row for the day before carries the chevron that says it can be opened.
|
||||
const row = [...sheetEl().querySelectorAll('button')].find(b => b.textContent.includes('11,000'))
|
||||
expect(row).toBeTruthy()
|
||||
click(row)
|
||||
await act(async () => {})
|
||||
|
||||
expect(api).toHaveBeenCalledWith('/api/vitals/hours?metric=step_count&day=2026-09-02')
|
||||
expect(sheet()).toContain('07:00')
|
||||
expect(sheet()).toContain('777')
|
||||
expect(sheet()).not.toContain('08:00')
|
||||
})
|
||||
})
|
||||
|
||||
/* The setup sheet is rendered from an element captured when it was opened (useUI.openSheet keeps
|
||||
the JSX), so anything it reads off the screen's state is frozen at that moment. The first
|
||||
version keyed the whole "2. The header" block off the screen's `key`, which meant clicking
|
||||
|
||||
+6
-1
@@ -232,7 +232,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
|
||||
<p class="api-facts">
|
||||
<span>OpenAPI 3.1.0</span>
|
||||
<span>KuentaGYM v1.3.8</span>
|
||||
<span>35 endpoints</span>
|
||||
<span>36 endpoints</span>
|
||||
<span>AGPL-3.0-or-later</span>
|
||||
</p>
|
||||
|
||||
@@ -2263,6 +2263,11 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
|
||||
<span class="p-type">integer</span>
|
||||
<span class="p-desc">Epoch ms of the day's newest sample.</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">hours</span>
|
||||
<span class="p-type">integer</span>
|
||||
<span class="p-desc">How many hourly buckets this day has (0 or 1 when the automation grouped by Day, or when the samples arrived without an hour of their own). The buckets themselves are not in this response — <code>GET /api/vitals/hours</code> answers one metric and one day, because 24 buckets × every metric × every day is not something a grid of cards should download.</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">f</span>
|
||||
<span class="p-type">object</span>
|
||||
|
||||
Reference in new issue
Block a user