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.
527 lines
28 KiB
JavaScript
527 lines
28 KiB
JavaScript
/* The merge rule is the whole point of vitals.js: an automation that runs every five minutes
|
||
must not turn a day of steps into three days of steps. These tests are all about that, plus
|
||
the shapes HAE actually sends (day-grouped totals, raw samples, Min/Avg/Max heart rate,
|
||
aggregated and segmented sleep, blood pressure, a metric that is selected but empty).
|
||
|
||
Every merge is given an explicit `now`, because the dedupe ledger is pruned against the wall
|
||
clock: a test that let the real clock in would delete its own fixtures the moment they were a
|
||
few days old, and start passing for the wrong reason. */
|
||
import { test } from 'node:test';
|
||
import assert from 'node:assert/strict';
|
||
import {
|
||
parsePayload, mergeVitals, vitalsSeries, vitalsHours, dropMetric, emptyVitals, parseHaeDate,
|
||
normalizeDoc, RETENTION_DAYS, LEDGER_MS, HOURS_KEPT_DAYS
|
||
} from '../vitals.js';
|
||
|
||
const NOW = Date.parse('2026-05-01T23:30:00Z');
|
||
const merge = (doc, payload, now = NOW) => mergeVitals(doc, payload, now);
|
||
const at = (day, time = '00:00:00', off = '+0000') => `${day} ${time} ${off}`;
|
||
/** One metric, one payload. */
|
||
const metric = (name, units, data) => ({ data: { metrics: [{ name, units, data }] } });
|
||
|
||
/* ---------- parsing ---------- */
|
||
|
||
test('parses both HAE date spellings, including the 12-hour one with a narrow no-break space', () => {
|
||
const a = parseHaeDate('2026-05-01 13:04:05 +0200');
|
||
assert.equal(a.day, '2026-05-01');
|
||
assert.equal(a.time, '13:04:05');
|
||
assert.equal(a.ms, Date.parse('2026-05-01T13:04:05+02:00'));
|
||
|
||
// U+202F between the time and the meridiem — what HAE writes on a 12-hour phone.
|
||
const b = parseHaeDate('2026-05-01 1:04:05\u202fPM -0700');
|
||
assert.equal(b.time, '13:04:05');
|
||
assert.equal(b.ms, Date.parse('2026-05-01T13:04:05-07:00'));
|
||
|
||
// The two hours a naive modulo gets wrong.
|
||
assert.equal(parseHaeDate('2026-05-01 12:00:00\u202fAM +0000').time, '00:00:00');
|
||
assert.equal(parseHaeDate('2026-05-01 12:30:00\u202fPM +0000').time, '12:30:00');
|
||
// No offset at all means UTC, not "whatever the server is".
|
||
assert.equal(parseHaeDate('2026-05-01 08:00:00').ms, Date.parse('2026-05-01T08:00:00Z'));
|
||
assert.equal(parseHaeDate('not a date'), null);
|
||
assert.equal(parseHaeDate('2026-13-45 08:00:00 +0000'), null);
|
||
assert.equal(parseHaeDate(undefined), null);
|
||
});
|
||
|
||
test('parsePayload accepts v2 (wrapped in data), the older flat shape, and drops empty metrics', () => {
|
||
const v2 = parsePayload({
|
||
data: {
|
||
metrics: [
|
||
{ name: 'step_count', units: 'count', data: [{ qty: 100, date: at('2026-05-01', '09:00:00') }] },
|
||
{ name: 'basal_body_temperature', units: 'degC', data: null }
|
||
],
|
||
workouts: []
|
||
}
|
||
});
|
||
assert.equal(v2.metrics.length, 2);
|
||
assert.equal(v2.metrics[1].points.length, 0, 'a selected-but-empty metric parses to no points');
|
||
|
||
const flat = parsePayload({ metrics: [{ name: 'weight_body_mass', units: 'kg', data: [{ qty: 80, date: at('2026-05-01', '07:00:00') }] }] });
|
||
assert.equal(flat.metrics[0].points[0].fields.qty, 80);
|
||
|
||
assert.throws(() => parsePayload({ hello: 'world' }), e => e.code === 'shape');
|
||
assert.throws(() => parsePayload(null), e => e.code === 'shape');
|
||
assert.throws(() => parsePayload({ data: { metrics: [], workouts: [] } }), e => e.code === 'empty');
|
||
// A datapoint with no readable date, or with no numbers at all, is not a datapoint.
|
||
const junk = parsePayload(metric('foo', 'x', [{ qty: 1, date: 'nonsense' }, { date: at('2026-05-01') }]));
|
||
assert.equal(junk.metrics[0].points.length, 0);
|
||
});
|
||
|
||
/* ---------- the merge rule ---------- */
|
||
|
||
test('raw samples: disjoint windows accumulate, overlapping ones do not double count', () => {
|
||
const p = (t, qty) => ({ qty, date: at('2026-05-01', t) });
|
||
|
||
// "Since Last Sync": each run carries only what happened since the last one.
|
||
let doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [p('09:00:00', 300), p('09:05:00', 700)]))).doc;
|
||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1000);
|
||
const inc = merge(doc, parsePayload(metric('step_count', 'count', [p('09:10:00', 200), p('09:15:00', 800)])));
|
||
doc = inc.doc;
|
||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 2000, 'new samples add on');
|
||
assert.equal(inc.stats.points, 2);
|
||
|
||
// "Today": every run re-sends the whole day, with the two samples since the last run added.
|
||
const today = metric('step_count', 'count', [
|
||
p('09:00:00', 300), p('09:05:00', 700), p('09:10:00', 200), p('09:15:00', 800),
|
||
p('09:20:00', 1000), p('09:25:00', 500)
|
||
]);
|
||
const first = merge(doc, parsePayload(today));
|
||
assert.equal(first.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 3500, 'only the two new samples count');
|
||
assert.equal(first.stats.points, 2);
|
||
assert.equal(first.stats.duplicates, 4);
|
||
|
||
const again = merge(first.doc, parsePayload(today));
|
||
assert.equal(again.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 3500, 're-sending changes nothing');
|
||
assert.equal(again.stats.points, 0);
|
||
assert.equal(again.stats.duplicates, 6);
|
||
});
|
||
|
||
test('day-grouped payloads replace the day: a growing total never adds up', () => {
|
||
const grouped = sum => metric('step_count', 'count', [{ qty: sum, date: at('2026-05-01') }]);
|
||
let doc = merge(emptyVitals(), parsePayload(grouped(1200))).doc;
|
||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1200);
|
||
|
||
// Ten more syncs through the day, each carrying the day's total so far — "Time Grouping: Days".
|
||
for (const total of [1400, 2600, 4100, 9800]) doc = merge(doc, parsePayload(grouped(total))).doc;
|
||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800, 'replaced, not accumulated');
|
||
|
||
const same = merge(doc, parsePayload(grouped(9800)));
|
||
assert.equal(same.stats.duplicates, 1);
|
||
assert.equal(same.stats.points, 0, 'the same total again is a no-op');
|
||
assert.equal(same.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800);
|
||
|
||
// A day-grouped payload covering several days corrects each of them independently.
|
||
const multi = merge(same.doc, parsePayload(metric('step_count', 'count', [
|
||
{ qty: 9800, date: at('2026-05-01') }, { qty: 3000, date: at('2026-04-30') }
|
||
])));
|
||
assert.equal(multi.doc.metrics.step_count.days['2026-04-30'].f.qty.sum, 3000);
|
||
assert.equal(multi.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800);
|
||
});
|
||
|
||
test('a day total and raw samples for the same day are kept apart by their own payload shape', () => {
|
||
// Two metrics in one payload, one grouped by day and one raw: each takes its own branch.
|
||
const body = {
|
||
data: {
|
||
metrics: [
|
||
{ name: 'step_count', units: 'count', data: [{ qty: 5000, date: at('2026-05-01') }] },
|
||
{ name: 'resting_heart_rate', units: 'bpm', data: [{ qty: 52, date: at('2026-05-01', '06:30:00') }] }
|
||
]
|
||
}
|
||
};
|
||
const { doc } = merge(emptyVitals(), parsePayload(body));
|
||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 5000);
|
||
assert.equal(doc.metrics.resting_heart_rate.days['2026-05-01'].f.qty.sum, 52);
|
||
});
|
||
|
||
test('the day key is the phone\'s own date, not the server\'s', () => {
|
||
// 23:30 in Manila is the previous day in UTC. The sample belongs to the phone's day.
|
||
const { doc } = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
|
||
{ qty: 500, date: at('2026-05-01', '23:30:00', '+0800') }
|
||
])));
|
||
assert.deepEqual(Object.keys(doc.metrics.step_count.days), ['2026-05-01']);
|
||
});
|
||
|
||
/* ---------- the shapes HAE actually sends ---------- */
|
||
|
||
test('heart rate keeps Min/Avg/Max per day instead of pretending they are one number', () => {
|
||
const body = metric('heart_rate', 'bpm', [
|
||
{ date: at('2026-05-01', '09:00:00'), Min: 58, Avg: 72, Max: 96, source: 'Apple Watch' },
|
||
{ date: at('2026-05-01', '10:00:00'), Min: 55, Avg: 68, Max: 88, source: 'Apple Watch' }
|
||
]);
|
||
const { doc } = merge(emptyVitals(), parsePayload(body));
|
||
const day = doc.metrics.heart_rate.days['2026-05-01'];
|
||
assert.equal(day.f.Avg.n, 2);
|
||
assert.equal(Math.round(day.f.Avg.sum), 140);
|
||
assert.equal(day.f.Min.min, 55);
|
||
assert.equal(day.f.Max.max, 96);
|
||
assert.deepEqual(doc.metrics.heart_rate.sources, ['Apple Watch']);
|
||
});
|
||
|
||
test('sleep: both the aggregated night and the segmented one land as hours per day', () => {
|
||
const aggregated = metric('sleep_analysis', 'hr', [{
|
||
date: at('2026-05-01', '07:00:00'),
|
||
sleepStart: at('2026-04-30', '23:10:00'), sleepEnd: at('2026-05-01', '06:55:00'),
|
||
inBed: 8.2, asleep: 7.4, core: 4.1, deep: 1.2, rem: 2.1, awake: 0.8, source: 'Apple Watch'
|
||
}]);
|
||
const { doc } = merge(emptyVitals(), parsePayload(aggregated));
|
||
// Keyed by the day the metric's own `date` names — the morning you woke up.
|
||
assert.equal(doc.metrics.sleep_analysis.days['2026-05-01'].f.asleep.last, 7.4);
|
||
assert.equal(doc.metrics.sleep_analysis.days['2026-05-01'].f.deep.last, 1.2);
|
||
|
||
const segments = [
|
||
{ startDate: at('2026-05-01', '22:10:00'), endDate: at('2026-05-01', '22:50:00'), qty: 0.67, value: 'asleepCore' },
|
||
{ startDate: at('2026-05-01', '23:10:00'), endDate: at('2026-05-01', '23:25:00'), qty: 1.33, value: 'asleepDeep' }
|
||
];
|
||
const seg = merge(emptyVitals(), parsePayload(metric('sleep_analysis', 'hr', segments))).doc;
|
||
// Segments carry no `date`, only startDate/endDate, so the day comes from the segment start.
|
||
assert.equal(seg.metrics.sleep_analysis.days['2026-05-01'].f.qty.sum, 2);
|
||
assert.equal(seg.metrics.sleep_analysis.days['2026-05-01'].f.qty.n, 2);
|
||
|
||
const repeat = merge(seg, parsePayload(metric('sleep_analysis', 'hr', segments)));
|
||
assert.equal(repeat.stats.duplicates, 2, 'the same segments again are the same segments');
|
||
assert.equal(repeat.doc.metrics.sleep_analysis.days['2026-05-01'].f.qty.sum, 2, 'and do not add up twice');
|
||
});
|
||
|
||
test('blood pressure keeps both numbers, and an unknown metric is stored rather than dropped', () => {
|
||
const body = {
|
||
data: {
|
||
metrics: [
|
||
{ name: 'blood_pressure_systolic', units: 'mmHg', data: [{ date: at('2026-05-01', '08:00:00'), systolic: 128, diastolic: 82 }] },
|
||
{ name: 'walking_steadiness', units: '%', data: [{ date: at('2026-05-01', '08:00:00'), qty: 91 }] }
|
||
]
|
||
}
|
||
};
|
||
const { doc } = merge(emptyVitals(), parsePayload(body));
|
||
assert.equal(doc.metrics.blood_pressure_systolic.days['2026-05-01'].f.systolic.last, 128);
|
||
assert.equal(doc.metrics.blood_pressure_systolic.days['2026-05-01'].f.diastolic.last, 82);
|
||
assert.equal(doc.metrics.walking_steadiness.days['2026-05-01'].f.qty.last, 91);
|
||
});
|
||
|
||
/* ---------- workouts ---------- */
|
||
|
||
test('workouts dedupe on name+start+end, newest first, and a re-send adds nothing', () => {
|
||
const w = (name, start, end, energy) => ({
|
||
name, start, end,
|
||
activeEnergy: { qty: energy, units: 'kcal' },
|
||
distance: { qty: 3.2, units: 'km' },
|
||
heartRateData: [{ date: at('2026-05-01', '18:00:00'), Avg: 128 }, { date: at('2026-05-01', '18:05:00'), Avg: 136, Max: 172 }]
|
||
});
|
||
const body = {
|
||
data: {
|
||
workouts: [
|
||
w('Walking', at('2026-05-01', '17:00:00'), at('2026-05-01', '18:00:00'), 210),
|
||
w('Functional Strength Training', at('2026-05-01', '07:00:00'), at('2026-05-01', '07:45:00'), 320)
|
||
]
|
||
}
|
||
};
|
||
|
||
const first = merge(emptyVitals(), parsePayload(body));
|
||
assert.equal(first.stats.workouts, 2);
|
||
assert.equal(first.doc.workouts[0].name, 'Walking', 'newest first (17:00 after 07:00)');
|
||
assert.equal(first.doc.workouts[0].durMin, 60);
|
||
assert.equal(first.doc.workouts[0].fields.activeEnergy.qty, 210);
|
||
assert.equal(first.doc.workouts[0].avgHr, 132, 'average of the heart-rate samples');
|
||
assert.equal(first.doc.workouts[0].maxHr, 172);
|
||
assert.equal(first.doc.workouts[1].name, 'Functional Strength Training');
|
||
assert.equal(first.doc.workouts[1].fields.activeEnergy.qty, 320);
|
||
|
||
const again = merge(first.doc, parsePayload(body));
|
||
assert.equal(again.stats.workouts, 0);
|
||
assert.equal(again.stats.duplicates, 2);
|
||
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('the phone\'s own day total is the day, and hours never get added to it', () => {
|
||
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 number the Health app
|
||
// shows, so it becomes the day — and the hours 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 hour points arrive for the same day. The day does NOT become their sum: the declared total
|
||
// already contains the hours below it, and adding them is exactly how 499 steps became 840. The
|
||
// sum rides beside it instead, so a disagreement between the two is visible rather than silent.
|
||
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;
|
||
const day = doc.metrics.step_count.days['2026-05-01'];
|
||
assert.equal(day.f.qty.sum, 1500, 'the phone\'s total is still the day');
|
||
assert.equal(day.own, true);
|
||
assert.equal(Object.keys(day.h).length, 3, 'and the hours still landed');
|
||
assert.equal(day.hsum.qty, 1600, 'with their sum beside them, for the screen to compare');
|
||
|
||
// A newer total replaces it, as it always did.
|
||
assert.equal(merge(doc, parsePayload(metric('step_count', 'count', [{ qty: 1700, date: at('2026-05-01') }]))).doc
|
||
.metrics.step_count.days['2026-05-01'].f.qty.sum, 1700);
|
||
});
|
||
|
||
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('a midnight total inside an hourly payload is the day, not hour zero', () => {
|
||
// The shape that produced "the watch says 499 and the app says 840": HAE sends the day's total
|
||
// stamped at midnight *and* the hours, in one payload. Read as hour 00, the total is added to the
|
||
// hours and the day doubles; read as what it is, the day is 499 and the hours are its shape.
|
||
const p = (qty, time) => ({ qty, date: at('2026-05-01', time) });
|
||
const payload = metric('step_count', 'count', [
|
||
p(499, '00:00:00'), // the day's own total, stamped at midnight
|
||
p(120, '08:00:00'), p(220, '09:00:00') // and two hours of it
|
||
]);
|
||
const doc = merge(emptyVitals(), parsePayload(payload)).doc;
|
||
const day = doc.metrics.step_count.days['2026-05-01'];
|
||
assert.equal(day.f.qty.sum, 499, 'the day is the total, not 499 + 340');
|
||
assert.equal(day.own, true);
|
||
assert.equal(day.h['00'], undefined, 'and the midnight point did not become hour 00');
|
||
assert.deepEqual(Object.keys(day.h).sort(), ['08', '09']);
|
||
assert.equal(day.hsum.qty, 340, 'the sum of the hours is kept beside it');
|
||
|
||
// The same payload again is a no-op on the day, and the hours converge.
|
||
const grew = merge(doc, parsePayload(metric('step_count', 'count', [
|
||
p(499, '00:00:00'), p(120, '08:00:00'), p(260, '09:00:00')
|
||
]))).doc.metrics.step_count.days['2026-05-01'];
|
||
assert.equal(grew.f.qty.sum, 499);
|
||
assert.equal(grew.h['09'].f.qty.sum, 260);
|
||
|
||
// A genuine 00:00 bucket — a handful of steps, less than the rest of the day — stays hour 00.
|
||
const small = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
|
||
p(3, '00:00:00'), p(300, '08:00:00'), p(400, '09:00:00')
|
||
]))).doc.metrics.step_count.days['2026-05-01'];
|
||
assert.equal(small.f.qty.sum, 703, 'a real first hour is summed like any other');
|
||
assert.equal(small.h['00'].f.qty.sum, 3);
|
||
assert.equal(small.own, undefined);
|
||
});
|
||
|
||
test('the receipt records what arrived, so a wrong number can be explained', () => {
|
||
const doc = merge(emptyVitals(), parsePayload({
|
||
data: { metrics: [
|
||
{ name: 'step_count', units: 'count', data: [
|
||
{ qty: 120, date: at('2026-05-01', '08:00:00'), source: 'Apple Watch' },
|
||
{ qty: 220, date: at('2026-05-01', '09:00:00'), source: 'Apple Watch' },
|
||
{ qty: 90, date: at('2026-05-01', '09:30:00'), source: 'iPhone' }
|
||
] }
|
||
] }
|
||
}), NOW).doc;
|
||
const r = doc.shape.step_count;
|
||
assert.equal(r.points, 3);
|
||
assert.equal(r.stamps, 'mixed', 'a payload with an hour and a real instant says so');
|
||
assert.equal(r.field, 'qty');
|
||
assert.deepEqual(r.sources, ['Apple Watch', 'iPhone']);
|
||
assert.equal(r.sum, 430);
|
||
assert.equal(r.newest.value, 90);
|
||
assert.equal(r.tail.length, 3);
|
||
assert.equal(r.head.length, 3);
|
||
assert.equal(r.at, NOW);
|
||
|
||
// Hour-stamped and day-stamped payloads are labelled too, because that is the question the
|
||
// receipt exists to answer.
|
||
const hourly = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
|
||
{ qty: 120, date: at('2026-05-01', '08:00:00') }, { qty: 220, date: at('2026-05-01', '09:00:00') }
|
||
]))).doc;
|
||
assert.equal(hourly.shape.step_count.stamps, 'hour');
|
||
const dayly = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 499, date: at('2026-05-01') }]))).doc;
|
||
assert.equal(dayly.shape.step_count.stamps, 'day');
|
||
// Replaced on every sync, never accumulated.
|
||
const again = merge(dayly, parsePayload(metric('heart_rate', 'bpm', [{ Avg: 62, date: at('2026-05-01', '09:00:00') }]))).doc;
|
||
assert.equal(again.shape.step_count.points, 1, 'the metric that did not arrive keeps its receipt');
|
||
assert.equal(again.shape.heart_rate.field, 'Avg');
|
||
// It survives a reload of the file, and it is not read by anything that computes a number.
|
||
assert.equal(normalizeDoc(JSON.parse(JSON.stringify(again))).shape.step_count.points, 1);
|
||
});
|
||
|
||
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', () => {
|
||
// 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: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: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']);
|
||
|
||
// Days past retention are dropped.
|
||
const old = new Date(NOW - (RETENTION_DAYS + 30) * 86400000).toISOString().slice(0, 10);
|
||
const withOld = normalizeDoc({ metrics: { step_count: { days: { [old]: { n: 1, f: { qty: { n: 1, sum: 1, min: 1, max: 1, last: 1 } } } } } } });
|
||
const pruned = merge(withOld, parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-01', '09:00:00') }]))).doc;
|
||
assert.equal(pruned.metrics.step_count.days[old], undefined);
|
||
assert.ok(LEDGER_MS === 72 * 3600 * 1000 && RETENTION_DAYS > 365);
|
||
});
|
||
|
||
test('dropMetric forgets one metric, days and all, and touches nothing else', () => {
|
||
const doc = merge(emptyVitals(), parsePayload({
|
||
data: {
|
||
metrics: [
|
||
{ name: 'step_count', units: 'count', data: [{ qty: 9000, date: at('2026-05-01') }, { qty: 8000, date: at('2026-04-30') }] },
|
||
{ name: 'heart_rate', units: 'bpm', data: [{ date: at('2026-05-01', '09:00:00'), Avg: 70 }] }
|
||
],
|
||
workouts: [{ name: 'Walking', start: at('2026-05-01', '10:00:00'), end: at('2026-05-01', '11:00:00') }]
|
||
}
|
||
}), NOW).doc;
|
||
|
||
const gone = dropMetric(doc, 'step_count');
|
||
assert.equal(gone.found, true);
|
||
assert.equal(gone.days, 2, 'and it says how much it took');
|
||
assert.equal(gone.doc.metrics.step_count, undefined);
|
||
assert.ok(gone.doc.metrics.heart_rate, 'the other metric is untouched');
|
||
assert.equal(gone.doc.workouts.length, 1, 'and a workout is not a health metric');
|
||
// The input document is not modified: this is a pure function like the merge.
|
||
assert.ok(doc.metrics.step_count);
|
||
|
||
// A metric that is not there, and a profile with no file at all, are both answers rather than
|
||
// errors — the screen says "nothing stored" instead of failing at the person.
|
||
assert.deepEqual(dropMetric(doc, 'never_heard_of_it'), { doc, days: 0, found: false });
|
||
assert.deepEqual(dropMetric(null, 'step_count'), { doc: null, days: 0, found: false });
|
||
});
|
||
|
||
test('normalizeDoc survives a hand-edited or half-written file', () => {
|
||
const d = normalizeDoc({ metrics: { step_count: null, heart_rate: { days: 'nope', units: 7, sources: 'x' } }, workouts: 'nope' });
|
||
assert.deepEqual(d.workouts, []);
|
||
assert.deepEqual(Object.keys(d.metrics), ['heart_rate']);
|
||
assert.deepEqual(d.metrics.heart_rate.days, {});
|
||
assert.deepEqual(d.metrics.heart_rate.sources, []);
|
||
assert.equal(d.metrics.heart_rate.units, '');
|
||
assert.deepEqual(normalizeDoc(null).metrics, {});
|
||
});
|
||
|
||
/* ---------- reading it back ---------- */
|
||
|
||
test('vitalsSeries gives per-field totals, averages and a window, oldest day first', () => {
|
||
const body = {
|
||
data: {
|
||
metrics: [
|
||
{ name: 'step_count', units: 'count', data: [{ qty: 4000, date: at('2026-04-30') }, { qty: 6000, date: at('2026-05-01') }] },
|
||
{ name: 'heart_rate', units: 'bpm', data: [{ date: at('2026-05-01', '09:00:00'), Min: 55, Avg: 70, Max: 90 }] }
|
||
],
|
||
workouts: [{ name: 'Walking', start: at('2026-05-01', '09:00:00'), end: at('2026-05-01', '09:30:00'), activeEnergy: { qty: 100, units: 'kcal' } }]
|
||
}
|
||
};
|
||
const { doc } = merge(emptyVitals(), parsePayload(body));
|
||
const s = vitalsSeries(doc, { days: 90, now: NOW });
|
||
assert.deepEqual(s.metrics.step_count.days.map(d => d.day), ['2026-04-30', '2026-05-01']);
|
||
assert.deepEqual(s.metrics.step_count.days.map(d => d.f.qty.sum), [4000, 6000]);
|
||
assert.equal(s.metrics.heart_rate.days[0].f.Avg.avg, 70);
|
||
assert.equal(s.metrics.step_count.units, 'count');
|
||
assert.equal(s.workouts.length, 1);
|
||
|
||
// A one-day window keeps only the day inside it.
|
||
const narrow = vitalsSeries(doc, { days: 1, now: NOW });
|
||
assert.deepEqual(narrow.metrics.step_count.days.map(d => d.day), ['2026-05-01']);
|
||
});
|