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
"Las actualizaciones están llegando pero las tarjetas no tienen los mismos números que Salud." Las actualizaciones llegan, entonces: el problema es qué se hace con ellas, y hay dos formas de que un día salga más grande de lo que el reloj dice. **El total del día leído como hora 00.** Si HAE manda el total del día con marca de medianoche en el mismo payload que las horas, ese punto caía en el cubo de las 00:00 y la suma del día lo contaba además de las horas — 499 declarados + 341 de horas = 840, que es exactamente el número reportado. Ahora un punto de medianoche que vale más que todo el resto del payload junto es el total del día (una hora no puede tener más que el día que la contiene) y nunca se convierte en hora 00; un 00:00 chico de verdad sigue siendo la primera hora y se suma como cualquier otra. **Horas sumadas a un total que ya las contenía.** Con el día declarado por el teléfono, cada hora que llegaba después se le sumaba encima — el mismo error, una capa más arriba. Ahora el total declarado **es** el día y las horas nunca se le agregan: son la forma del día, no un segundo número. Su suma queda al lado, en `hours_sum`, y la hoja de la métrica dice cuando los dos difieren, en palabras: tanto el teléfono declaró, tanto suman las horas, y cuál de los dos estás viendo. Un total que no se renueva en seis horas deja de mandar, así que cambiar una automatización de Días a Horas converge en vez de congelarse para el resto del día. Y para la otra forma — horas que en realidad son **totales acumulados** en vez de deltas, que también suman de más — cada envío deja un **recibo por métrica**, visible en la hoja: cuántos datos llegaron, cómo vienen marcados (un total por día, uno por hora, muestras sueltas o mezcla), de qué fuentes, cuánto suman y los tres últimos valores. Una corrida de números que suben (340 → 420 → 499) es la señal de que son acumulados, y eso es la diferencia entre 499 y 840 vista en la pantalla en vez de deducida. Es un recibo, no una lectura: el campo que cita se elige por una lista fija porque este módulo no tiene el catálogo, y nada de él entra en el cálculo de un día. Seis tests nuevos del merge y del recibo, dos de las filas de la hoja y uno de render por la hoja real. Mutation-check de las dos mitades del arreglo: leer el total como hora 00 falla, y sumarle las horas al total declarado falla. API 261 en verde, frontend 1701, build OK.
702 lines
34 KiB
JavaScript
702 lines
34 KiB
JavaScript
/* 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;
|
||
/**
|
||
* How long a day the phone totalled itself stays the day's number while hours keep arriving. In the
|
||
* shape this exists for the total is re-sent on every sync, so it never goes stale; an automation
|
||
* that was reconfigured to hours only stops sending it, and after this the sum of the hours takes
|
||
* over instead of the number freezing for the rest of the day.
|
||
*/
|
||
export const DECLARED_STALE_MS = 6 * 3600 * 1000;
|
||
/** 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') : [],
|
||
// The last sync's receipt per metric (see receiptFor): replaced every time, never read by
|
||
// anything that computes a number.
|
||
shape: d.shape && typeof d.shape === 'object' && !Array.isArray(d.shape) ? d.shape : {}
|
||
};
|
||
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 ---------- */
|
||
|
||
/**
|
||
* A midnight-stamped datapoint that carries more than everything else in its payload put together
|
||
* is the day's own total, not hour 00: an hour cannot hold more than the day it belongs to. Returns
|
||
* the day keys it applies to, so the loop can treat exactly those points as day totals.
|
||
*/
|
||
function declaredDay(points) {
|
||
const rest = points.filter(p => !isMidnight(p.at))
|
||
.map(p => headline(p.fields))
|
||
.filter(Boolean)
|
||
.reduce((n, h) => n + h.value, 0);
|
||
const keys = new Set();
|
||
for (const p of points) {
|
||
if (!isMidnight(p.at)) continue;
|
||
const h = headline(p.fields);
|
||
if (h && h.value > rest) keys.add(p.at.day);
|
||
}
|
||
return keys;
|
||
}
|
||
|
||
/** 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;
|
||
day.hsum = sumHours(day);
|
||
}
|
||
|
||
/**
|
||
* What a day's hours add up to, per field — kept beside the day whether or not the day's own number
|
||
* came from them. When the phone also declares a total the two can disagree, and that disagreement
|
||
* is the most useful thing there is to show: "the hours add up to 840 and the newest one says 499"
|
||
* explains a wrong number, where the wrong number alone explains nothing.
|
||
*/
|
||
function sumHours(day) {
|
||
const out = {};
|
||
for (const hb of Object.values(day.h || {})) {
|
||
for (const [k, v] of Object.entries(hb.f || {})) out[k] = Math.round(((out[k] || 0) + (v.sum || 0)) * 100) / 100;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/**
|
||
* 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);
|
||
|
||
// The receipt is written once per metric, from the payload as it arrived.
|
||
out.shape[m.name] = receiptFor(m.points, now);
|
||
|
||
/* A midnight-stamped datapoint inside a payload that also carries hours is the day's own total,
|
||
not hour 00 of it — an hour cannot hold more than the day does. Reading it as an hour is what
|
||
turns "499 today" into 840, so when its value exceeds everything else in the payload added
|
||
together, it is taken as the day. Anything smaller is left where it is: a genuine 00:00 bucket
|
||
is a handful of steps, never more than the rest of the day. */
|
||
// A Set, and empty is not "yes": `declared.has(day)` is what the loop asks, because a truthy
|
||
// empty Set would turn every midnight point into a day total.
|
||
const declared = replace ? null : declaredDay(m.points);
|
||
|
||
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 || (declared && declared.has(p.at.day) && isMidnight(p.at))) {
|
||
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, ownAt: now };
|
||
cur.days[key].hsum = sumHours(cur.days[key]);
|
||
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.
|
||
Three days are the exceptions, and all three are days whose aggregate is not "the hours so
|
||
far":
|
||
own — the phone totalled this day itself. Its total is the number the Health app shows,
|
||
and hours were re-folded into it once already (that is the bug this replaced:
|
||
499 declared plus 341 of hours became 840). So the total stays the day, and the
|
||
hours stay the shape of it. The escape hatch is time: if no fresh total has
|
||
arrived for six hours while hours keep coming, the automation was clearly
|
||
reconfigured to hours only, and the day goes back to the sum of them.
|
||
!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. */
|
||
const declaredStale = day.own && now - (day.ownAt || 0) > DECLARED_STALE_MS;
|
||
if (declaredStale) { delete day.own; delete day.ownAt; day.hc = true; }
|
||
if (day.own) {
|
||
/* The phone declared this day, so its number *is* the day: adding the hour to it would
|
||
count the morning twice, which is the whole failure this branch exists to prevent. The
|
||
hours still move — they are the shape of the day and the detail sheet draws them — and
|
||
the sum beside them moves with them so the two can be compared. */
|
||
day.hsum = sumHours(day);
|
||
} else if (day.hc || day.n === 0) {
|
||
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;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/* ---------- the receipt: what actually arrived ----------
|
||
*
|
||
* One entry per metric, replaced on every sync: how many datapoints came, how they were stamped
|
||
* (a day total, an hour, or a real instant), from which sources, what they add up to, and the first
|
||
* and last few values as the phone wrote them. It exists because "the number in the app does not
|
||
* match the Health app" is unanswerable from the number alone, and the answer is always in the
|
||
* shape of what arrived: hourly values that are really running totals add up to more than the day,
|
||
* and two devices recording the same walk add up to more than either.
|
||
*
|
||
* Bounded on purpose (three values at each end), and it is a *receipt*, not a reading: the headline
|
||
* field is picked by a fixed order rather than by the metric's meaning, because this module does not
|
||
* have the catalogue. Nothing here is used to compute a day. */
|
||
|
||
/** The field a receipt quotes for a point: the one a person would read if they had to pick one. */
|
||
const HEADLINE_FIELDS = ['qty', 'Avg', 'avg', 'value', 'asleep', 'totalSleep', 'systolic'];
|
||
function headline(fields) {
|
||
for (const k of HEADLINE_FIELDS) if (typeof fields[k] === 'number') return { field: k, value: fields[k] };
|
||
for (const [k, v] of Object.entries(fields)) if (typeof v === 'number') return { field: k, value: v };
|
||
return null;
|
||
}
|
||
|
||
const stampKind = t => (isMidnight(t) ? 'day' : onTheHour(t) ? 'hour' : 'sample');
|
||
|
||
function receiptFor(points, now) {
|
||
const kinds = new Set(points.map(p => stampKind(p.at)));
|
||
const valued = points.map(p => ({ at: p.at, h: headline(p.fields) })).filter(x => x.h);
|
||
const sum = valued.reduce((n, x) => n + x.h.value, 0);
|
||
const last = valued.length ? valued[valued.length - 1] : null;
|
||
const pair = x => [x.at.raw, x.h.value];
|
||
return {
|
||
at: now,
|
||
points: points.length,
|
||
field: valued.length ? valued[0].h.field : null,
|
||
stamps: kinds.size > 1 ? 'mixed' : [...kinds][0],
|
||
sources: [...new Set(points.map(p => p.source).filter(Boolean))].slice(0, MAX_SOURCES),
|
||
sum: Math.round(sum * 100) / 100,
|
||
newest: last ? { stamp: last.at.raw, value: last.h.value, ms: last.at.ms } : null,
|
||
head: valued.slice(0, 3).map(pair),
|
||
tail: valued.slice(-3).map(pair)
|
||
};
|
||
}
|
||
|
||
/* ---------- 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,
|
||
// `own`: this day's number is the total the phone declared, not the sum of its hours.
|
||
// `hours_sum`: what its hours add up to, so a disagreement between the two is visible
|
||
// instead of hidden — the screen shows it, and so does anybody debugging a wrong number.
|
||
own: !!b.own,
|
||
hours_sum: b.hsum || null,
|
||
f: projectFields(b.f)
|
||
});
|
||
}
|
||
if (out.length) metrics[name] = { units: m.units, sources: m.sources, days: out, shape: d.shape[name] || null };
|
||
}
|
||
return { updatedAt: d.updatedAt, last: d.last, metrics, workouts: d.workouts };
|
||
}
|
||
|
||
/**
|
||
* Forget one metric, keeping everything else.
|
||
*
|
||
* The whole-file delete exists and is two taps, but it is the wrong size for the question people
|
||
* actually arrive with: "these numbers look wrong, let me start that one over". With a Date Range
|
||
* of a week or a month the phone re-sends the metric on its next sync, so this is a *reset* rather
|
||
* than a loss — and every other metric, the workouts and the ingest key are untouched, which is
|
||
* what makes it safe to do without thinking about the rest of the profile.
|
||
*
|
||
* @returns {{doc:object|null, days:number, found:boolean}} `doc` is null when the profile has no
|
||
* health file at all, so the caller can leave the file alone instead of writing an empty one.
|
||
*/
|
||
export function dropMetric(doc, metric) {
|
||
if (!doc || typeof doc !== 'object') return { doc: null, days: 0, found: false };
|
||
const out = normalizeDoc(doc);
|
||
const name = String(metric || '');
|
||
if (!Object.prototype.hasOwnProperty.call(out.metrics, name)) return { doc, days: 0, found: false };
|
||
const days = Object.keys(out.metrics[name].days || {}).length;
|
||
delete out.metrics[name];
|
||
return { doc: out, days, found: true };
|
||
}
|
||
|
||
/**
|
||
* 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 };
|
||
}
|