Salud: el total del día es el día, y un recibo que explica el número que no cuadra
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
"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.
This commit is contained in:
1 parent
81301523ab
commit
407d7c47c9
9 files changed
+373
-19
No files matched your search
@@ -1369,6 +1369,11 @@ body.chips-dragging *{cursor:inherit}
|
||||
/* The receipt line under the range control: dimmer and closer to the caption above it than to the
|
||||
cards, because it is an answer to "why has nothing moved", not a measurement. */
|
||||
.vh-sync{margin:-6px 2px 12px;line-height:1.45}
|
||||
/* A day whose hours and total disagree, said in words. Amber rather than red: nothing is broken —
|
||||
the two numbers are both real, and one of them is the day. */
|
||||
.vh-note{margin:10px 0 0;padding:9px 11px;border-radius:var(--r-sm);font-size:12.5px;line-height:1.5;
|
||||
color:var(--label-2);background:color-mix(in srgb,var(--orange) 12%,transparent);
|
||||
border:var(--hair) solid color-mix(in srgb,var(--orange) 30%,transparent)}
|
||||
.ins-card{--tint:var(--acc);padding:12px 14px 14px;margin-bottom:12px}
|
||||
.ins-hd{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:4px}
|
||||
.ins-t{display:flex;align-items:center;gap:6px;font-size:14px;font-weight:600;color:var(--tint)}
|
||||
|
||||
@@ -380,6 +380,48 @@ export function detailRows(card, day, m) {
|
||||
}))
|
||||
}
|
||||
|
||||
/* ---------- the receipt: what the phone actually sent ---------- */
|
||||
|
||||
/* The shape of the last payload for a metric, as words. This is the screen's answer to "the number
|
||||
does not match the Health app", which is a question no number can answer about itself: 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. The receipt says which of those it is looking at. */
|
||||
const STAMP_LABEL = { day: 'one total a day', hour: 'one total an hour', sample: 'individual samples', mixed: 'mixed stamps' }
|
||||
export const stampLabel = kind => (STAMP_LABEL[kind] ? t(STAMP_LABEL[kind]) : String(kind || ''))
|
||||
|
||||
/** The receipt as rows: how it was stamped, where it came from, what it adds up to. */
|
||||
export function receiptRows(shape) {
|
||||
if (!shape || !shape.points) return []
|
||||
const rows = [
|
||||
{ key: 'points', label: t('Datapoints in the last sync'), value: fmtValue(shape.points) },
|
||||
{ key: 'stamps', label: t('How they were stamped'), value: stampLabel(shape.stamps) },
|
||||
{ key: 'sources', label: t('Sources'), value: (shape.sources || []).join(', ') || t('not reported') }
|
||||
]
|
||||
if (shape.sum != null && shape.field) rows.push({ key: 'sum', label: t('{0} adds up to', shape.field), value: fmtValue(shape.sum, 0) })
|
||||
if (shape.newest) rows.push({ key: 'newest', label: t('Newest value'), value: fmtValue(shape.newest.value, 0) })
|
||||
// The three newest values, oldest first: a run of rising numbers is the tell that they are running
|
||||
// totals rather than one hour each, and it is the difference between 499 and 840.
|
||||
if (Array.isArray(shape.tail) && shape.tail.length > 1) {
|
||||
rows.push({ key: 'tail', label: t('Latest values, oldest first'), value: shape.tail.map(([, v]) => fmtValue(v, 0)).join(' → ') })
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the day we are showing disagrees with the sum of its own hours — the single most useful
|
||||
* comparison on this screen, because a day total and a sum of hours that do not match is a number
|
||||
* somebody has to explain, and both numbers are right there.
|
||||
*/
|
||||
export function dayConflict(day) {
|
||||
if (!day || !day.hours_sum || !day.f) return null
|
||||
const sums = Object.entries(day.hours_sum).filter(([, v]) => Number.isFinite(v))
|
||||
if (sums.length !== 1) return null
|
||||
const [field, sum] = sums[0]
|
||||
const shown = day.f[field] && day.f[field].sum
|
||||
if (!Number.isFinite(shown) || !Number.isFinite(sum) || shown === sum) return null
|
||||
return { field, shown, sum, declared: !!day.own }
|
||||
}
|
||||
|
||||
/* ---------- the hours behind a day, and the days behind a card ---------- */
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
METRICS, specOf, humanize, valueOfDay, metricCards, sortCards, groupedCards, trendOf,
|
||||
chartPoints, workoutRows, hasVitals, activeDays, ingestUrl, unitLabel, fmtValue, agoLabel,
|
||||
detailRows, workoutIcon, GROUP_ORDER, tintOf, dayLabel,
|
||||
hourRows, hourChartPoints, historyRows
|
||||
hourRows, hourChartPoints, historyRows, receiptRows, dayConflict, stampLabel
|
||||
} from './vitals-view.js'
|
||||
|
||||
/* The mapping from HAE's metric names to what a card shows. Worth testing because it is the one
|
||||
@@ -353,6 +353,44 @@ describe('days, units and captions', () => {
|
||||
expect(historyRows(cards[0]).every(r => r.hours === 0)).toBe(true)
|
||||
})
|
||||
|
||||
/* The receipt and the day-conflict line: the two things that explain a number nobody can explain
|
||||
from the number itself. Worth testing because they are *sentences about data* — the place where
|
||||
"the hours add up to 840" quietly becomes "the day is 840" if nobody is looking. */
|
||||
it('turns the sync receipt into rows a person can read', () => {
|
||||
const rows = receiptRows({
|
||||
at: 1, points: 720, field: 'qty', stamps: 'hour', sources: ['Apple Watch', 'iPhone'],
|
||||
sum: 840, newest: { stamp: '2026-09-23 14:00:00 +0000', value: 499 },
|
||||
head: [['2026-09-23 08:00:00 +0000', 120]], tail: [['2026-09-23 12:00:00 +0000', 340], ['2026-09-23 13:00:00 +0000', 420], ['2026-09-23 14:00:00 +0000', 499]]
|
||||
})
|
||||
const get = k => rows.find(r => r.key === k)?.value
|
||||
expect(get('points')).toBe('720')
|
||||
expect(get('stamps')).toBe('one total an hour')
|
||||
expect(get('sources')).toBe('Apple Watch, iPhone')
|
||||
expect(get('sum')).toBe('840')
|
||||
expect(get('newest')).toBe('499')
|
||||
// A run of rising numbers is the tell that they are running totals, not one hour each.
|
||||
expect(get('tail')).toBe('340 → 420 → 499')
|
||||
expect(receiptRows(null)).toEqual([])
|
||||
expect(receiptRows({ points: 0 })).toEqual([])
|
||||
// Nothing reported is said as nothing, not as an empty join.
|
||||
expect(receiptRows({ points: 2, stamps: 'day', field: 'qty', sum: 10 }).find(r => r.key === 'sources').value).toBe('not reported')
|
||||
})
|
||||
|
||||
it('sees when a day disagrees with the sum of its own hours', () => {
|
||||
const day = { day: '2026-09-23', f: { qty: bucket(499) }, hours_sum: { qty: 340 }, own: true }
|
||||
expect(dayConflict(day)).toEqual({ field: 'qty', shown: 499, sum: 340, declared: true })
|
||||
// Agreement is not a conflict, and neither is a day with no hours behind it.
|
||||
expect(dayConflict({ ...day, hours_sum: { qty: 499 } })).toBe(null)
|
||||
expect(dayConflict({ day: '2026-09-23', f: { qty: bucket(499) } })).toBe(null)
|
||||
expect(dayConflict(null)).toBe(null)
|
||||
// A sum that is not the day's own is still a conflict worth saying out loud.
|
||||
expect(dayConflict({ f: { qty: bucket(840) }, hours_sum: { qty: 840 } , own: false })).toBe(null)
|
||||
expect(dayConflict({ f: { qty: bucket(840) }, hours_sum: { qty: 340 }, own: false }))
|
||||
.toEqual({ field: 'qty', shown: 840, sum: 340, declared: false })
|
||||
// Several fields at once is not something to guess about.
|
||||
expect(dayConflict({ f: { qty: bucket(1) }, hours_sum: { qty: 2, Avg: 3 } })).toBe(null)
|
||||
})
|
||||
|
||||
it('builds an absolute ingest URL that survives a subpath deployment', () => {
|
||||
expect(ingestUrl({ origin: 'https://gym.example.com', pathname: '/' })).toBe('https://gym.example.com/api/vitals/ingest')
|
||||
expect(ingestUrl({ origin: 'https://example.com', pathname: '/gym/' })).toBe('https://example.com/gym/api/vitals/ingest')
|
||||
|
||||
@@ -1406,6 +1406,20 @@ export default {
|
||||
// resetting one measurement, from its own detail sheet
|
||||
'Reset this measurement': 'Reiniciar esta medición',
|
||||
// segunda opinión (Jev)
|
||||
'What arrived last': 'Qué llegó en el último envío',
|
||||
'Datapoints in the last sync': 'Datos en el último envío',
|
||||
'How they were stamped': 'Cómo vienen marcados',
|
||||
'Sources': 'Fuentes',
|
||||
'not reported': 'sin informar',
|
||||
'Newest value': 'Valor más nuevo',
|
||||
'Latest values, oldest first': 'Últimos valores, del más viejo al más nuevo',
|
||||
'{0} adds up to': '{0} suma',
|
||||
'one total a day': 'un total por día',
|
||||
'one total an hour': 'un total por hora',
|
||||
'individual samples': 'muestras individuales',
|
||||
'mixed stamps': 'marcas mezcladas',
|
||||
'The phone declared {0} for this day, and its hours add up to {1}. The declared total is the one shown — the hours are how the day was shaped, not a second number to add.': 'El teléfono declaró {0} para este día, y sus horas suman {1}. El número que se muestra es el total declarado: las horas son la forma del día, no un segundo número para sumar.',
|
||||
'This day\'s hours add up to {0} but the day shows {1}, which means the phone sent a total for the day as well as its hours.': 'Las horas de este día suman {0} pero el día muestra {1}: el teléfono mandó también un total del día además de sus horas.',
|
||||
'Second opinion': 'Segunda opinión',
|
||||
'Second opinion updated': 'Segunda opinión actualizada',
|
||||
'What is sent': 'Qué se envía',
|
||||
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
hourRows, hourChartPoints, historyRows
|
||||
} from '../lib/vitals-view.js'
|
||||
import { insightView, sentRows, pct } from '../lib/insight-view.js'
|
||||
import { receiptRows, dayConflict } from '../lib/vitals-view.js'
|
||||
|
||||
/* The period filter, "Today" first and by default: a card's headline is always the newest
|
||||
reading, and "is that right now?" is the question a five-minute cadence exists to answer. The
|
||||
@@ -225,6 +226,8 @@ function MetricSheet({ card, metric, close, onReset }) {
|
||||
return () => { live = false }
|
||||
}, [card.name, day, dayHours])
|
||||
|
||||
const receipt = receiptRows(metric && metric.shape)
|
||||
const conflict = dayConflict(metric && metric.days ? metric.days.find(d => d.day === card.day) : null)
|
||||
const hourList = hourRows(hours, card)
|
||||
const history = historyRows(card)
|
||||
const val = r => fmtValue(r.value, card.dec) + (unitLabel(card.unit) ? ' ' + unitLabel(card.unit) : '')
|
||||
@@ -258,6 +261,12 @@ function MetricSheet({ card, metric, close, onReset }) {
|
||||
{t('This metric arrived as one total a day. Health Auto Export keeps the hours if you set Time grouping to Hours, and then this sheet draws the day hour by hour — the day total is the sum of them, so nothing is counted twice.')}
|
||||
</div>}
|
||||
|
||||
{conflict && <div className="vh-note">
|
||||
{conflict.declared
|
||||
? t('The phone declared {0} for this day, and its hours add up to {1}. The declared total is the one shown — the hours are how the day was shaped, not a second number to add.', fmtValue(conflict.shown, card.dec), fmtValue(conflict.sum, card.dec))
|
||||
: t('This day\'s hours add up to {0} but the day shows {1}, which means the phone sent a total for the day as well as its hours.', fmtValue(conflict.sum, card.dec), fmtValue(conflict.shown, card.dec))}
|
||||
</div>}
|
||||
|
||||
{history.length > 1 && <>
|
||||
<h4 className="sec">{t('Day by day')}</h4>
|
||||
<div className="list">
|
||||
@@ -280,6 +289,14 @@ function MetricSheet({ card, metric, close, onReset }) {
|
||||
{card.sources.length ? ' · ' + card.sources.join(', ') : ''}
|
||||
</div>
|
||||
|
||||
{/* What the phone actually sent for this metric, last sync. It is here because "the number in
|
||||
the app does not match the Health app" cannot be answered by the number itself: the shape of
|
||||
what arrived is the answer. */}
|
||||
{receipt.length > 0 && <>
|
||||
<h4 className="sec">{t('What arrived last')}</h4>
|
||||
<div className="list">{receipt.map(r => <Row key={r.key} title={r.label} value={r.value} />)}</div>
|
||||
</>}
|
||||
|
||||
{/* Starting one measurement over, not the whole profile. The two rows that can delete health
|
||||
data are worded so they cannot be confused: this one names the metric it resets, and the
|
||||
one in the setup sheet says it takes everything. */}
|
||||
|
||||
@@ -394,6 +394,43 @@ describe('the detail sheet', () => {
|
||||
expect(sheet()).not.toContain('This metric arrived as one total a day')
|
||||
})
|
||||
|
||||
/* The sheet has to be able to explain a number that does not match the Health app, because the
|
||||
number cannot explain itself: what arrived, how it was stamped, and — when the day and its own
|
||||
hours disagree — which of the two is being shown. */
|
||||
it('shows what arrived, and says so when a day disagrees with its own hours', async () => {
|
||||
const withReceipt = () => ({
|
||||
...VITALS,
|
||||
metrics: {
|
||||
step_count: {
|
||||
units: 'count', sources: ['Apple Watch', 'iPhone'],
|
||||
shape: {
|
||||
at: Date.now(), points: 720, field: 'qty', stamps: 'hour', sources: ['Apple Watch', 'iPhone'],
|
||||
sum: 840, newest: { stamp: '2026-09-23 14:00:00 +0000', value: 499, ms: 1 },
|
||||
head: [['2026-09-23 08:00:00 +0000', 120]],
|
||||
tail: [['2026-09-23 12:00:00 +0000', 340], ['2026-09-23 13:00:00 +0000', 420], ['2026-09-23 14:00:00 +0000', 499]]
|
||||
},
|
||||
days: [
|
||||
{ ...day('2026-09-02', { qty: bucket(11000) }), hours: 24, own: false, hours_sum: { qty: 11000 } },
|
||||
{ ...day('2026-09-03', { qty: bucket(499) }), hours: 3, own: true, hours_sum: { qty: 340 } }
|
||||
]
|
||||
}
|
||||
}
|
||||
})
|
||||
route(withReceipt(), HOURS)
|
||||
await mountWithSheets()
|
||||
openSteps()
|
||||
await act(async () => {})
|
||||
|
||||
const text = sheet()
|
||||
expect(text).toContain('What arrived last')
|
||||
expect(text).toContain('one total an hour')
|
||||
expect(text).toContain('Apple Watch, iPhone')
|
||||
expect(text).toContain('340 → 420 → 499')
|
||||
// The day keeps the phone's total, and the sheet says why the two numbers differ instead of
|
||||
// leaving whoever noticed to guess.
|
||||
expect(text).toContain('The phone declared 499 for this day, and its hours add up to 340')
|
||||
})
|
||||
|
||||
it('says the automation groups by day instead of drawing an empty hour list', async () => {
|
||||
route(VITALS, HOURS)
|
||||
await mountWithSheets()
|
||||
|
||||
Reference in new issue
Block a user