Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Reported as "le doy a cualquier actividad y solo me presenta los pasos de hoy… debiera presentarme una medida por hora, y no me da el histórico". Two separate things, and only one of them was the app's fault. **The history was the automation's setting.** With Date Range on its default (`Today`) every sync carries today and nothing else, so there is exactly one day in the file to draw. That is why a card looked frozen: not a rendering bug, a range that was never sent. The setup steps now say `Previous 7 Days` and say why. **The hours were thrown away by us.** Even when the phone sends 288 readings a day, the receiver folded every one of them into a single day aggregate, so "8,123 steps today" was all there could ever be — a number you cannot look into. Worse, the recommended setting was Time Grouping `Days`, which sends one point per metric per day: the intraday detail never arrived in the first place. The recommendation is now `Hours`, and the storage keeps the hours. The merge rule for them is the same shape as the day rule, for the same reason: a payload whose datapoints all sit on the hour is HAE's own hour grouping, and the hour *in progress* grows on every run of a five-minute automation, so it is replaced and never unioned — 500 + 900 + 1,340 steps in one hour is a number no watch recorded. The day is then recomputed as the sum of its hours, which is what keeps the card and the detail from ever disagreeing, and which also makes switching an automation from Days to Hours mid-day converge instead of double-count. Raw samples (real timestamps) still union by instant plus numbers, and they now land in their own hour, which is where intraday detail comes from when nothing is grouped. Three things that would have been silent bugs, caught while writing it: - The hour rule is decided from the **whole payload**, never from one timestamp. A five-minute automation produces samples that sit exactly on the hour, and reading one of those as an hour total wipes the hour it belongs to. There is a test with a 09:00:00 and a 09:05:00 sample in one payload, and it fails against the per-point version of the rule. - A day that arrived as a day total keeps its hours beside it, and a day stored before this existed keeps its aggregate when the first hour shows up — recomputing it from hours it does not have would delete 2,000 steps. Both are mutation-checked (removing either guard fails a test). - A payload grouped by hour writes the ledger row anyway, because a later payload with real minutes can describe the same instant and the union path can only see the ledger. Without it the raw-sample route test double-counts a single sample. The hours are the bulky part of this data, so they are kept for a week (the day aggregates still live the full 400 days), pruned when the night's file is written, and fetched one metric and one day at a time — `GET /api/vitals/hours`. A screen listing forty cards downloads none of them; the day view carries only a count per day, which is what tells the sheet whether it is worth asking. The sheet draws the hours, the days before it (tapping one moves the hour list to that day), and every field the watch sent; when the automation groups by Days it says so instead of leaving a gap where a chart should be. Coverage: 6 new tests in `api/test/vitals.test.js` (19 total) and a route test in `api/test/server-vitals.test.js` (5), the hour/history model in `vitals-view.test.js` (31), three render tests through the real sheet, the route documented in `api/openapi.yaml` and `website/api.html`, and `docs/HEALTH.md` with the settings, the new merge row and the two symptoms now in Troubleshooting.
422 lines
23 KiB
JavaScript
422 lines
23 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, 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('a day total and an hour total for the same day agree on which number is the day', () => {
|
||
const hours = metric('step_count', 'count', [
|
||
{ qty: 500, date: at('2026-05-01', '08:00:00') },
|
||
{ qty: 900, date: at('2026-05-01', '09:00:00') }
|
||
]);
|
||
let doc = merge(emptyVitals(), parsePayload(hours)).doc;
|
||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1400);
|
||
|
||
// A second automation grouped by Days sends the day itself: it is the better day number, and
|
||
// the hours are a shape the total cannot contradict, so they stay for the sheet to draw.
|
||
const total = merge(doc, parsePayload(metric('step_count', 'count', [{ qty: 1500, date: at('2026-05-01') }])));
|
||
doc = total.doc;
|
||
assert.equal(total.stats.points, 1);
|
||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1500);
|
||
assert.equal(Object.keys(doc.metrics.step_count.days['2026-05-01'].h).length, 2, 'the hours rode along');
|
||
|
||
// Then the hourly automation sends the next hour: it re-sends the whole day, so from here the
|
||
// day is the hours again — the two rules converge instead of drifting apart.
|
||
doc = merge(doc, parsePayload(metric('step_count', 'count', [
|
||
{ qty: 500, date: at('2026-05-01', '08:00:00') },
|
||
{ qty: 900, date: at('2026-05-01', '09:00:00') },
|
||
{ qty: 200, date: at('2026-05-01', '10:00:00') }
|
||
]))).doc;
|
||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1600);
|
||
});
|
||
|
||
test('a day stored before hours existed keeps its samples when the first hour arrives', () => {
|
||
// A document written by an older version: the day has an aggregate and no hours, so its samples
|
||
// cannot be placed in an hour. Rebuilding the day from the hours it does not have would throw
|
||
// 2,000 steps away; the sample is added to the day the old way and the hour is what it is.
|
||
const legacy = normalizeDoc({
|
||
metrics: { step_count: { days: { '2026-05-01': { n: 4, lastTs: 0, f: { qty: { n: 4, sum: 2000, min: 100, max: 900, last: 900 } } } } } }
|
||
});
|
||
const r = merge(legacy, parsePayload(metric('step_count', 'count', [{ qty: 300, date: at('2026-05-01', '09:05:00') }])));
|
||
const day = r.doc.metrics.step_count.days['2026-05-01'];
|
||
assert.equal(day.f.qty.sum, 2300, 'nothing already stored was lost');
|
||
assert.equal(day.f.qty.n, 5);
|
||
assert.equal(day.h['09'].f.qty.sum, 300, 'and the hour holds only what has a time of its own');
|
||
});
|
||
|
||
test('vitalsHours answers for one metric and one day, and invents nothing', () => {
|
||
const doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
|
||
{ qty: 500, date: at('2026-05-01', '08:00:00') },
|
||
{ qty: 900, date: at('2026-05-01', '09:00:00') }
|
||
]))).doc;
|
||
const got = vitalsHours(doc, { metric: 'step_count', day: '2026-05-01' });
|
||
assert.deepEqual(got.hours.map(x => x.h), ['08', '09'], 'oldest hour first');
|
||
assert.equal(got.units, 'count');
|
||
assert.equal(got.hours[0].f.qty.sum, 500);
|
||
assert.equal(got.hours[0].f.qty.avg, 500);
|
||
assert.ok(got.hours[0].ts > 0);
|
||
|
||
// A day the automation never grouped by hour — a day total, or a day that does not exist — is
|
||
// an empty list rather than a fabricated one; the screen says why instead of drawing zeros.
|
||
const grouped = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 1500, date: at('2026-05-01') }]))).doc;
|
||
assert.deepEqual(vitalsHours(grouped, { metric: 'step_count', day: '2026-05-01' }).hours, []);
|
||
assert.deepEqual(vitalsHours(doc, { metric: 'step_count', day: '2026-04-01' }).hours, []);
|
||
assert.deepEqual(vitalsHours(doc, { metric: 'not_a_metric', day: '2026-05-01' }).hours, []);
|
||
assert.equal(vitalsHours(doc, { metric: 'step_count', day: 'not-a-day' }).day, null);
|
||
assert.equal(vitalsHours(emptyVitals(), { metric: 'step_count', day: '2026-05-01' }).metric, null);
|
||
});
|
||
|
||
test('the hourly detail is pruned after a week while the day aggregates live on', () => {
|
||
const start = Date.parse('2026-05-06T12:00:00Z');
|
||
const doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
|
||
{ qty: 100, date: at('2026-05-05', '08:00:00') },
|
||
{ qty: 200, date: at('2026-05-06', '08:00:00') }
|
||
])), start).doc;
|
||
assert.ok(doc.metrics.step_count.days['2026-05-05'].h, 'hours are stored while they are recent');
|
||
|
||
// A week later the sheet can still ask for today and yesterday, and nothing it could show is
|
||
// older than this: 24 buckets × every metric × every day of the year is what this avoids.
|
||
const later = merge(doc, parsePayload(metric('step_count', 'count', [{ qty: 300, date: at('2026-05-13', '08:00:00') }])), Date.parse('2026-05-13T12:00:00Z')).doc;
|
||
assert.equal(later.metrics.step_count.days['2026-05-05'].h, undefined, 'the hours of an old day are gone');
|
||
assert.equal(later.metrics.step_count.days['2026-05-05'].f.qty.sum, 100, 'the day itself stays');
|
||
assert.ok(later.metrics.step_count.days['2026-05-06'].h, 'and a day inside the window keeps its own');
|
||
assert.ok(HOURS_KEPT_DAYS >= 2 && HOURS_KEPT_DAYS <= RETENTION_DAYS);
|
||
});
|
||
|
||
/* ---------- housekeeping ---------- */
|
||
|
||
test('the dedupe ledger and the day buckets are both pruned, so the file stays bounded', () => {
|
||
// 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('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']);
|
||
});
|