Coach: der Weg vom akzeptierten Plan ins Training

Nach dem Annehmen landete man auf /plan — einem Screen, der "heute" gar nicht
kennt und keinen Startknopf hat. Home kennt es laengst: effectiveRoutine fuer
heute, und onToday gibt die Routine an startFlow. Also faehrt der Accept jetzt
dorthin, wenn der Wochenplan uebernommen wurde, und nur sonst noch auf /plan.
Kein zweiter Startpfad, kein neues Sheet.

Was auf Home gefehlt hat: an einem Ruhetag war die Zeile eine Sackgasse. Neu
nennt sie die naechste Einheit — nextTrainingDay() neben effectiveRoutine,
nimmt ein ISO-Datum statt die Uhr zu lesen, ueberspringt Routinen ohne
Uebungen (sonst startet man in eine leere Session) und respektiert dayPlan.

Dabei zwei Fehler gefunden, die genau diesen Weg kaputt gemacht haetten:

- mergePlan schreibt s.week neu, ruehrt s.dayPlan aber nie an. Eine alte
  Verschiebung auf 'rest' versteckte damit eine Einheit, die der neue Plan
  vorsieht, und eine alte Routine-Id gewann gegen die neue Woche. Der Sweep
  sitzt bewusst in applyCreatedPlan, nicht in mergePlan: mergePlan haengt auch
  am Plan-Import, und dem jemandem die Verschiebungen zu loeschen, weil er
  einen fremden Plan importiert, waere eine ganz andere Aenderung — ohne Undo.
- remove-routine raeumte die Woche auf, den dayPlan aber nicht. Der Zeiger
  blieb liegen und der Tag trug dauerhaft das "verschoben"-Abzeichen.

Snapshots tragen dafuer einen Patch der geloeschten Eintraege statt einer
Kopie des ganzen dayPlan — der umfasst jedes je verschobene Datum, und drei
Kopien davon haetten echte Snapshots aus dem 256-KB-Budget gedraengt.

Ausserdem: validateProposal nennt sich Spiegel des Servers, pruefte aber nur,
dass routines nicht leer ist. Der Server lehnt auch eine Routine ohne
Uebungen ab — sonst wird die eingeplant und "heute starten" oeffnet eine
Session ohne Inhalt.
This commit is contained in:
Duarte Santos committed 2026-08-18 23:17:03 +02:00
1 parent 8d3f667c89
commit ad82db415a
19 files changed
+340 -7

No files matched your search

