diff --git a/frontend/src/lib/coach.js b/frontend/src/lib/coach.js index e09d2b2..b2db4ed 100644 --- a/frontend/src/lib/coach.js +++ b/frontend/src/lib/coach.js @@ -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) => { diff --git a/frontend/src/lib/coach.test.js b/frontend/src/lib/coach.test.js index efe501e..8f47ed1 100644 --- a/frontend/src/lib/coach.test.js +++ b/frontend/src/lib/coach.test.js @@ -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') + }) +}) diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js index 9c440ae..6fe01f7 100644 --- a/frontend/src/lib/history.js +++ b/frontend/src/lib/history.js @@ -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) diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.js index 352972e..c04a1f3 100644 --- a/frontend/src/lib/history.test.js +++ b/frontend/src/lib/history.test.js @@ -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 }) + }) +}) diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.js index 7e41d1d..0b6cca7 100644 --- a/frontend/src/lib/plan-share.js +++ b/frontend/src/lib/plan-share.js @@ -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() diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index f963a26..28d483e 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -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', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index a1ea2c3..983cfdb 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -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', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index b06f4d7..615172e 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -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', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 91a19d6..07fcb77 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -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': 'इस महीने कोई वर्कआउट नहीं', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 6aea7ea..350f2fa 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -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', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 90571fd..7d700c5 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -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': '이번 달 운동 없음', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 9737069..c86f47a 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -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', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 5384689..da1e7c3 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -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', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index 318af44..e81f444 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -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': 'В этом месяце тренировок нет', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index e2cbb98..62f62d3 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -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', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index e6fcb59..2eba7dc 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -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': '本月没有训练', diff --git a/frontend/src/views/CoachProposal.jsx b/frontend/src/views/CoachProposal.jsx index 8794e19..f7d0cdf 100644 --- a/frontend/src/views/CoachProposal.jsx +++ b/frontend/src/views/CoachProposal.jsx @@ -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({ diff --git a/frontend/src/views/CoachProposal.test.jsx b/frontend/src/views/CoachProposal.test.jsx new file mode 100644 index 0000000..fe02eb0 --- /dev/null +++ b/frontend/src/views/CoachProposal.test.jsx @@ -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('
') + 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) + }) +}) diff --git a/frontend/src/views/Home.jsx b/frontend/src/views/Home.jsx index 1a751f8..34b9b27 100644 --- a/frontend/src/views/Home.jsx +++ b/frontend/src/views/Home.jsx @@ -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() {