Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

fix(stats): body weight can be logged for an earlier day, the way measurements can

Miles Smithc9b23d20499a
diff --git a/frontend/src/lib/bodyweight.js b/frontend/src/lib/bodyweight.js
index 385a853da..0b6871a01 100644
--- a/frontend/src/lib/bodyweight.js
+++ b/frontend/src/lib/bodyweight.js
@@ -1,7 +1,7 @@
// Weigh-ins read back week by week (Discord 'Weight'). From one morning to the next, body weight
// moves with water, salt and the last meal by more than it moves in a month, so the number worth
// following is the week's mean — the one a single weigh-in on the card cannot give you.
-import { weekKey } from './format.js'
+import { isoOf, weekKey } from './format.js'
/**
* The weigh-ins grouped into weeks, newest week first. Each week carries its mean, how many
@@ -26,3 +26,13 @@ export function weeklyWeights(bodyweight, ws) {
weeks.forEach((week, i) => { week.delta = i ? week.avg - weeks[i - 1].avg : null })
return weeks.reverse()
}
+
+/**
+ * Where a weigh-in sits on a time axis. `t` is when it was typed, which is what a sync merge goes
+ * by; for a weigh-in logged for an earlier day that is not on its day, so it is put
+ * at noon of the day it is for instead.
+ */
+export function weighInAt(b) {
+ const t = Number(b?.t)
+ return t > 0 && isoOf(new Date(t)) === b.d ? t : new Date(b.d + 'T12:00:00').getTime()
+}
diff --git a/frontend/src/lib/bodyweight.test.js b/frontend/src/lib/bodyweight.test.js
index 9085895bd..37a5526da 100644
--- a/frontend/src/lib/bodyweight.test.js
+++ b/frontend/src/lib/bodyweight.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { weeklyWeights } from './bodyweight.js'
+import { weeklyWeights, weighInAt } from './bodyweight.js'
// Discord 'Weight': every weigh-in, week by week, with the week's mean.
describe('weeklyWeights', () => {
@@ -39,3 +39,20 @@ describe('weeklyWeights', () => {
expect(weeklyWeights(undefined, 1)).toEqual([])
})
})
+
+// A weigh-in logged for an earlier day is typed today, so its `t` is not on its day.
+describe('weighInAt', () => {
+ const at = iso => new Date(iso).getTime()
+
+ it('keeps the time a weigh-in was typed on its own day', () => {
+ expect(weighInAt({ d: '2026-09-09', w: 80, t: at('2026-09-09T07:30:00') })).toBe(at('2026-09-09T07:30:00'))
+ })
+
+ it('puts a weigh-in typed on a later day at noon of the day it is for', () => {
+ expect(weighInAt({ d: '2026-03-02', w: 84, t: at('2026-09-09T07:30:00') })).toBe(at('2026-03-02T12:00:00'))
+ })
+
+ it('puts one with no time at noon of its day', () => {
+ expect(weighInAt({ d: '2026-03-02', w: 84 })).toBe(at('2026-03-02T12:00:00'))
+ })
+})
diff --git a/frontend/src/lib/coach-insights.js b/frontend/src/lib/coach-insights.js
index cc57daedf..5c62bc215 100644
--- a/frontend/src/lib/coach-insights.js
+++ b/frontend/src/lib/coach-insights.js
@@ -9,6 +9,7 @@ import { EXIDX } from './exercises.js'
import { workoutVolume, workoutAt } from './history.js'
import { isWarmupRow } from './workout-model.js'
import { bestSetOf } from './onerm.js'
+import { weighInAt } from './bodyweight.js'
const median = arr => {
const a = arr.filter(n => Number.isFinite(n)).sort((x, y) => x - y)
@@ -47,7 +48,7 @@ export function insightsFor(S, win = {}, { topN = 3 } = {}) {
const from = win.from || ws[0]?.d || null
const to = win.to || ws[ws.length - 1]?.d || null
const bw = (S.bodyweight || []).filter(b => b && b.d && (!from || b.d >= from) && (!to || b.d <= to))
- .map(b => ({ t: b.t || new Date(b.d + 'T12:00:00').getTime(), y: b.w, d: b.d }))
+ .map(b => ({ t: weighInAt(b), y: b.w, d: b.d }))
const bodyweight = {
points: bw,
delta: bw.length > 1 ? Math.round((bw[bw.length - 1].y - bw[0].y) * 10) / 10 : null,
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 1be569f95..ee530b182 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -2090,6 +2090,7 @@ export default {
'Enter at least one measurement': 'أدخل قياسًا واحدًا على الأقل',
'Choose a valid date': 'اختر تاريخًا صالحًا',
'That date already has measurements. Edit it instead.': 'هذا التاريخ فيه قياسات بالفعل. عدّلها بدلًا من ذلك.',
+ 'That date already has a weigh-in. Delete it first.': 'هذا التاريخ فيه وزن مسجّل بالفعل. احذفه أولًا.',
'A custom measurement with that name already exists.': 'يوجد قياس مخصص بهذا الاسم بالفعل.',
'Body fat must be between 0 and 100%.': 'يجب أن تكون نسبة الدهون بين 0 و100%.',
'No measurements yet': 'لا توجد قياسات بعد',
diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.js
index 6ad7a0339..b7099fb40 100644
--- a/frontend/src/locales/bn.js
+++ b/frontend/src/locales/bn.js
@@ -2058,6 +2058,7 @@ export default {
'Enter at least one measurement': 'অন্তত একটি মাপ লিখুন',
'Choose a valid date': 'সঠিক তারিখ বেছে নিন',
'That date already has measurements. Edit it instead.': 'এই তারিখে আগেই মাপ আছে। বরং সেটা সম্পাদনা করুন।',
+ 'That date already has a weigh-in. Delete it first.': 'এই তারিখে আগেই ওজন মাপা আছে। আগে সেটা মুছুন।',
'A custom measurement with that name already exists.': 'এই নামে একটি কাস্টম মাপ আগে থেকেই আছে।',
'Body fat must be between 0 and 100%.': 'শরীরের চর্বি ০ থেকে ১০০% এর মধ্যে হতে হবে।',
'No measurements yet': 'এখনো কোনো মাপ নেই',
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 1a9cdb60a..f1d654292 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -2035,6 +2035,7 @@ export default {
'Enter at least one measurement': 'Trage mindestens ein Maß ein',
'Choose a valid date': 'Wähle ein gültiges Datum',
'That date already has measurements. Edit it instead.': 'Für dieses Datum gibt es schon Maße — bearbeite sie stattdessen.',
+ 'That date already has a weigh-in. Delete it first.': 'Für dieses Datum gibt es schon eine Wiegung — lösche sie zuerst.',
'A custom measurement with that name already exists.': 'Ein eigenes Maß mit diesem Namen gibt es schon.',
'Body fat must be between 0 and 100%.': 'Körperfett muss zwischen 0 und 100 % liegen.',
'No measurements yet': 'Noch keine Maße',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 660464b3c..82ee584ab 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -2015,6 +2015,7 @@ export default {
'Enter at least one measurement': 'Introduce al menos una medida',
'Choose a valid date': 'Elige una fecha válida',
'That date already has measurements. Edit it instead.': 'Esa fecha ya tiene medidas — edítalas en su lugar.',
+ 'That date already has a weigh-in. Delete it first.': 'Esa fecha ya tiene un pesaje — elimínalo primero.',
'A custom measurement with that name already exists.': 'Ya existe una medida personalizada con ese nombre.',
'Body fat must be between 0 and 100%.': 'La grasa corporal debe estar entre 0 y 100 %.',
'No measurements yet': 'Aún no hay medidas',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index fb06833e3..6b689f51a 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -2015,6 +2015,7 @@ export default {
'Enter at least one measurement': 'Saisis au moins une mesure',
'Choose a valid date': 'Choisis une date valide',
'That date already has measurements. Edit it instead.': 'Cette date a déjà des mesures — modifie-les plutôt.',
+ 'That date already has a weigh-in. Delete it first.': 'Cette date a déjà une pesée — supprime-la d’abord.',
'A custom measurement with that name already exists.': 'Une mesure personnalisée porte déjà ce nom.',
'Body fat must be between 0 and 100%.': 'La masse grasse doit être entre 0 et 100 %.',
'No measurements yet': 'Pas encore de mesures',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 2de04e8cf..778281f04 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -2015,6 +2015,7 @@ export default {
'Enter at least one measurement': 'कम से कम एक माप दर्ज करें',
'Choose a valid date': 'मान्य तारीख़ चुनें',
'That date already has measurements. Edit it instead.': 'उस तारीख़ के माप पहले से हैं — उन्हीं को संपादित करें।',
+ 'That date already has a weigh-in. Delete it first.': 'उस तारीख़ की वज़न प्रविष्टि पहले से है — पहले उसे हटाएँ।',
'A custom measurement with that name already exists.': 'इस नाम का कस्टम माप पहले से मौजूद है।',
'Body fat must be between 0 and 100%.': 'बॉडी फैट 0 से 100 % के बीच होना चाहिए।',
'No measurements yet': 'अभी कोई माप नहीं',
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 42247c680..f22031cc7 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -2038,6 +2038,7 @@ export default {
'Enter at least one measurement': 'Adj meg legalább egy méretet',
'Choose a valid date': 'Válassz érvényes dátumot',
'That date already has measurements. Edit it instead.': 'Ehhez a naphoz már van méret. Inkább szerkeszd azt.',
+ 'That date already has a weigh-in. Delete it first.': 'Ehhez a naphoz már van mérés. Előbb töröld azt.',
'A custom measurement with that name already exists.': 'Már van ilyen nevű egyéni méret.',
'Body fat must be between 0 and 100%.': 'A testzsír 0 és 100% között lehet.',
'No measurements yet': 'Még nincs méret',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index fe8f5ec5c..5b2bf64e2 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -2015,6 +2015,7 @@ export default {
'Enter at least one measurement': 'Inserisci almeno una misura',
'Choose a valid date': 'Scegli una data valida',
'That date already has measurements. Edit it instead.': 'Quella data ha già delle misure — modifica quelle.',
+ 'That date already has a weigh-in. Delete it first.': 'Quella data ha già una pesata — eliminala prima.',
'A custom measurement with that name already exists.': 'Esiste già una misura personalizzata con questo nome.',
'Body fat must be between 0 and 100%.': 'Il grasso corporeo deve essere tra 0 e 100 %.',
'No measurements yet': 'Ancora nessuna misura',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 651cbf52c..b1f8b4f98 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -2015,6 +2015,7 @@ export default {
'Enter at least one measurement': '측정값을 하나 이상 입력하세요',
'Choose a valid date': '올바른 날짜를 선택하세요',
'That date already has measurements. Edit it instead.': '그 날짜에는 이미 측정값이 있어요 — 기존 기록을 편집하세요.',
+ 'That date already has a weigh-in. Delete it first.': '그 날짜에는 이미 체중 기록이 있어요 — 먼저 삭제하세요.',
'A custom measurement with that name already exists.': '같은 이름의 사용자 항목이 이미 있어요.',
'Body fat must be between 0 and 100%.': '체지방률은 0에서 100 % 사이여야 해요.',
'No measurements yet': '아직 측정값이 없어요',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index b072d2def..0caf6947e 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -2015,6 +2015,7 @@ export default {
'Enter at least one measurement': 'Wpisz co najmniej jeden pomiar',
'Choose a valid date': 'Wybierz prawidłową datę',
'That date already has measurements. Edit it instead.': 'Ta data ma już pomiary — edytuj je zamiast tego.',
+ 'That date already has a weigh-in. Delete it first.': 'Ta data ma już ważenie — najpierw je usuń.',
'A custom measurement with that name already exists.': 'Własny pomiar o tej nazwie już istnieje.',
'Body fat must be between 0 and 100%.': 'Tkanka tłuszczowa musi mieścić się między 0 a 100 %.',
'No measurements yet': 'Brak pomiarów',
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index d822c0263..c545d59fc 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -1025,6 +1025,7 @@ export const PT_BR_OVERRIDES = {
'Clear': 'Limpar',
'QR code': 'QR code',
'Delete weigh-in': 'Excluir pesagem',
+ 'That date already has a weigh-in. Delete it first.': 'Essa data já tem uma pesagem — exclua-a primeiro.',
'Green': 'Verde',
'Blue': 'Azul',
'Orange': 'Laranja',
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index af227d65b..d0fdd22c0 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -2015,6 +2015,7 @@ export default {
'Enter at least one measurement': 'Introduz pelo menos uma medida',
'Choose a valid date': 'Escolhe uma data válida',
'That date already has measurements. Edit it instead.': 'Essa data já tem medidas — edita-as em vez disso.',
+ 'That date already has a weigh-in. Delete it first.': 'Essa data já tem uma pesagem — elimina-a primeiro.',
'A custom measurement with that name already exists.': 'Já existe uma medida personalizada com esse nome.',
'Body fat must be between 0 and 100%.': 'A gordura corporal tem de estar entre 0 e 100 %.',
'No measurements yet': 'Ainda sem medidas',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 870adabb1..dc633413f 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -2019,6 +2019,7 @@ export default {
'Enter at least one measurement': 'Введи хотя бы один замер',
'Choose a valid date': 'Выбери корректную дату',
'That date already has measurements. Edit it instead.': 'На эту дату замеры уже есть — измени их.',
+ 'That date already has a weigh-in. Delete it first.': 'На эту дату взвешивание уже есть — сначала удали его.',
'A custom measurement with that name already exists.': 'Свой замер с таким названием уже есть.',
'Body fat must be between 0 and 100%.': 'Процент жира должен быть от 0 до 100 %.',
'No measurements yet': 'Замеров пока нет',
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index e0ffccc9c..1ac3c1b56 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -2046,6 +2046,7 @@ export default {
'Enter at least one measurement': 'ใส่การวัดอย่างน้อยหนึ่งรายการ',
'Choose a valid date': 'เลือกวันที่ที่ถูกต้อง',
'That date already has measurements. Edit it instead.': 'วันที่นี้มีการวัดอยู่แล้ว แก้ไขอันเดิมแทนนะ',
+ 'That date already has a weigh-in. Delete it first.': 'วันที่นี้มีการชั่งน้ำหนักอยู่แล้ว ลบอันเดิมก่อน',
'A custom measurement with that name already exists.': 'มีการวัดแบบกำหนดเองชื่อนี้อยู่แล้ว',
'Body fat must be between 0 and 100%.': 'ไขมันในร่างกายต้องอยู่ระหว่าง 0 ถึง 100%',
'No measurements yet': 'ยังไม่มีการวัด',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index cfebb52e3..07442300d 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -2015,6 +2015,7 @@ export default {
'Enter at least one measurement': 'En az bir ölçü gir',
'Choose a valid date': 'Geçerli bir tarih seç',
'That date already has measurements. Edit it instead.': 'Bu tarihte zaten ölçü var — onu düzenle.',
+ 'That date already has a weigh-in. Delete it first.': 'Bu tarihte zaten tartı var — önce onu sil.',
'A custom measurement with that name already exists.': 'Bu adda özel bir ölçü zaten var.',
'Body fat must be between 0 and 100%.': 'Vücut yağı %0 ile %100 arasında olmalı.',
'No measurements yet': 'Henüz ölçü yok',
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index 15e561678..0235ea24d 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -2032,6 +2032,7 @@ export default {
'Enter at least one measurement': 'Введіть хоча б один вимір',
'Choose a valid date': 'Оберіть коректну дату',
'That date already has measurements. Edit it instead.': 'На цю дату вже є виміри. Змініть їх.',
+ 'That date already has a weigh-in. Delete it first.': 'На цю дату вже є зважування. Спершу видаліть його.',
'A custom measurement with that name already exists.': 'Власний вимір із такою назвою вже існує.',
'Body fat must be between 0 and 100%.': 'Відсоток жиру має бути від 0 до 100%.',
'No measurements yet': 'Вимірів поки немає',
diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.js
index eaed2d6e5..d31da1b3e 100644
--- a/frontend/src/locales/zh-TW.js
+++ b/frontend/src/locales/zh-TW.js
@@ -2011,6 +2011,7 @@ export default {
'Enter at least one measurement': '請至少輸入一項測量',
'Choose a valid date': '請選擇有效的日期',
'That date already has measurements. Edit it instead.': '這個日期已經有測量紀錄,請改為編輯它。',
+ 'That date already has a weigh-in. Delete it first.': '這個日期已經有體重紀錄,請先刪除它。',
'A custom measurement with that name already exists.': '已經有同名的自訂測量。',
'Body fat must be between 0 and 100%.': '體脂率必須介於 0 到 100% 之間。',
'No measurements yet': '還沒有測量紀錄',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 134fd4544..a568aea36 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -2015,6 +2015,7 @@ export default {
'Enter at least one measurement': '请至少输入一项测量',
'Choose a valid date': '请选择有效日期',
'That date already has measurements. Edit it instead.': '该日期已有测量——请直接编辑。',
+ 'That date already has a weigh-in. Delete it first.': '该日期已有称重记录——请先删除。',
'A custom measurement with that name already exists.': '已有同名的自定义测量项。',
'Body fat must be between 0 and 100%.': '体脂率必须在 0% 到 100% 之间。',
'No measurements yet': '还没有测量',
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index be03e49ef..d080627ff 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -297,14 +297,17 @@ function BwSheet({ required, onDone, close }) {
const unit = st.unit
const bw = lastBW(st)
const [v, setV] = useState(bw ? bw.w : 70)
+ const [date, setDate] = useState(todayISO())
const save = () => {
const n = Math.round((v || 0) * 10) / 10
if (!n || n <= 0) { toast(t('Enter a valid weight')); return }
if (bwTooHeavy(n, unit)) return
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || date > todayISO()) { toast(t('Choose a valid date')); return }
+ // Today's weigh-in is replaced by a second one, as it always was; an earlier day's is not.
+ if (date !== todayISO() && st.bodyweight.some(b => b.d === date)) { toast(t('That date already has a weigh-in. Delete it first.')); return }
update(s => {
- const iso = todayISO()
- const ex = s.bodyweight.find(b => b.d === iso)
- if (ex) { ex.w = n; ex.t = Date.now() } else s.bodyweight.push({ d: iso, w: n, t: Date.now() })
+ const ex = s.bodyweight.find(b => b.d === date)
+ if (ex) { ex.w = n; ex.t = Date.now() } else s.bodyweight.push({ d: date, w: n, t: Date.now() })
s.bodyweight.sort((a, b) => (a.d < b.d ? -1 : 1))
})
close()
@@ -324,7 +327,12 @@ function BwSheet({ required, onDone, close }) {
<button className="iconbtn" aria-label={t('Cancel')} onClick={() => close()}><Icon name="xmark" /></button>
</div>
: <h3>{t('Log body weight')}</h3>}
- <div className="muted small">{required ? t('Slide or tap to set your weight. We ask before every workout so your curve stays honest.') : t('Today') + ', ' + fmtDate(todayISO(), true)}</div>
+ {required
+ ? <div className="muted small">{t('Slide or tap to set your weight. We ask before every workout so your curve stays honest.')}</div>
+ : <label className="measure-date">
+ <span>{t('Date')}</span>
+ <input className="field" type="date" value={date} max={todayISO()} onChange={e => setDate(e.target.value)} />
+ </label>}
<WeightInput value={v} setValue={setV} unit={unit} />
<div style={{ height: 14 }} />
<Button variant="primary" onClick={save}>{required ? t('Save & start workout') : t('Save')}</Button>
diff --git a/frontend/src/sheets.weighin-history.test.jsx b/frontend/src/sheets.weighin-history.test.jsx
index 9005a45ba..6c4b8bf75 100644
--- a/frontend/src/sheets.weighin-history.test.jsx
+++ b/frontend/src/sheets.weighin-history.test.jsx
@@ -119,3 +119,48 @@ describe('weigh-ins sheet', () => {
expect(button(mountTopSheet(), 'All weigh-ins')).toBeUndefined()
})
})
+
+// A weigh-in can be logged for an earlier day, the way measurements can.
+describe('log sheet date', () => {
+ const setDate = (host, value) => act(() => {
+ const el = host.querySelector('input[type="date"]')
+ Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
+ el.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+
+ it('logs a weigh-in for an earlier day, in date order', () => {
+ bwSheet()
+ const log = mountTopSheet()
+ setDate(log, '2026-09-05')
+ act(() => { button(log, 'Save').click() })
+ const bw = useStore.getState().S.bodyweight
+ expect(bw.map(b => b.d)).toEqual(['2026-09-01', '2026-09-03', '2026-09-05', '2026-09-07', '2026-09-09', '2026-09-13'])
+ expect(bw.find(b => b.d === '2026-09-05')).toMatchObject({ w: 79 })
+ expect(useUI.getState().sheets).toHaveLength(0)
+ })
+
+ it('leaves an earlier day that already has a weigh-in as it is', () => {
+ bwSheet()
+ const log = mountTopSheet()
+ setDate(log, '2026-09-03')
+ act(() => { button(log, 'Save').click() })
+ expect(useStore.getState().S.bodyweight).toEqual(LOG)
+ expect(useUI.getState().toastMsg).toBe('That date already has a weigh-in. Delete it first.')
+ expect(useUI.getState().sheets).toHaveLength(1)
+ })
+
+ it('does not take a day after today', () => {
+ const d = new Date(); d.setDate(d.getDate() + 1)
+ bwSheet()
+ const log = mountTopSheet()
+ setDate(log, d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'))
+ act(() => { button(log, 'Save').click() })
+ expect(useStore.getState().S.bodyweight).toEqual(LOG)
+ expect(useUI.getState().toastMsg).toBe('Choose a valid date')
+ })
+
+ it('has no date on the weigh-in before a workout', () => {
+ bwSheet({ required: true })
+ expect(mountTopSheet().querySelector('input[type="date"]')).toBeNull()
+ })
+})
diff --git a/frontend/src/views/Home.jsx b/frontend/src/views/Home.jsx
index 0ffeec0fa..d7713aae2 100644
--- a/frontend/src/views/Home.jsx
+++ b/frontend/src/views/Home.jsx
@@ -15,6 +15,7 @@ import { Button } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { glyphOf } from '../lib/glyphs.js'
import { dayNoteOf } from '../lib/day-notes.js'
+import { weighInAt } from '../lib/bodyweight.js'
// Home = what to do now + a quick glance. Deep charts & history live in Stats.
export default function Home() {
@@ -92,7 +93,7 @@ export default function Home() {
// The streak card's fraction: this calendar week's workouts over the weekdays with a plan, or,
// in a coach week, the queue's sessions and your own days together (lib/queue.js weekTally).
const { done: doneThisWeek, planned: plannedPerWeek } = weekTally(S, todayISO())
- const bwPoints = S.bodyweight.slice(-30).map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))
+ const bwPoints = S.bodyweight.slice(-30).map(b => ({ t: weighInAt(b), y: b.w, d: b.d }))
// today's session shown right under the week strip
const onToday = () => { if (S.active) nav('/workout'); else if (todayRoutines.length) startFlow(effectiveRoutineIds(S, todayISO())); else dayOverrideSheet(todayISO()) }
diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx
index 28fa2910d..664604a74 100644
--- a/frontend/src/views/Stats.jsx
+++ b/frontend/src/views/Stats.jsx
@@ -18,6 +18,7 @@ import { fatigueStateOf } from '../lib/recovery-view.js'
import { e1rmSeries, best1RM, formulaOf } from '../lib/onerm.js'
import { currentDbLoad, workoutAs } from '../lib/dumbbells.js'
import { maxRepsSeries } from '../lib/pyramid.js'
+import { weighInAt } from '../lib/bodyweight.js'
import { perSetSessions, perSetLines, dropOffSet } from '../lib/per-set.js'
import {
hasEffort, hasEstimableEffort, displayScale, scaleName, toScale, avgRir, effortSummary, effortWeeks,
@@ -427,9 +428,9 @@ export default function Stats() {
const kind = displayScale(S)
const hd = scaleName(kind)
- const bwPts = S.bodyweight.filter(b => range === 0 || (b.t || new Date(b.d).getTime()) > now - range * 86400000)
- .map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))
- const bw30 = S.bodyweight.filter(b => (b.t || new Date(b.d).getTime()) > now - 30 * 86400000)
+ const bwPts = S.bodyweight.filter(b => range === 0 || weighInAt(b) > now - range * 86400000)
+ .map(b => ({ t: weighInAt(b), y: b.w, d: b.d }))
+ const bw30 = S.bodyweight.filter(b => weighInAt(b) > now - 30 * 86400000)
const bwDelta30 = bw30.length > 1 ? bw30[bw30.length - 1].w - bw30[0].w : null
const workouts = S.workouts
const monthW = workouts.filter(w => workoutDay(w)?.slice(0, 7) === todayISO().slice(0, 7)).length