Files
kuentagym/api/vitals.js
T
dsantillan aa6ec8ef22
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
Salud: a card opens onto the day, hour by hour, and onto the days before it
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.
2026-09-23 13:28:58 -04:00

559 lines
27 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* vitals.js — Apple Health ingestion (Health Auto Export → KuentaGYM).
*
* The phone runs a "REST API" automation in Health Auto Export (HAE) that POSTs its JSON export
* to /api/vitals/ingest. This module is the whole of what happens to that payload: parse, fold
* into per-day buckets, merge with what is already stored, prune. Nothing here touches the
* filesystem or the network — server.js owns the file, this owns the arithmetic, which is what
* makes it testable without a phone (see test/vitals.test.js).
*
* ── Why this is not just "append the samples" ───────────────────────────────────────────────
*
* A five-minute automation re-sends overlapping windows: with Date Range = "Today" or the
* default ("previous day + today so far") every sync carries the whole day again, so appending
* would double every step count. With Date Range = "Since Last Sync" the windows are disjoint
* and *replacing* would throw away everything but the last five minutes. The same receiver has to
* survive both without knowing which one the phone is configured for, so the rule is chosen per
* payload from the payload's own shape:
*
* dayAggregated() every datapoint sits exactly on midnight
* → HAE already grouped by day ("Time Grouping: Days"), and a grouped day is a *total*:
* a day total only ever replaces another one. Wait, "replaces" is wrong for the current
* day, which legitimately grows all day long — and that is precisely why replacement is
* 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.
*
* 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
* depend on the window at all.
*
* The one configuration neither rule can fully rescue is grouping by *minutes* 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 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 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 ────────────────────────────────────────────────────────
*
* Buckets are **per day, keyed by the day the phone wrote**, never by the server's own timezone:
* HAE stamps each sample with the phone's local offset, so grouping by a server-local date would
* slide every evening's steps into the next day for anyone not on UTC. The day key is therefore
* taken straight from the payload's own date text.
*
* {
* v: 1, updatedAt: 1699999999999,
* last: { ts, metrics, points, duplicates, workouts, source },
* metrics: {
* step_count: {
* units: 'count', sources: ['iPhone'],
* days: { '2026-05-01': { n: 288, lastTs: 1699999999999,
* 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 }
* }
* },
* workouts: [ { name, start, end, durMin, fields: { activeEnergy: { qty, units } } } ]
* }
*
* Numeric fields are kept generically (`f`) rather than decoded per metric, because a health
* catalogue is wide and keeps growing: heart_rate carries Min/Avg/Max, blood_pressure carries
* systolic/diastolic, sleep carries asleep/inBed/core/deep/rem — and a metric this code has never
* heard of still lands in `f` under whatever HAE called it. Which field a *card* shows is a
* presentation decision, and it lives in frontend/src/lib/vitals-view.js with the labels. That
* split is deliberate: it means a metric added to HAE next year shows up without a server change.
*/
export const VITALS_VERSION = 1;
/** Ledger lives 72 h: the longest overlap a sane automation cadence can span. */
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
export function emptyVitals() {
return { v: VITALS_VERSION, updatedAt: 0, last: null, metrics: {}, workouts: [] };
}
/** A stored document that is missing pieces (hand-edited, or written by an older version). */
export function normalizeDoc(doc) {
const d = doc && typeof doc === 'object' && !Array.isArray(doc) ? doc : {};
const out = {
v: VITALS_VERSION,
updatedAt: Number(d.updatedAt) || 0,
last: d.last && typeof d.last === 'object' ? d.last : null,
metrics: {},
workouts: Array.isArray(d.workouts) ? d.workouts.filter(w => w && typeof w === 'object') : []
};
const metrics = d.metrics && typeof d.metrics === 'object' && !Array.isArray(d.metrics) ? d.metrics : {};
for (const [name, m] of Object.entries(metrics)) {
if (!m || typeof m !== 'object') continue;
const days = m.days && typeof m.days === 'object' && !Array.isArray(m.days) ? m.days : {};
out.metrics[name] = {
units: typeof m.units === 'string' ? m.units : '',
sources: Array.isArray(m.sources) ? m.sources.filter(s => typeof s === 'string').slice(0, MAX_SOURCES) : [],
days,
seen: m.seen && typeof m.seen === 'object' && !Array.isArray(m.seen) ? m.seen : {}
};
}
return out;
}
/* ---------- parsing ---------- */
// HAE writes "2021-12-24 00:04:00 +0800", or "2021-12-24 3:04:05 PM -0700" when the phone is on
// a 12-hour clock — and that separator is U+202F (narrow no-break space), not a plain space, which
// is exactly the kind of thing that turns into NaN three weeks later. Both are normalised below.
const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{1,2}):(\d{2}):(\d{2})(?:[\s\u202f\u00a0]*([AaPp])\.?[Mm]\.?)?(?:[\s\u202f\u00a0]*([+-]\d{2}):?(\d{2})|Z)?$/;
/**
* Parse one HAE timestamp.
* @returns {{ms:number, day:string, time:string, raw:string}|null} `day` is the date the phone
* wrote (its own local day), `time` is "HH:MM:SS" in 24-hour form, `ms` an epoch instant.
*/
export function parseHaeDate(value) {
if (typeof value !== 'string') return null;
const raw = value.trim();
const m = DATE_RE.exec(raw);
if (!m) return null;
const [, y, mo, d, h, mi, s, ap, offH, offM] = m;
let hour = Number(h);
if (ap) {
// 12 AM is 00, 12 PM is 12 — the two hours the naive modulo gets wrong.
const pm = ap.toLowerCase() === 'p';
if (hour === 12) hour = pm ? 12 : 0;
else if (pm) hour += 12;
}
if (hour > 23 || Number(mi) > 59 || Number(s) > 59) return null;
const time = `${String(hour).padStart(2, '0')}:${mi}:${s}`;
const day = `${y}-${mo}-${d}`;
const offset = offH ? `${offH}:${offM || '00'}` : 'Z'; // no offset in the payload means UTC
const ms = Date.parse(`${day}T${time}${offset}`);
if (!Number.isFinite(ms)) return null;
return { ms, day, time, raw };
}
/** 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.
const NON_VALUE_KEYS = new Set(['date', 'startDate', 'endDate', 'sleepStart', 'sleepEnd', 'inBedStart', 'inBedEnd', 'source', 'Source', 'value']);
const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null);
/** The numeric measurements on one datapoint, keyed exactly as HAE named them. */
export function fieldsOf(point) {
const out = {};
for (const [k, v] of Object.entries(point)) {
if (NON_VALUE_KEYS.has(k)) continue;
const n = num(v);
if (n != null) out[k] = n;
}
return out;
}
/** The instant of a datapoint: metrics carry `date`, sleep carries `sleepStart`/`startDate`. */
function instantOf(point) {
for (const k of ['date', 'sleepStart', 'startDate', 'inBedStart']) {
const t = parseHaeDate(point[k]);
if (t) return t;
}
return null;
}
const str = v => (typeof v === 'string' ? v : '');
/**
* Validate and normalise an HAE export body into what mergeVitals() expects.
*
* Version 2 wraps everything in `data`; the older flat shape puts the arrays at the top level and
* is accepted too, since it costs one line and a user pasting an old export should not get a
* blank page. A metric with `data: null` is normal (HAE sends the metric because it is selected
* but has no samples) and is dropped here rather than stored as an empty day.
*
* @throws {Error} with `.code` of 'shape' (not an export at all) or 'empty' (an export with
* nothing in it) — server.js turns both into a 400 that names the problem.
*/
export function parsePayload(body) {
if (!body || typeof body !== 'object' || Array.isArray(body)) throw err('shape');
const data = body.data && typeof body.data === 'object' && !Array.isArray(body.data) ? body.data : body;
const rawMetrics = Array.isArray(data.metrics) ? data.metrics : [];
const rawWorkouts = Array.isArray(data.workouts) ? data.workouts : [];
if (!rawMetrics.length && !rawWorkouts.length && !('metrics' in data) && !('workouts' in data)) throw err('shape');
const metrics = [];
for (const m of rawMetrics) {
if (!m || typeof m !== 'object') continue;
const name = str(m.name).trim();
if (!name) continue;
const points = [];
for (const p of Array.isArray(m.data) ? m.data : []) {
if (!p || typeof p !== 'object') continue;
const at = instantOf(p);
if (!at) continue; // a datapoint with no readable date is unusable
const fields = fieldsOf(p);
if (!Object.keys(fields).length) continue; // ...and so is one with no numbers
points.push({ at, fields, source: str(p.source) || str(p.Source) });
}
metrics.push({ name, units: str(m.units), points });
}
const workouts = [];
for (const w of rawWorkouts) {
if (!w || typeof w !== 'object') continue;
const name = str(w.name).trim();
const start = parseHaeDate(w.start);
if (!name || !start) continue;
const end = parseHaeDate(w.end);
const fields = {};
for (const [k, v] of Object.entries(w)) {
if (['name', 'start', 'end', 'route', 'heartRateData', 'heartRateRecovery'].includes(k)) continue;
const q = v && typeof v === 'object' && !Array.isArray(v) ? num(v.qty) : num(v);
if (q == null) continue;
fields[k] = { qty: q, units: v && typeof v === 'object' ? str(v.units) : '' };
}
const mins = end ? Math.round((end.ms - start.ms) / 60000) : null;
workouts.push({
name,
start: start.ms,
end: end ? end.ms : null,
day: start.day,
durMin: mins != null && mins >= 0 ? mins : null,
avgHr: hrAvg(w.heartRateData) ?? fields.heartRate?.qty ?? null,
maxHr: hrMax(w.heartRateData) ?? null,
fields
});
}
if (!metrics.length && !workouts.length) throw err('empty');
return { metrics, workouts };
}
const err = code => Object.assign(new Error(code), { code });
/** Average of HAE's per-second/minute workout heart-rate samples. */
function hrAvg(samples) {
if (!Array.isArray(samples) || !samples.length) return null;
const vals = samples.map(s => num(s?.Avg) ?? num(s?.qty)).filter(v => v != null);
if (!vals.length) return null;
return Math.round((vals.reduce((a, b) => a + b, 0) / vals.length) * 10) / 10;
}
function hrMax(samples) {
if (!Array.isArray(samples) || !samples.length) return null;
const vals = samples.map(s => num(s?.Max) ?? num(s?.qty)).filter(v => v != null);
return vals.length ? Math.max(...vals) : null;
}
/* ---------- merging ---------- */
/** Does this metric payload look like HAE's own day-by-day grouping? */
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) {
for (const [k, v] of Object.entries(fields)) {
const f = bucket.f[k] || (bucket.f[k] = { n: 0, sum: 0, min: v, max: v, last: v });
f.n++; f.sum += v;
if (v < f.min) f.min = v;
if (v > f.max) f.max = v;
f.last = v;
}
bucket.n++;
}
const bucketFrom = (fields, ts) => {
const b = { n: 0, lastTs: ts, f: {} };
addFields(b, fields);
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.
*
* @returns {{doc:object, stats:{metrics:number, points:number, duplicates:number, workouts:number}}}
*/
export function mergeVitals(doc, payload, now = Date.now()) {
const out = normalizeDoc(doc);
const stats = { metrics: 0, points: 0, duplicates: 0, workouts: 0 };
for (const m of payload.metrics) {
if (!m.points.length) continue;
stats.metrics++;
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);
for (const p of m.points) {
const key = p.at.day;
if (!dayKeyOk(key)) continue;
if (p.source && !cur.sources.includes(p.source)) {
cur.sources = [p.source, ...cur.sources].slice(0, MAX_SOURCES);
}
if (replace) {
const prev = cur.days[key];
// Nothing to do when the phone re-sends the value we already have (the common case for
// 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; }
// 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 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);
out.metrics[m.name] = cur;
}
if (payload.workouts.length) {
const seen = new Set(out.workouts.map(w => wkey(w)));
for (const w of payload.workouts) {
const k = wkey(w);
if (seen.has(k)) { stats.duplicates++; continue; }
seen.add(k);
out.workouts.push(w);
stats.workouts++;
}
// Newest first, and the oldest are dropped: a wrist that records every walk produces
// thousands of entries a year, and nobody scrolls past the last few hundred.
out.workouts.sort((a, b) => b.start - a.start);
if (out.workouts.length > MAX_WORKOUTS) out.workouts.length = MAX_WORKOUTS;
}
pruneDays(out, now);
out.updatedAt = now;
out.last = { ts: now, ...stats };
return { doc: out, stats };
}
const wkey = w => `${w.name}|${w.start}|${w.end ?? ''}`;
/** Same numbers as the stored bucket? `raw` is a payload's plain field map, `stored` a bucket's. */
function sameFields(stored, raw) {
const ka = Object.keys(stored), kb = Object.keys(raw);
if (ka.length !== kb.length) return false;
return ka.every(k => raw[k] === stored[k].last);
}
/** A sample's identity: when it happened plus what it says. */
function sampleId(p) {
const f = Object.keys(p.fields).sort().map(k => `${k}:${p.fields[k]}`).join(',');
return `${p.at.raw}|${f}`;
}
function pruneLedger(seen, now, enforceCap = false) {
for (const [k, ts] of Object.entries(seen)) if (now - ts > LEDGER_MS) delete seen[k];
if (!enforceCap) return;
const keys = Object.keys(seen);
if (keys.length <= MAX_LEDGER_KEYS) return;
// Oldest first — a repeat can only be recent, so the tail is what may be given up.
keys.sort((a, b) => seen[a] - seen[b]);
for (const k of keys.slice(0, keys.length - MAX_LEDGER_KEYS)) delete seen[k];
}
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, 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);
// `days` counts calendar days *including today*, so `days: 1` is today alone. Day keys are the
// phone's own local dates (see the header), which is why this is a plain string comparison
// rather than an instant one: an evening sample in Manila and one in Lima each keep their own
// day, and neither is dragged across a boundary by the server's timezone.
const from = new Date(now - Math.max(0, days - 1) * 86400000).toISOString().slice(0, 10);
const metrics = {};
for (const [name, m] of Object.entries(d.metrics)) {
const out = [];
for (const day of Object.keys(m.days).sort()) {
if (day < from) continue;
const b = m.days[day];
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 };
}