Salud: reset one measurement, without losing the rest
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
"Podemos reiniciar los números de esas mediciones para yo enviar el de hoy." The whole-file reset
already existed two taps away in the setup sheet, but it is the wrong size for the question: the
four metrics he suspects are not the profile. Throwing away a month of heart rate to start steps
over is not a reset, it is a tax.
So a metric can now be forgotten on its own: the detail sheet has **Reset this measurement**, which
deletes that metric's days (and hours) and nothing else — the other metrics, the workouts and the
ingest key stay. With any Date Range wider than a day the phone re-sends that metric on its next
sync, which is what makes this a reset rather than a loss: Apple Health still has the data, and a
day total replaces the day it names, so the stored past is rewritten rather than duplicated.
The two destructive rows are worded apart on purpose and the confirm names the metric ("¿Reiniciar
Pasos?"), because the neighbouring action in the setup sheet takes every metric there is.
`dropMetric()` is pure and returns how many days it took, and the route answers `metric: null` for
a metric the profile does not have (or a profile with no health file at all) instead of an error —
a screen that says "nothing stored" is more useful than a 404 answering a button press. Tested
from both ends: the helper's purity and arithmetic, the route against a real server (one metric
gone, the others and the workouts intact, the key still working, and a re-sync rebuilding it), and
the sheet's flow through the real confirm. Mutation-checked: pointing the row at the whole-file
delete fails it.
This commit is contained in:
1 parent
d93861a73f
commit
5c69540f62
11 files changed
+209
-7
No files matched your search
+16
-2
@@ -668,10 +668,24 @@ paths:
|
||||
delete:
|
||||
tags: [health]
|
||||
operationId: vitalsClear
|
||||
summary: Delete the caller's health data
|
||||
description: >-
|
||||
summary: Delete the caller's health data, or one metric of it
|
||||
description: |
|
||||
Removes the profile's health file and nothing else: the workout history, the account and the
|
||||
ingest key are untouched, so a phone needs no re-configuring to sync again.
|
||||
|
||||
With `?metric=` it forgets **one** measurement instead, days and hours included, and leaves
|
||||
every other metric in place — the answer to "these numbers look wrong, start this one over".
|
||||
It is a reset rather than a loss whenever the automation's Date Range is wider than a day:
|
||||
the next sync sends that metric again from Apple Health. A metric the profile does not have
|
||||
answers `200` with `metric: null`, not an error.
|
||||
parameters:
|
||||
- name: metric
|
||||
in: query
|
||||
required: false
|
||||
schema: { type: string }
|
||||
description: >-
|
||||
The metric name exactly as HAE wrote it (`step_count`, `heart_rate`…). Omit it to clear
|
||||
everything.
|
||||
responses:
|
||||
'200':
|
||||
description: Deleted (also when there was nothing stored).
|
||||
|
||||
+12
-1
@@ -19,7 +19,7 @@ import { startCadence } from './coach/cadence.js';
|
||||
import { startWarmup } from './coach/warmup.js';
|
||||
import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';
|
||||
import { verifyError } from './verify-error.js';
|
||||
import { parsePayload, mergeVitals, vitalsSeries, vitalsHours, emptyVitals, RETENTION_DAYS } from './vitals.js';
|
||||
import { parsePayload, mergeVitals, vitalsSeries, vitalsHours, dropMetric, emptyVitals, RETENTION_DAYS } from './vitals.js';
|
||||
import { hostAllowed, readCapped, parseMusicPage } from './music.js';
|
||||
|
||||
const PORT = +(process.env.PORT || 3000);
|
||||
@@ -1108,6 +1108,17 @@ const routes = {
|
||||
'DELETE /api/vitals': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
/* `?metric=` narrows the delete to one measurement — "reset Pasos", not "start over". The rest
|
||||
of the file, the workouts and the key stay, and with any Date Range wider than a day the
|
||||
phone sends that metric again on its next sync, so it comes back with Apple's numbers. */
|
||||
const metric = new URL(req.url, 'http://x').searchParams.get('metric');
|
||||
if (metric) {
|
||||
const { doc, days, found } = dropMetric(readVitals(user.id), metric);
|
||||
// No file, or no such metric in it: nothing to write, and the caller is told which it was.
|
||||
if (doc && found) writeVitals(user.id, doc);
|
||||
audit(req, 'auth.health.metric.clear', { user, msg: `${metric}:${days}` });
|
||||
return json(res, 200, { ok: true, metric: found ? metric : null, days });
|
||||
}
|
||||
try { fs.unlinkSync(vitalsFile(user.id)); } catch { /* nothing stored */ }
|
||||
audit(req, 'auth.health.clear', { user });
|
||||
json(res, 200, { ok: true });
|
||||
|
||||
@@ -251,6 +251,47 @@ test('GET /api/vitals/hours opens one metric\'s day, and only with a session', a
|
||||
assert.equal((await read('metric=nope&day=' + today)).metric, null);
|
||||
});
|
||||
|
||||
test('DELETE /api/vitals?metric= resets one measurement and keeps everything else', async t => {
|
||||
const h = await startServer(t);
|
||||
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key;
|
||||
await ingest(h, key, payload());
|
||||
await ingest(h, key, { data: { metrics: [{ name: 'step_count', units: 'count', data: [{ qty: 9000, date: `${yday} 00:00:00 +0000` }] }] } });
|
||||
|
||||
// A session, like every other read: the ingest key cannot delete anything either.
|
||||
assert.equal((await fetch(`${h.api}/api/vitals?metric=step_count`)).status, 401);
|
||||
assert.equal((await fetch(`${h.api}/api/vitals?metric=step_count`, { method: 'DELETE', headers: { Authorization: `Bearer ${key}` } })).status, 401);
|
||||
|
||||
const before = await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json();
|
||||
assert.equal(before.metrics.step_count.days.length, 2, 'two days of steps to start over from');
|
||||
|
||||
const gone = await (await fetch(`${h.api}/api/vitals?metric=step_count`, { method: 'DELETE', headers: cookie('u_h1') })).json();
|
||||
assert.deepEqual(gone, { ok: true, metric: 'step_count', days: 2 });
|
||||
|
||||
const after = await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json();
|
||||
assert.equal(after.metrics.step_count, undefined, 'the metric is gone');
|
||||
assert.deepEqual(Object.keys(after.metrics).sort(), ['heart_rate', 'weight_body_mass'], 'the others are not');
|
||||
assert.equal(after.workouts.length, 1, 'and the workouts are not health data');
|
||||
assert.equal(after.key, key, 'the key survives, so the phone keeps syncing');
|
||||
|
||||
// Asking again is not an error and not a surprise: it says it found nothing.
|
||||
assert.deepEqual(await (await fetch(`${h.api}/api/vitals?metric=step_count`, { method: 'DELETE', headers: cookie('u_h1') })).json(),
|
||||
{ ok: true, metric: null, days: 0 });
|
||||
// A profile with no health file at all answers the same way rather than writing an empty one.
|
||||
assert.deepEqual(await (await fetch(`${h.api}/api/vitals?metric=step_count`, { method: 'DELETE', headers: cookie('u_h2') })).json(),
|
||||
{ ok: true, metric: null, days: 0 });
|
||||
assert.equal((await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h2') })).json()).metrics.step_count, undefined);
|
||||
|
||||
// The phone syncs again and the metric is rebuilt from what it sends.
|
||||
assert.equal((await ingest(h, key, payload())).status, 200);
|
||||
const rebuilt = await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json();
|
||||
assert.equal(rebuilt.metrics.step_count.days.length, 1);
|
||||
assert.equal(rebuilt.metrics.step_count.days[0].f.qty.sum, 8000);
|
||||
|
||||
// ...and the whole-file delete still works when no metric is named.
|
||||
assert.equal((await fetch(`${h.api}/api/vitals`, { method: 'DELETE', headers: cookie('u_h1') })).status, 200);
|
||||
assert.deepEqual((await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json()).metrics, {});
|
||||
});
|
||||
|
||||
test('DELETE /api/vitals wipes the health file and leaves the account, the key and the workouts alone', async t => {
|
||||
const h = await startServer(t);
|
||||
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key;
|
||||
|
||||
+28
-2
@@ -9,8 +9,8 @@
|
||||
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
|
||||
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');
|
||||
@@ -385,6 +385,32 @@ test('the dedupe ledger and the day buckets are both pruned, so the file stays b
|
||||
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, []);
|
||||
|
||||
@@ -536,6 +536,28 @@ export function vitalsSeries(doc, { days = 90, now = Date.now() } = {}) {
|
||||
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.
|
||||
*
|
||||
|
||||
Reference in new issue
Block a user