+48 -1
View File
@@ -14,7 +14,7 @@
import { EXIDX } from './exercises.js'
import { modeOf, isBw, isPerSide, cleanupSg } from './history.js'
import { uid } from './format.js'
import { uid, todayISO } from './format.js'
import { mergePlan } from './plan-share.js'
import { POLICIES } from './progression.js'
import { t } from './i18n.js'
@@ -157,6 +157,11 @@ export function validateProposal(p) {
if (!p || typeof p !== 'object') throw new Error(t('That proposal can’t be read.'))
if (p.bundle) {
if (!Array.isArray(p.bundle.routines) || !p.bundle.routines.length) throw new Error(t('That proposal can’t be read.'))
// The server rejects a routine with no exercises; so must this, or an empty one is appended,
// gets scheduled, and "start today's session" opens a workout with nothing in it.
for (const r of p.bundle.routines) {
if (!Array.isArray(r.ex) || !r.ex.length) throw new Error(t('That proposal can’t be read.'))
}
return true
}
if (!Array.isArray(p.changes)) throw new Error(t('That proposal can’t be read.'))
@@ -170,6 +175,36 @@ export function validateProposal(p) {
const clone = o => JSON.parse(JSON.stringify(o))
/**
* Remember the `dayPlan` entries an apply step deleted, on the snapshot that will undo it.
*
* A patch, not a clone: `dayPlan` holds every date the user ever rescheduled, and three copies
* of it in the snapshot ring would crowd real snapshots out of the 256 KB namespace budget that
* `trim()` enforces. The first value recorded for a date wins — that is the pre-apply one.
*/
function recordDayPlanDrops(s, dropped) {
if (!Object.keys(dropped).length) return
const snaps = coachOf(s).snapshots || []
const snap = snaps[snaps.length - 1]
if (!snap) return
snap.dayPlanRestore = { ...dropped, ...(snap.dayPlanRestore || {}) }
}
/**
* Drop per-date reschedules from `iso` onwards.
*
* A created plan replaces the whole week, so overrides made against the old one are no longer
* about anything: `'rest'` would hide a session the new plan schedules, and a routine id wins
* over the new week on that day. Past dates stay — those are history, not intent.
*/
function sweepDayPlan(s, fromIso) {
const dropped = {}
Object.keys(s.dayPlan || {}).forEach(iso => {
if (iso >= fromIso) { dropped[iso] = s.dayPlan[iso]; delete s.dayPlan[iso] }
})
recordDayPlanDrops(s, dropped)
}
/** Snapshot `{routines, week}` before touching either. The unit of revert (FR-30/31). */
export function pushSnapshot(s, proposalId, label) {
const c = coachOf(s)
@@ -193,6 +228,8 @@ export function revertLast(s) {
if (!snap) return false
s.routines = clone(snap.routines)
s.week = clone(snap.week)
// Snapshots taken before this field existed have nothing to put back.
if (snap.dayPlanRestore) Object.assign(s.dayPlan, snap.dayPlanRestore)
appendLog(s, { kind: 'revert', at: Date.now(), proposalId: snap.proposalId, summary: t('Reverted the last Coach changes.') })
return true
}
@@ -238,6 +275,9 @@ export function applyCreatedPlan(s, proposal, { schedule } = {}) {
routines: bundle.routines.map(r => ({ ...r, why: undefined, ex: r.ex.map(e => ({ ...e, why: undefined, name: undefined })) }))
}
const res = mergePlan(s, stripped, { schedule })
// Only when the week actually moved — with the switch off the old schedule still stands, and
// so do the reschedules made against it.
if (schedule) sweepDayPlan(s, todayISO())
appendLog(s, {
kind: 'create', at: Date.now(), proposalId: proposal.id,
summary: proposal.summary || '', routines: res.routines, iteration: proposal.iteration || 1
@@ -352,6 +392,13 @@ const CHANGE_APPLY = {
// A week pointing at a routine that no longer exists reads as a rest day anyway; clearing
// it keeps the plan honest rather than merely harmless.
Object.keys(s.week || {}).forEach(d => { if (s.week[d] === id) delete s.week[d] })
// RoutineEdit does the same on a hand-deleted routine. A pointer left behind here is not
// merely inert: the day still counts as overridden, so it wears a "rescheduled" badge for good.
const dropped = {}
Object.keys(s.dayPlan || {}).forEach(iso => {
if (s.dayPlan[iso] === id) { dropped[iso] = id; delete s.dayPlan[iso] }
})
recordDayPlanDrops(s, dropped)
},
'rename-routine': (s, c) => { need(findRoutine(s, c.target.routineId)).name = c.after },
week: (s, c) => {
+70
View File
@@ -367,6 +367,55 @@ describe('the log', () => {
})
describe('created plans', () => {
// Accepting a plan replaces the whole week, so reschedules aimed at the old one are stale:
// 'rest' would hide a session the new plan schedules, and an id outranks the new week.
describe('per-date reschedules', () => {
const past = '2020-01-02'
const future = '2099-12-31'
const withOverrides = () => JSON.parse(JSON.stringify(state({
dayPlan: { [past]: 'r1', [future]: 'rest' }
})))
it('drops today-and-later overrides when the schedule moves, and keeps past ones', () => {
const s = withOverrides()
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: true })
expect(s.dayPlan[future]).toBeUndefined()
expect(s.dayPlan[past]).toBe('r1') // history, not intent
})
it('leaves them alone when the schedule was not taken', () => {
const s = withOverrides()
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: false })
expect(s.dayPlan[future]).toBe('rest')
expect(s.dayPlan[past]).toBe('r1')
})
it('puts the dropped overrides back on revert', () => {
const s = withOverrides()
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: true })
expect(revertLast(s)).toBe(true)
expect(s.dayPlan[future]).toBe('rest')
expect(s.dayPlan[past]).toBe('r1')
})
it('reverts cleanly for a snapshot taken before the patch existed', () => {
const s = withOverrides()
pushSnapshot(s, 'old', 'legacy')
delete s.coach.snapshots[s.coach.snapshots.length - 1].dayPlanRestore
expect(() => revertLast(s)).not.toThrow()
expect(s.dayPlan[future]).toBe('rest')
})
})
it('refuses a bundle carrying a routine with no exercises', () => {
// The server rejects this; if the client does not, the empty routine gets scheduled and
// starting today's session opens a workout with nothing in it.
const empty = { ...bundle, routines: [{ id: 'x1', name: 'A', ex: [] }] }
const s = JSON.parse(JSON.stringify(state()))
expect(() => applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle: empty }, {})).toThrow()
expect(s.routines).toHaveLength(2)
})
const bundle = {
opengym_plan: 1, name: 'Coach plan', summary: 'three days',
week: { 1: 'x1', 3: 'x2' },
@@ -472,3 +521,24 @@ describe('the gate has something real to read', () => {
expect(coachAvailable(undefined, { id: 'u' })).toBe(false) // the bug, pinned
})
})
describe('removing a routine takes its per-date reschedules with it', () => {
// RoutineEdit does this on a hand-deleted routine. A pointer left behind still counts as an
// override, so the day wears a "rescheduled" badge for good with no way to clear it.
const c = { id: 'c1', type: 'remove-routine', target: { routineId: 'r2' }, before: null, after: null, why: 'unused' }
it('clears dayPlan entries pointing at the removed routine', () => {
const S = state({ dayPlan: { '2099-01-01': 'r2', '2099-01-02': 'r1' } })
const s = apply(S, proposal([c]), ['c1'])
expect(s.dayPlan['2099-01-01']).toBeUndefined()
expect(s.dayPlan['2099-01-02']).toBe('r1') // a different routine is none of its business
expect(s.week[3]).toBeUndefined()
})
it('restores them on revert', () => {
const S = state({ dayPlan: { '2099-01-01': 'r2' } })
const s = apply(S, proposal([c]), ['c1'])
expect(revertLast(s)).toBe(true)
expect(s.dayPlan['2099-01-01']).toBe('r2')
})
})
+19
View File
@@ -249,6 +249,25 @@ export function effectiveRoutine(S, iso) {
const id = effectiveRoutineId(S, iso)
return id ? S.routines.find(r => r.id === id) || null : null
}
/**
* The next day that actually has something to train, looking forward from `iso` (exclusive).
*
* Takes a date string rather than reading the clock so callers and tests agree on "today".
* A routine with no exercises does not count: starting one lands you in an empty session, so
* it is not an answer to "what is next" (the same guard TabBar applies before starting).
* Returns null when the whole week is rest.
*/
export function nextTrainingDay(S, iso) {
for (let i = 1; i <= 7; i++) {
const d = new Date(iso + 'T12:00:00')
d.setDate(d.getDate() + i)
const nextIso = isoOf(d)
const routine = effectiveRoutine(S, nextIso)
if (routine && (routine.ex || []).length) return { iso: nextIso, weekday: d.getDay(), routine }
}
return null
}
export function buildSets(S, cfg, options = {}) {
const last = lastEntryFor(S, cfg.id)
const n = Math.max(1, cfg.sets || 1)
+51 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits } from './history.js'
import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits } from './history.js'
import { EXDB } from './exercises.js'
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
@@ -684,3 +684,53 @@ describe('warm-up rows identified by phase alone', () => {
expect(next[2].w).toBe(100)
})
})
describe('nextTrainingDay', () => {
// 2026-08-18 is a Tuesday; the week map is keyed by getDay(), so 0 is Sunday.
const TUE = '2026-08-18'
const base = (over = {}) => ({
dayPlan: {},
routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001' }] }, { id: 'r2', name: 'B', ex: [{ id: '0002' }] }],
week: {},
...over
})
it('finds the next scheduled day and names its routine', () => {
const S = base({ week: { 4: 'r2' } }) // Thursday
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-20', weekday: 4 })
expect(nextTrainingDay(S, TUE).routine.name).toBe('B')
})
it('looks forward only — today itself is never the answer', () => {
// Only Tuesday is scheduled and today is Tuesday, so the next one is a week out. (The UI
// cannot reach this: a day with a session takes the other branch and never asks.)
const S = base({ week: { 2: 'r1' } })
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-25', weekday: 2 })
})
it('wraps around the end of the week', () => {
const S = base({ week: { 1: 'r1' } }) // Monday, six days on
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-24', weekday: 1 })
})
it('is null when every day is rest', () => {
expect(nextTrainingDay(base(), TUE)).toBeNull()
})
it('skips a day whose routine no longer exists', () => {
const S = base({ week: { 3: 'gone', 5: 'r1' } })
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-21', weekday: 5 })
})
it('skips a routine with no exercises — starting it would open an empty session', () => {
const S = base({ routines: [{ id: 'r1', name: 'A', ex: [] }, { id: 'r2', name: 'B', ex: [{ id: '1' }] }], week: { 3: 'r1', 5: 'r2' } })
expect(nextTrainingDay(S, TUE)).toMatchObject({ weekday: 5 })
})
it('respects a per-date override in both directions', () => {
const moved = base({ week: {}, dayPlan: { '2026-08-19': 'r1' } })
expect(nextTrainingDay(moved, TUE)).toMatchObject({ iso: '2026-08-19' })
const off = base({ week: { 3: 'r1', 5: 'r2' }, dayPlan: { '2026-08-19': 'rest' } })
expect(nextTrainingDay(off, TUE)).toMatchObject({ weekday: 5 })
})
})
+1 -1
View File
@@ -109,7 +109,7 @@ export function parsePlan(raw) {
export function mergePlan(s, bundle, { schedule } = {}) {
s.customEx = s.customEx || []
const exIdMap = {}
bundle.customEx.forEach(c => {
;(bundle.customEx || []).forEach(c => {
const same = s.customEx.find(x => (x.n || '').toLowerCase() === (c.n || '').toLowerCase() && x.bp === c.bp)
if (same) { exIdMap[c.id] = same.id; return }
const nid = uid()
+1
View File
@@ -109,6 +109,7 @@ export default {
'Sick, missed a day or want a different session? Pick what to train instead.': 'Krank, Tag verpasst oder Lust auf was anderes? Wähle, was du stattdessen trainierst.',
'Rest / skip this day': 'Pause / Tag überspringen',
'Rest day': 'Pausentag',
'Next session: {0}, {1}': 'Nächste Einheit: {0}, {1}',
'{0} workout': '{0} Training',
'{0} workouts': '{0} Trainings',
'No workouts this month': 'Keine Trainings in diesem Monat',
+1
View File
@@ -104,6 +104,7 @@ export default {
'Sick, missed a day or want a different session? Pick what to train instead.': '¿Enfermo, te saltaste un día o quieres otra sesión? Elige qué entrenar en su lugar.',
'Rest / skip this day': 'Descansar / saltar este día',
'Rest day': 'Día de descanso',
'Next session: {0}, {1}': 'Próxima sesión: {0}, {1}',
'{0} workout': '{0} entrenamiento',
'{0} workouts': '{0} entrenamientos',
'No workouts this month': 'Sin entrenamientos este mes',
+1
View File
@@ -104,6 +104,7 @@ export default {
'Sick, missed a day or want a different session? Pick what to train instead.': 'Malade, jour manqué ou envie d’autre chose ? Choisis quoi entraîner à la place.',
'Rest / skip this day': 'Repos / sauter ce jour',
'Rest day': 'Jour de repos',
'Next session: {0}, {1}': 'Prochaine séance : {0}, {1}',
'{0} workout': '{0} séance',
'{0} workouts': '{0} séances',
'No workouts this month': 'Aucune séance ce mois-ci',
+1
View File
@@ -104,6 +104,7 @@ export default {
'Sick, missed a day or want a different session? Pick what to train instead.': 'बीमार हैं, दिन छूट गया या कुछ और करना है? चुनें कि इसके बदले क्या ट्रेन करें।',
'Rest / skip this day': 'आराम / यह दिन छोड़ें',
'Rest day': 'आराम का दिन',
'Next session: {0}, {1}': 'अगला सत्र: {0}, {1}',
'{0} workout': '{0} वर्कआउट',
'{0} workouts': '{0} वर्कआउट',
'No workouts this month': 'इस महीने कोई वर्कआउट नहीं',
+1
View File
@@ -104,6 +104,7 @@ export default {
'Sick, missed a day or want a different session? Pick what to train instead.': 'Malato, giorno saltato o voglia di altro? Scegli cosa allenare al suo posto.',
'Rest / skip this day': 'Riposo / salta questo giorno',
'Rest day': 'Giorno di riposo',
'Next session: {0}, {1}': 'Prossima sessione: {0}, {1}',
'{0} workout': '{0} allenamento',
'{0} workouts': '{0} allenamenti',
'No workouts this month': 'Nessun allenamento questo mese',
+1
View File
@@ -104,6 +104,7 @@ export default {
'Sick, missed a day or want a different session? Pick what to train instead.': '아프거나, 하루를 놓쳤거나, 다른 운동이 하고 싶나요? 대신 할 운동을 선택하세요.',
'Rest / skip this day': '휴식 / 이 날 건너뛰기',
'Rest day': '휴식일',
'Next session: {0}, {1}': '다음 세션: {0}, {1}',
'{0} workout': '운동 {0}회',
'{0} workouts': '운동 {0}회',
'No workouts this month': '이번 달 운동 없음',
+1
View File
@@ -104,6 +104,7 @@ export default {
'Sick, missed a day or want a different session? Pick what to train instead.': 'Choroba, opuszczony dzień albo ochota na coś innego? Wybierz, co trenować zamiast tego.',
'Rest / skip this day': 'Odpoczynek / pomiń ten dzień',
'Rest day': 'Dzień odpoczynku',
'Next session: {0}, {1}': 'Następny trening: {0}, {1}',
'{0} workout': '{0} trening',
'{0} workouts': '{0} treningów',
'No workouts this month': 'Brak treningów w tym miesiącu',
+1
View File
@@ -104,6 +104,7 @@ export default {
'Sick, missed a day or want a different session? Pick what to train instead.': 'Doente, falhaste um dia ou queres outra sessão? Escolhe o que treinar em vez disso.',
'Rest / skip this day': 'Descansar / saltar este dia',
'Rest day': 'Dia de descanso',
'Next session: {0}, {1}': 'Próxima sessão: {0}, {1}',
'{0} workout': '{0} treino',
'{0} workouts': '{0} treinos',
'No workouts this month': 'Sem treinos este mês',
+1
View File
@@ -104,6 +104,7 @@ export default {
'Sick, missed a day or want a different session? Pick what to train instead.': 'Заболел, пропустил день или хочешь другую тренировку? Выбери, что делать вместо этого.',
'Rest / skip this day': 'Отдых / пропустить день',
'Rest day': 'День отдыха',
'Next session: {0}, {1}': 'Следующая тренировка: {0}, {1}',
'{0} workout': 'Тренировок: {0}',
'{0} workouts': 'Тренировок: {0}',
'No workouts this month': 'В этом месяце тренировок нет',
+1
View File
@@ -104,6 +104,7 @@ export default {
'Sick, missed a day or want a different session? Pick what to train instead.': 'Hasta mısın, gün mü kaçırdın ya da farklı bir seans mı istiyorsun? Yerine ne çalışacağını seç.',
'Rest / skip this day': 'Dinlen / bu günü atla',
'Rest day': 'Dinlenme günü',
'Next session: {0}, {1}': 'Sonraki antrenman: {0}, {1}',
'{0} workout': '{0} antrenman',
'{0} workouts': '{0} antrenman',
'No workouts this month': 'Bu ay antrenman yok',
+1
View File
@@ -104,6 +104,7 @@ export default {
'Sick, missed a day or want a different session? Pick what to train instead.': '生病、错过一天或想换个训练?选择改练什么。',
'Rest / skip this day': '休息 / 跳过这天',
'Rest day': '休息日',
'Next session: {0}, {1}': '下次训练:{0},{1}',
'{0} workout': '{0} 次训练',
'{0} workouts': '{0} 次训练',
'No workouts this month': '本月没有训练',
+10 -2
View File
@@ -56,7 +56,9 @@ function CreatedPlan({ p, S, update, toast, nav, refresh }) {
update(s => { applyCreatedPlan(s, p, { schedule }) })
resolvePending({ accepted: ['plan'] }).catch(() => {})
toast(t('Your plan is live'))
nav('/plan')
// With the schedule on, the week just moved, so the useful next screen is the one that
// knows what today is and can start it. /plan has no notion of today and no way in.
nav(schedule ? '/home' : '/plan')
} catch (e) { toast(e.message || t('That proposal can’t be read.')) }
}
const discard = () => confirmSheet({
@@ -145,7 +147,13 @@ function ChangeSet({ p, S, update, toast, nav }) {
update(s => { applyChangeSet(s, marked, ids) })
resolvePending({ accepted: ids, rejected: marked.changes.filter(c => !ids.includes(c.id)).map(c => c.id) }).catch(() => {})
toast(t(ids.length === 1 ? '{0} change applied' : '{0} changes applied', ids.length))
nav('/plan')
// Same rule as an accepted plan: go to the screen that knows about today, but only when
// something actually moved the week. Editing sets and reps leaves the schedule alone.
const movedWeek = ids.some(id => {
const c = usable.find(x => x.id === id)
return !!c && (c.type === 'week' || c.type === 'remove-routine')
})
nav(movedWeek ? '/home' : '/plan')
} catch (e) { toast(e.message || t('Could not apply those changes')) }
}
const discard = () => confirmSheet({
+125
View File
@@ -0,0 +1,125 @@
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { parseHTML } from 'linkedom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import CoachProposal from './CoachProposal.jsx'
import { applyCreatedPlan } from '../lib/coach.js'
import { effectiveRoutine } from '../lib/history.js'
import { todayISO } from '../lib/format.js'
// Accepting a plan used to end on /plan, a screen with no notion of today and no way to start
// anything. These tests pin the destination, and — more to the point — that the destination can
// actually start today's session through the app's one start path rather than a second copy.
const mocks = vi.hoisted(() => {
const state = { S: null, pending: null, nav: vi.fn(), toast: vi.fn() }
state.storeSnapshot = () => ({
S: state.S,
user: { id: 'u1' },
config: { coach: { enabled: true } },
update: mut => mut(state.S),
})
state.uiSnapshot = () => ({ toast: state.toast })
return state
})
vi.mock('../store/useStore.js', () => {
const useStore = selector => selector(mocks.storeSnapshot())
useStore.getState = mocks.storeSnapshot
return { useStore }
})
vi.mock('../store/useUI.js', () => {
const useUI = selector => selector ? selector(mocks.uiSnapshot()) : mocks.uiSnapshot()
useUI.getState = mocks.uiSnapshot
return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.nav }))
vi.mock('../lib/coach-api.js', () => ({
useCoachStatus: () => ({ pending: mocks.pending, loading: false, refresh: vi.fn() }),
resolvePending: vi.fn(() => Promise.resolve({})),
refinePlan: vi.fn(() => Promise.resolve({})),
}))
vi.mock('../sheets.jsx', () => ({ startFlow: vi.fn(), confirmSheet: vi.fn() }))
vi.mock('../components/BodyMap.jsx', () => ({ default: () => null }))
vi.mock('../lib/api.js', () => ({
api: vi.fn(() => Promise.resolve({})),
IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics',
}))
let dom, root, container
const TODAY_WD = new Date(todayISO() + 'T12:00:00').getDay()
// A plan that trains every day, so "today" has a session whatever day the suite runs on.
const bundle = (week) => ({
opengym_plan: 1, name: 'Coach plan', summary: 'a plan',
week,
routines: [{ id: 'x1', name: 'Full body A', emoji: '💪', ex: [{ id: '0001', sets: 3, reps: 10, mode: 'reps' }] }],
customEx: [],
})
const everyDay = Object.fromEntries([0, 1, 2, 3, 4, 5, 6].map(d => [d, 'x1']))
const state = () => ({
unit: 'kg', lang: 'en', customEx: [], workouts: [], bodyweight: [], exWeights: {},
dayPlan: {}, routines: [], week: {},
coach: { consent: { agreedAt: '2026-07-01T00:00:00Z', version: 1 }, log: [], snapshots: [] },
})
function installDom() {
const parsed = parseHTML('<!doctype html><html><body><div id="root"></div></body></html>')
dom = parsed.window
globalThis.window = dom
globalThis.document = dom.document
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
for (const key of ['HTMLElement', 'Node', 'Element', 'Event', 'Blob']) globalThis[key] = dom[key]
globalThis.IS_REACT_ACT_ENVIRONMENT = true
container = document.getElementById('root')
root = createRoot(container)
}
async function mount(pending) {
mocks.S = state()
mocks.pending = pending
installDom()
await act(async () => { root.render(React.createElement(CoachProposal)) })
}
const byText = re => [...container.querySelectorAll('button')].find(b => re.test(b.textContent || ''))
async function click(el) {
expect(el).toBeTruthy()
await act(async () => { el.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
beforeEach(() => { vi.clearAllMocks() })
afterEach(async () => {
if (root) { await act(async () => { root.unmount() }); root = null }
container = null; dom = null
})
describe('accepting a created plan hands off to training', () => {
it('lands on the screen that knows about today when it took the schedule', async () => {
await mount({ id: 'p1', kind: 'create', bundle: bundle(everyDay) })
await click(byText(/Accept plan/))
expect(mocks.nav).toHaveBeenCalledWith('/home')
})
it('leaves the user on the plan screen when the schedule was declined', async () => {
await mount({ id: 'p1', kind: 'create', bundle: bundle(everyDay) })
const sw = container.querySelector('[role="switch"]')
expect(sw.getAttribute('aria-checked')).toBe('true') // on by default
await click(sw)
await click(byText(/Accept plan/))
expect(mocks.nav).toHaveBeenCalledWith('/plan')
})
it('leaves today startable through the app’s one start path', async () => {
// What the destination can actually do: the same lookup Home does on render resolves a
// routine with exercises, which is exactly what it hands to startFlow.
const s = state()
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle: bundle(everyDay) }, { schedule: true })
const todays = effectiveRoutine(s, todayISO())
expect(todays).toBeTruthy()
expect(todays.ex.length).toBeGreaterThan(0)
expect(s.week[TODAY_WD]).toBe(todays.id)
})
})
+5 -2
View File
@@ -1,8 +1,8 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { effectiveRoutine, effectiveRoutineId, streakWeeks, lastBW, setsDoneActive } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, isoOf, weekKey, DAYS } from '../lib/format.js'
import { effectiveRoutine, effectiveRoutineId, nextTrainingDay, streakWeeks, lastBW, setsDoneActive } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, isoOf, weekKey, DAYS, DAYN } from '../lib/format.js'
import { t, dateLocale } from '../lib/i18n.js'
import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, loadStarterPlan, bwDeltaColor } from '../sheets.jsx'
import LineChart from '../components/LineChart.jsx'
@@ -20,6 +20,8 @@ export default function Home() {
const today = new Date()
const routine = effectiveRoutine(S, todayISO())
const todayOvr = S.dayPlan[todayISO()] !== undefined
// On a rest day, saying when you train next beats leaving the row as a full stop.
const next = !S.active && !routine ? nextTrainingDay(S, todayISO()) : null
const bw = lastBW(S)
const prevBW = S.bodyweight.length > 1 ? S.bodyweight[S.bodyweight.length - 2] : null
const delta = bw && prevBW ? bw.w - prevBW.w : null
@@ -66,6 +68,7 @@ export default function Home() {
<div style={{ minWidth: 0 }}>
<div className="lbl2">{t('Today')}</div>
<div className="ttl">{S.active ? t('{0} — in progress', S.active.name) : routine ? routine.name : t('Rest day')}{todayOvr && routine ? ' · ' + t('rescheduled') : ''}</div>
{next && <div className="ss">{t('Next session: {0}, {1}', t(DAYN[next.weekday]), next.routine.name)}</div>}
</div>
</div>
{S.active ? <span className="tag" style={{ color: 'var(--orange)', background: 'color-mix(in srgb,var(--orange) 16%,transparent)' }}>{t('Resume')}</span>