Trening: naprawa timera przerwy (start przy kliknieciu, persystencja, sync po wybudzeniu) i kryterium uzupelnienia = powtorzenia

This commit is contained in:
Tilumca
2026-10-14 21:14:23 +02:00
parent c3f937f621
commit 50d4f1d950
2 changed files with 179 additions and 34 deletions

View File

@@ -36,6 +36,42 @@ import {
} from '../components/ui';
import type { SetFieldValues } from '../components/ui';
/* Stan timera przerwy — „until" to bezwzględny znacznik czasu, dzięki czemu
odliczanie jest prawdziwe nawet gdy interwał jest throttlowany (tło karty). */
type RestState = { setId: string; totalSec: number; until: number };
/* Trwały (per karta, per sesja) zapis timera — przetrwa reload i nawigację. */
const restKey = (id: string) => `fitos-rest-${id}`;
function storeRest(id: string, r: RestState | null) {
try {
if (r) sessionStorage.setItem(restKey(id), JSON.stringify(r));
else sessionStorage.removeItem(restKey(id));
} catch {
/* brak sessionStorage (np. tryb prywatny) — timer żyje wtedy tylko w stanie */
}
}
function readStoredRest(id: string): RestState | null {
try {
const raw = sessionStorage.getItem(restKey(id));
if (!raw) return null;
const p = JSON.parse(raw) as { setId?: unknown; totalSec?: unknown; until?: unknown };
if (
typeof p.setId === 'string' &&
typeof p.totalSec === 'number' &&
typeof p.until === 'number' &&
p.totalSec > 0 &&
p.until > Date.now()
) {
return { setId: p.setId, totalSec: p.totalSec, until: p.until };
}
} catch {
/* uszkodzony wpis — traktujemy jak brak timera */
}
return null;
}
/* Karta statusu sesji: badge'y + start + pasek normy + hint „została N seria" + timer przerwy. */
function SessionStatusCard({
session,
@@ -131,7 +167,9 @@ function SetRow({
onDelete: () => void;
}) {
const isExtra = set.planSetId == null;
const done = set.reps != null || set.rir != null || set.difficulty != null;
// Kryterium „uzupełniona" musi być tożsame z serwerowym (completeSession) i normDone:
// liczą się tylko powtórzenia — RIR/trudność bez reps nie domykają serii.
const done = set.reps != null;
const secondary = [
set.rir != null ? `RIR ${set.rir}` : null,
set.difficulty != null ? `Trudność ${set.difficulty}` : null,
@@ -205,7 +243,7 @@ function SetRow({
{set.reps} <Unit>powt.</Unit>
</span>
)}
{done && secondary && <span className="text-dim text-[0.8125rem]">{secondary}</span>}
{secondary && <span className="text-dim text-[0.8125rem]">{secondary}</span>}
{!done && isNext && <span className="text-dim text-[0.8125rem]">seria do wykonania</span>}
{inProgress && (
<div className="flex flex-wrap gap-2 sm:justify-end">
@@ -406,9 +444,10 @@ export default function DayExecution() {
restSec: number | null;
} | null>(null);
// Timer przerwy: startuje automatycznie po zapisaniu uzupełnionej serii,
// która ma zaplanowany czas przerwy (restSec).
const [rest, setRest] = useState<{ setId: string; totalSec: number; until: number } | null>(null);
// Timer przerwy: startuje natychmiast przy zapisie serii po raz pierwszy
// (od kliknięcia, nie od odpowiedzi API), jeśli seria ma zaplanowany restSec.
// Stan utrwalamy w sessionStorage — reload/nawigacja nie zeruje odliczania.
const [rest, setRest] = useState<RestState | null>(null);
const [restNow, setRestNow] = useState(() => Date.now());
useEffect(() => {
@@ -417,15 +456,27 @@ export default function DayExecution() {
return () => clearInterval(id);
}, [rest]);
useEffect(() => {
// interwały w uśpionej karcie są throttlowane — po powrocie pokaż realny stan
const sync = () => setRestNow(Date.now());
document.addEventListener('visibilitychange', sync);
window.addEventListener('focus', sync);
return () => {
document.removeEventListener('visibilitychange', sync);
window.removeEventListener('focus', sync);
};
}, []);
const restRemaining = rest ? Math.max(0, Math.ceil((rest.until - restNow) / 1000)) : 0;
useEffect(() => {
if (rest && restRemaining <= 0) {
setRest(null);
if (sessionId) storeRest(sessionId, null);
playAlarm();
push('Koniec przerwy', 'info');
}
}, [rest, restRemaining, push]);
}, [rest, restRemaining, push, sessionId]);
const { data: sessionData, isLoading: sessionLoading } = useSession(sessionId ?? '');
const session = sessionData?.session;
@@ -469,7 +520,9 @@ export default function DayExecution() {
useEffect(() => {
setEditSet(null);
setRest(null);
// przy zmianie sesji lub ponownym wejściu na stronę odtwórz przerwę, jeśli wciąż trwa
setRest(sessionId ? readStoredRest(sessionId) : null);
setRestNow(Date.now());
}, [sessionId]);
const [dayInfo, setDayInfo] = useState<{
@@ -526,6 +579,7 @@ export default function DayExecution() {
setError('');
try {
await completeSession(session.id);
storeRest(session.id, null);
await queryClient.invalidateQueries({ queryKey: ['sessions'] });
await queryClient.invalidateQueries({ queryKey: ['dashboard'] });
await queryClient.invalidateQueries({ queryKey: ['calendar'] });
@@ -622,6 +676,19 @@ export default function DayExecution() {
if (!session) return;
const num = (v: string) => (v === '' ? null : parseInt(v));
const restSec = editSet?.restSec ?? null;
// Odliczanie startuje natychmiast przy kliknięciu „Zapisz” (nie po odpowiedzi API)
// i tylko przy PIERWSZYM wpisaniu powtórzeń — edycja już uzupełnionej serii go nie
// uruchamia. Kryterium „uzupełniona” = powtórzenia (tożsame z serwerem).
let startedRest = false;
const prevRest = rest;
if (restSec != null && editSetData?.reps == null && values.reps !== '') {
startedRest = true;
const now = Date.now();
setRestNow(now);
setRest({ setId, totalSec: restSec, until: now + restSec * 1000 });
if (sessionId)
storeRest(sessionId, { setId, totalSec: restSec, until: now + restSec * 1000 });
}
try {
await updateSessionSet(setId, {
reps: num(values.reps),
@@ -631,18 +698,12 @@ export default function DayExecution() {
note: values.note.trim() || null,
});
await queryClient.invalidateQueries({ queryKey: ['sessions', session.id] });
// Odliczanie startuje tylko przy PIERWSZYM uzupełnieniu serii (pusta → uzupełniona)
// z zaplanowaną przerwą — edycja już uzupełnionej serii go nie uruchamia.
const wasFilled =
editSetData != null &&
(editSetData.reps != null || editSetData.rir != null || editSetData.difficulty != null);
const nowFilled = values.reps !== '' || values.rir !== '' || values.difficulty !== '';
if (!wasFilled && nowFilled && restSec != null) {
const now = Date.now();
setRestNow(now);
setRest({ setId, totalSec: restSec, until: now + restSec * 1000 });
}
} catch (e) {
if (startedRest) {
// zapis nie wszedł — cofamy optymistyczny start przerwy do stanu sprzed kliknięcia
setRest(prevRest);
if (sessionId) storeRest(sessionId, prevRest);
}
setError(e instanceof Error ? e.message : 'Błąd');
}
};
@@ -712,7 +773,10 @@ export default function DayExecution() {
normPending={normPending}
rest={rest ? { totalSec: rest.totalSec } : null}
restRemaining={restRemaining}
onEndRest={() => setRest(null)}
onEndRest={() => {
setRest(null);
if (sessionId) storeRest(sessionId, null);
}}
/>
{session.exercises
@@ -775,23 +839,15 @@ export default function DayExecution() {
values={editValues}
planned={editSet?.planned ?? { reps: null, rir: null }}
title={
editSet &&
(editValues.reps !== '' || editValues.rir !== '' || editValues.difficulty !== '')
? `Edytuj serię ${editSet.index + 1}`
: undefined
editSet && editValues.reps !== '' ? `Edytuj serię ${editSet.index + 1}` : undefined
}
rest={
rest && restRemaining > 0
? {
remaining: restRemaining,
total: rest.totalSec,
// odliczanie restartuje tylko przy pierwszym uzupełnieniu serii z zaplanowaną przerwą
resetsOnSave:
editSet?.restSec != null &&
(editSetData == null ||
(editSetData.reps == null &&
editSetData.rir == null &&
editSetData.difficulty == null)),
// odliczanie restartuje tylko przy pierwszym wpisaniu powtórzeń w serię
resetsOnSave: editSet?.restSec != null && editSetData?.reps == null,
}
: null
}

View File

@@ -48,7 +48,10 @@ function sessionBody(
status: 'IN_PROGRESS' | 'ABANDONED' = 'IN_PROGRESS',
extra: CatalogExercise[] = [],
notes: Record<string, string | null> = {},
rirOnly: string[] = [],
) {
const has = (id: string) => reps[id] != null;
const secondary = (id: string) => has(id) || rirOnly.includes(id);
return {
session: {
id: 'sess-1',
@@ -82,11 +85,11 @@ function sessionBody(
index: indices['ss-1'] ?? 0,
reps: reps['ss-1'],
// pusta seria nie ma wpisanych rir/trudności (wtedy przycisk to „Uzupełnij serię”, nie „Edytuj”)
rir: reps['ss-1'] != null ? 2 : null,
difficulty: reps['ss-1'] != null ? 3 : null,
rir: secondary('ss-1') ? 2 : null,
difficulty: secondary('ss-1') ? 3 : null,
note: notes['ss-1'] ?? null,
},
{ id: 'ss-2', planSetId: 'ps-2', index: indices['ss-2'] ?? 1, reps: reps['ss-2'], rir: null, difficulty: null, note: notes['ss-2'] ?? null },
{ id: 'ss-2', planSetId: 'ps-2', index: indices['ss-2'] ?? 1, reps: reps['ss-2'], rir: secondary('ss-2') ? 2 : null, difficulty: secondary('ss-2') ? 3 : null, note: notes['ss-2'] ?? null },
],
},
{
@@ -128,6 +131,12 @@ interface MockApiOptions {
nextTraining?: boolean;
/** Katalog ćwiczeń w modalu „Dodaj ćwiczenie”. */
exerciseCatalog?: CatalogExercise[];
/** Serie z zapisanym samym RIR/trudnością (bez powtórzeń). */
rirOnly?: string[];
/** PATCH serii nigdy nie odpowiada (test startu odliczania przed odpowiedzią). */
hangSets?: boolean;
/** PATCH serii odpowiada 500 (test rollbacku optymistycznego timera). */
failSets?: boolean;
}
function mockApi(
@@ -141,6 +150,7 @@ function mockApi(
let daySkipped = opts.daySkipped ?? abandoned;
const { nextTraining = false } = opts;
const catalog = opts.exerciseCatalog ?? CATALOG;
const rirOnly = opts.rirOnly ?? [];
// Stateful: POST /sessions/sess-1/exercises dodaje ćwiczenie do sesji (widoczne po refetchu).
const added: CatalogExercise[] = [];
// Stateful: PATCH /sessions/sets/:id zapisuje komentarz serii (widoczny po refetchu).
@@ -202,9 +212,11 @@ function mockApi(
},
});
if (url.includes('/sessions/sess-1'))
return jsonResponse(200, sessionBody(reps, indices, abandoned ? 'ABANDONED' : 'IN_PROGRESS', added, notes));
return jsonResponse(200, sessionBody(reps, indices, abandoned ? 'ABANDONED' : 'IN_PROGRESS', added, notes, rirOnly));
if (url.includes('/sessions/sets/')) {
if (method === 'PATCH') {
if (opts.hangSets) return new Promise<Response>(() => undefined);
if (opts.failSets) return jsonResponse(500, { error: { code: 'SERVER_ERROR', message: 'awaria serwera' } });
const body = JSON.parse(String(init?.body)) as { note?: string | null };
const setId = url.split('/').pop() ?? '';
notes[setId] = body.note ?? null;
@@ -253,6 +265,8 @@ beforeEach(async () => {
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
// timer przerwy przeżywa remont w sessionStorage — izolujemy testy
sessionStorage.clear();
useAuth.setState({ user: null, ready: false });
});
@@ -573,6 +587,81 @@ describe('Kolejka serii w sesji', () => {
expect(screen.queryByRole('button', { name: 'Zakończ' })).not.toBeInTheDocument();
});
it('serii z samym RIR/trudnością (bez powtórzeń) nie traktuje jako uzupełnionej', async () => {
// kryterium „uzupełniona" musi być tożsame z serwerowym (completeSession liczy reps)
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': null }, {}, { rirOnly: ['ss-1'] });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// ss-1 ma zapisany RIR, ale brak powtórzeń — nadal „Uzupełnij serię”, nie „Edytuj”
expect(screen.queryByRole('button', { name: 'Edytuj' })).not.toBeInTheDocument();
expect(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]).toBeEnabled();
// norma liczona po powtórzeniach — żadna seria normowa nie jest zakończona
expect(await screen.findByText('0%')).toBeInTheDocument();
expect(screen.getByText(/zostały 2 serie/)).toBeInTheDocument();
// zapisany RIR/trudność pozostają widoczne w wierszu mimo braku powtórzeń
expect(screen.getByText('RIR 2 · Trudność 3')).toBeInTheDocument();
});
it('uruchamia odliczanie natychmiast przy kliknięciu „Zapisz”, przed odpowiedzią API', async () => {
// PATCH wisi w nieskończoność — timer nie może czekać na odpowiedź serwera
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': null }, {}, { hangSets: true });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
await user.click(screen.getByRole('button', { name: 'Norma spełniona' }));
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
// odliczanie widoczne mimo nierozstrzygniętego żądania
expect(await screen.findByRole('button', { name: 'Zakończ' })).toBeInTheDocument();
});
it('cofa odliczanie, gdy zapis serii kończy się błędem', async () => {
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': null }, {}, { failSets: true });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
await user.click(screen.getByRole('button', { name: 'Norma spełniona' }));
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByText('awaria serwera')).toBeInTheDocument();
// timer wystartował optymistycznie, ale nieudany zapis musiał go cofnąć
expect(screen.queryByRole('button', { name: 'Zakończ' })).not.toBeInTheDocument();
});
it('odtwarza trwające odliczanie po opuszczeniu i powrocie na stronę dnia', async () => {
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
await user.click(screen.getByRole('button', { name: 'Norma spełniona' }));
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByRole('button', { name: 'Zakończ' })).toBeInTheDocument();
// nawigacja do dashboardu i z powrotem — komponent remountuje, odliczanie zostaje
await user.click(screen.getByRole('link', { name: 'Dashboard', exact: true }));
expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Zakończ' })).not.toBeInTheDocument();
await user.click(screen.getByRole('link', { name: 'Trening', exact: true }));
expect(
await screen.findByRole('heading', { name: 'Poniedziałek · 24.08.2026' }),
).toBeInTheDocument();
expect(await screen.findByRole('button', { name: 'Zakończ' })).toBeInTheDocument();
});
it('numeruje serie sekwencyjnie (pozycja) mimo luk w indeksach po usunięciu', async () => {
// ss-2 ma indeks 2 ( luka po usuniętej serii ), ale powinna być „Seria 2” (pozycja)
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': null }, { 'ss-2': 2 });