Plany: kopiowanie dni w edytorze + ochrona historii — 'Kopiuj dzien z…' podmienia biezacy dzien treścią dnia z dowolnego tygodnia lub dnia tygodnia (kopia bez id, tydzien odlaczany), 'Kopiuj z…' dla calego tygodnia, badge/kladka historii w siatce dni i ConfirmDialog + forceRemoveDays przy podmianie dni z historia; normalizacja obciazenia z przecinkiem (parseLoadInput) (app unit 270, e2e plans 7 przechodza)
This commit is contained in:
@@ -656,6 +656,12 @@ export interface PlanBody {
|
||||
startDate?: string;
|
||||
/** Edycja planu ACTIVE: wymagana notatka audytowa, gdy coś faktycznie się zmienia. */
|
||||
changeNote?: string;
|
||||
/**
|
||||
* Edycja planu ACTIVE: świadoma zgoda na usunięcie dnia z historią treningową.
|
||||
* Backend soft-remuje taki dzień (removedAt) — historia sesji/serii zostaje,
|
||||
* dzień znika z planu, kalendarza i statystyk.
|
||||
*/
|
||||
forceRemoveDays?: boolean;
|
||||
}
|
||||
|
||||
export function createPlan(body: PlanBody) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ChevronDown, ChevronUp, MessageSquare, MessageSquarePlus, Trash2 } from 'lucide-react';
|
||||
import type { HistorySession } from '../api/types';
|
||||
import { fmtDate, fmtDuration, fmtVolume } from '../lib/format';
|
||||
import { fmtDate, fmtDuration, fmtLoadKg, fmtVolume } from '../lib/format';
|
||||
import { localizedName } from '../lib/localizedName';
|
||||
import { muscleName, SESSION_STATUS } from '../lib/labels';
|
||||
import { Badge, Button, Textarea } from './ui';
|
||||
@@ -182,7 +182,7 @@ export default function HistoryTable({
|
||||
{t('history.planPrefix')}
|
||||
{set.planned.reps ?? '—'}
|
||||
{set.planned.loadKg != null
|
||||
? `/${set.planned.loadKg} kg`
|
||||
? `/${fmtLoadKg(set.planned.loadKg)} kg`
|
||||
: ''}
|
||||
{set.planned.restSec != null
|
||||
? `/${set.planned.restSec} s`
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Dumbbell } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { MessageAttachment } from '../api/types';
|
||||
import { fmtDate } from '../lib/format';
|
||||
import { fmtDate, fmtLoadKg } from '../lib/format';
|
||||
import { localizedName } from '../lib/localizedName';
|
||||
|
||||
/**
|
||||
@@ -44,7 +44,9 @@ export default function MessageAttachmentCard({
|
||||
{s.reps ?? '—'} {t('plans:exec.repsUnit')}
|
||||
</span>
|
||||
<span>RIR {s.rir ?? '—'}</span>
|
||||
{s.planned?.loadKg != null && <span className="text-dim">{s.planned.loadKg} kg</span>}
|
||||
{s.planned?.loadKg != null && (
|
||||
<span className="text-dim">{fmtLoadKg(s.planned.loadKg)} kg</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Play } from 'lucide-react';
|
||||
import { fmtDate } from '../../lib/format';
|
||||
import { localizedName } from '../../lib/localizedName';
|
||||
import { DAY_STATUS } from '../../lib/labels';
|
||||
import { dayName } from '../../lib/format';
|
||||
import { dayName, fmtLoadKg } from '../../lib/format';
|
||||
import { Badge, Card, H2 } from '../ui';
|
||||
import { buttonVariants } from '../ui/button';
|
||||
import { cn } from '../../lib/utils';
|
||||
@@ -74,7 +74,7 @@ export function PlanDayRow({
|
||||
{ex.sets
|
||||
.map(
|
||||
(s) =>
|
||||
`${s.reps ?? '?'} ${i18n.t('plans:exec.repsUnit')}${s.loadKg ? ` @ ${s.loadKg}kg` : ''}`,
|
||||
`${s.reps ?? '?'} ${i18n.t('plans:exec.repsUnit')}${s.loadKg ? ` @ ${fmtLoadKg(s.loadKg)}kg` : ''}`,
|
||||
)
|
||||
.join(', ')}
|
||||
</span>
|
||||
|
||||
@@ -68,7 +68,8 @@
|
||||
"resultsTitle": "Trainee results",
|
||||
"insertBtn": "Insert results",
|
||||
"lastSession": "Last session:",
|
||||
"dayPickerAria": "Training days"
|
||||
"dayPickerAria": "Training days",
|
||||
"dayHistoryAria": "day with training history"
|
||||
},
|
||||
"meta": {
|
||||
"title": "Title",
|
||||
@@ -152,7 +153,28 @@
|
||||
"clearWeekLabel": "Clear",
|
||||
"removeDayTitle": "Remove day?",
|
||||
"removeDayDesc": "Remove {{day}} and its {{exercises}}?",
|
||||
"removeDayLabel": "Remove day"
|
||||
"removeDayLabel": "Remove day",
|
||||
"historyBadge": "History",
|
||||
"removeLockedTitle": "Remove a day with history?",
|
||||
"removeLockedDesc": "{{day}} has training history (sessions or a settled status). The day will disappear from the plan, calendar and stats, but the training history will be kept. The change is recorded in the plan history along with your note.",
|
||||
"removeLockedLabel": "Remove despite history",
|
||||
"copyWeekLockedTitle": "Replace days that have history?",
|
||||
"copyWeekLockedDesc": "This week contains days with training history. Replacing its days will remove them from the plan — the training history will be kept.",
|
||||
"copyWeekLockedLabel": "Replace days",
|
||||
"copyDayFrom": "Copy day from…",
|
||||
"dayCopyTitle": "Copy {{day}} from…",
|
||||
"dayCopyDesc": "Pick a day to copy from — the current day takes over its exercises and sets, and the week becomes standalone.",
|
||||
"dayCopyLabel": "Copy: {{label}}",
|
||||
"dayCopyLockedTitle": "Replace the day that has history?",
|
||||
"dayCopyLockedDesc": "{{day}} has training history. Replacing it will remove the day from the plan — the training history will be kept.",
|
||||
"dayCopyLockedLabel": "Replace day",
|
||||
"shrinkWeeksLockedTitle": "Shorten the plan over weeks with history?",
|
||||
"shrinkWeeksLockedDesc": "The weeks being removed contain days with training history. They will disappear from the plan and calendar — the training history will be kept.",
|
||||
"shrinkWeeksLockedLabel": "Shorten plan",
|
||||
"clearWeekHistoryNote": "This week contains {{count}} day(s) with training history. They will be removed from the plan — the training history will be kept.",
|
||||
"clearWeekHistoryNote_one": "This week contains {{count}} day with training history. It will be removed from the plan — the training history will be kept.",
|
||||
"clearWeekHistoryNote_other": "This week contains {{count}} days with training history. They will be removed from the plan — the training history will be kept.",
|
||||
"historyGuardError": "Week {{week}}, {{day}} has training history — it was not removed. To remove it, use “Remove despite history”."
|
||||
},
|
||||
"week": {
|
||||
"title": "Week {{n}}",
|
||||
|
||||
@@ -68,7 +68,8 @@
|
||||
"resultsTitle": "Wyniki podopiecznego",
|
||||
"insertBtn": "Wstaw wyniki",
|
||||
"lastSession": "Ostatnia sesja:",
|
||||
"dayPickerAria": "Dni treningowe"
|
||||
"dayPickerAria": "Dni treningowe",
|
||||
"dayHistoryAria": "dzień z historią treningów"
|
||||
},
|
||||
"meta": {
|
||||
"title": "Tytuł",
|
||||
@@ -152,7 +153,29 @@
|
||||
"clearWeekLabel": "Wyczyść",
|
||||
"removeDayTitle": "Usunąć dzień?",
|
||||
"removeDayDesc": "Usunąć {{day}} i jego {{exercises}}?",
|
||||
"removeDayLabel": "Usuń dzień"
|
||||
"removeDayLabel": "Usuń dzień",
|
||||
"historyBadge": "Historia",
|
||||
"removeLockedTitle": "Usunąć dzień z historią?",
|
||||
"removeLockedDesc": "{{day}} ma historię treningów (sesje lub rozliczony status). Dzień zniknie z planu, kalendarza i statystyk, ale historia treningowa zostanie zachowana. Zmiana trafi do historii planu razem z notatką.",
|
||||
"removeLockedLabel": "Usuń mimo historii",
|
||||
"copyWeekLockedTitle": "Podmienić dni z historią?",
|
||||
"copyWeekLockedDesc": "Ten tydzień zawiera dni z historią treningów. Podmiana usunie je z planu — historia treningowa zostanie zachowana.",
|
||||
"copyWeekLockedLabel": "Podmień dni",
|
||||
"copyDayFrom": "Kopiuj dzień z…",
|
||||
"dayCopyTitle": "Kopiuj {{day}} z…",
|
||||
"dayCopyDesc": "Wybierz dzień do skopiowania — bieżący dzień przejmie jego ćwiczenia i serie, a tydzień stanie się samodzielny.",
|
||||
"dayCopyLabel": "Kopiuj: {{label}}",
|
||||
"dayCopyLockedTitle": "Podmienić dzień z historią?",
|
||||
"dayCopyLockedDesc": "{{day}} ma historię treningów. Podmiana usunie ten dzień z planu — historia treningowa zostanie zachowana.",
|
||||
"dayCopyLockedLabel": "Podmień dzień",
|
||||
"shrinkWeeksLockedTitle": "Skrócić plan z tygodniami z historią?",
|
||||
"shrinkWeeksLockedDesc": "Usuwane tygodnie zawierają dni z historią treningów. Znikną z planu i kalendarza — historia treningowa zostanie zachowana.",
|
||||
"shrinkWeeksLockedLabel": "Skróć plan",
|
||||
"clearWeekHistoryNote": "Ten tydzień zawiera {{count}} dni z historią treningów. Znikną z planu — historia treningowa zostanie zachowana.",
|
||||
"clearWeekHistoryNote_one": "Ten tydzień zawiera {{count}} dzień z historią treningów. Zniknie z planu — historia treningowa zostanie zachowana.",
|
||||
"clearWeekHistoryNote_few": "Ten tydzień zawiera {{count}} dni z historią treningów. Znikną z planu — historia treningowa zostanie zachowana.",
|
||||
"clearWeekHistoryNote_many": "Ten tydzień zawiera {{count}} dni z historią treningów. Znikną z planu — historia treningowa zostanie zachowana.",
|
||||
"historyGuardError": "Tydzień {{week}}, dzień {{day}} ma historię treningów — nie został usunięty. Aby go usunąć, użyj „Usuń mimo historii”."
|
||||
},
|
||||
"week": {
|
||||
"title": "Tydzień {{n}}",
|
||||
|
||||
@@ -113,6 +113,48 @@ export function fmtVolume(kg: number): string {
|
||||
return `${Math.round(kg).toLocaleString(currentTag())} kg`;
|
||||
}
|
||||
|
||||
/** Obciążenie w kg do wyświetlania: 62.5 → „62,5” (Intl, max 2 miejsca po przecinku). */
|
||||
export function fmtLoadKg(kg: number): string {
|
||||
return kg.toLocaleString(currentTag(), { maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizer wpisu obciążenia (stan edytora): cyfry + co najwyżej jeden separator
|
||||
* przecinkowy z max 2 miejscami po przecinku; kropka normalizowana do przecinka,
|
||||
* wartość ograniczona do limitu API (1000 kg). Zawsze zwraca string przechodzący
|
||||
* LOAD_INPUT_RE albo ''.
|
||||
*/
|
||||
export function sanitizeLoadInput(raw: string): string {
|
||||
let v = raw.replace(/[^\d.,]/g, '').replace(/\./g, ',');
|
||||
const sep = v.indexOf(',');
|
||||
if (sep !== -1) v = v.slice(0, sep + 1) + v.slice(sep + 1).replace(/,/g, '');
|
||||
const [rawInt = '', rawDec = ''] = v.split(',');
|
||||
let int = rawInt.replace(/^0+(?=\d)/, '');
|
||||
let dec = rawDec;
|
||||
if (Number(int) >= 1000) {
|
||||
int = '1000';
|
||||
dec = '';
|
||||
}
|
||||
dec = dec.slice(0, 2);
|
||||
if (int === '' && dec === '') return '';
|
||||
if (int === '') int = '0';
|
||||
return dec === '' ? int : `${int},${dec}`;
|
||||
}
|
||||
|
||||
/** Dopuszczalna forma wpisu obciążenia: całkowita lub z przecinkiem (max 2 miejsca). */
|
||||
const LOAD_INPUT_RE = /^\d{1,4}(?:[.,]\d{1,2})?$/;
|
||||
|
||||
/**
|
||||
* Parsowanie wartości obciążenia po sanityzacji (separator ',' lub '.') do number;
|
||||
* nieprawidłowa/pusta lub 0 (brak obciążenia) → null — nigdy NaN.
|
||||
*/
|
||||
export function parseLoadInput(v: string): number | null {
|
||||
const s = v.trim();
|
||||
if (!LOAD_INPUT_RE.test(s)) return null;
|
||||
const n = Number(s.replace(',', '.'));
|
||||
return Number.isFinite(n) && n > 0 ? n : null;
|
||||
}
|
||||
|
||||
/** Czas trwania sesji: „45 min”, „1 h 30 min”. */
|
||||
export function fmtDuration(startIso: string, endIso: string): string {
|
||||
const min = Math.round((new Date(endIso).getTime() - new Date(startIso).getTime()) / 60000);
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
useSession,
|
||||
updateSessionSet,
|
||||
} from '../api/queries';
|
||||
import { fmtDate, dayName, setsPlural } from '../lib/format';
|
||||
import { fmtDate, fmtLoadKg, dayName, setsPlural } from '../lib/format';
|
||||
import { localizedName } from '../lib/localizedName';
|
||||
import { SESSION_STATUS, muscleName } from '../lib/labels';
|
||||
import type { Exercise, PlanSet, Session, SessionExercise, SessionSet } from '../api/types';
|
||||
@@ -231,7 +231,7 @@ function SetRow({
|
||||
<span key="norm" className="font-semibold tabular-nums">
|
||||
{planned.loadKg != null && (
|
||||
<>
|
||||
{planned.loadKg} <Unit>kg</Unit>
|
||||
{fmtLoadKg(planned.loadKg)} <Unit>kg</Unit>
|
||||
</>
|
||||
)}
|
||||
{planned.loadKg != null && planned.reps != null ? ' × ' : ''}
|
||||
|
||||
@@ -15,7 +15,8 @@ import {
|
||||
useExercises,
|
||||
type PlanBody,
|
||||
} from '../../api/queries';
|
||||
import { CalendarX, Check, ChevronLeft, ChevronRight, Unlink } from 'lucide-react';
|
||||
import { CalendarX, Check, ChevronLeft, ChevronRight, Copy, History, Unlink } from 'lucide-react';
|
||||
import { ApiError } from '../../api/client';
|
||||
import {
|
||||
BackButton,
|
||||
Badge,
|
||||
@@ -24,6 +25,7 @@ import {
|
||||
EmptyState,
|
||||
H3,
|
||||
isPastWeek,
|
||||
Modal,
|
||||
Skeleton,
|
||||
Tabs,
|
||||
type BadgeColor,
|
||||
@@ -32,7 +34,7 @@ import { useToast } from '../../components/toast';
|
||||
import { cn } from '../../lib/utils';
|
||||
import { localizedName } from '../../lib/localizedName';
|
||||
import { exerciseAvailableAtGym } from '../../lib/equipment';
|
||||
import { dayName } from '../../lib/format';
|
||||
import { dayName, parseLoadInput } from '../../lib/format';
|
||||
import { dayCountLabel, exerciseCountLabel } from '../../lib/labels';
|
||||
import { useTopbar } from '../../topbar';
|
||||
import { displayedDaysOf, type EditorDay, type EditorWeek } from './plan-editor/types';
|
||||
@@ -172,6 +174,7 @@ export default function PlanEditor() {
|
||||
setStep(n);
|
||||
return;
|
||||
}
|
||||
setDayCopyOpen(false);
|
||||
if (n === 2 && step1Valid) setStep(2);
|
||||
if (n === 3 && step1Valid) setStep(3);
|
||||
};
|
||||
@@ -235,6 +238,18 @@ export default function PlanEditor() {
|
||||
const [confirmExit, setConfirmExit] = useState(false);
|
||||
const [clearWeekIdx, setClearWeekIdx] = useState<number | null>(null);
|
||||
const [removeDayReq, setRemoveDayReq] = useState<{ wi: number; dow: number } | null>(null);
|
||||
// Usunięcie dnia z historią (aktywny plan): osobne potwierdzenie + forceRemoveDays w payloadzie.
|
||||
const [removeLockedReq, setRemoveLockedReq] = useState<{ wi: number; dow: number } | null>(null);
|
||||
const [copyWeekReq, setCopyWeekReq] = useState<{ srcWi: number } | null>(null);
|
||||
// „Kopiuj dzień z…”: wybór dnia-źródła (modal) + podmiana dnia z historią (potwierdzenie)
|
||||
const [dayCopyOpen, setDayCopyOpen] = useState(false);
|
||||
const [dayCopyReq, setDayCopyReq] = useState<{
|
||||
targetDow: number;
|
||||
srcWi: number;
|
||||
srcDow: number;
|
||||
} | null>(null);
|
||||
const [shrinkReq, setShrinkReq] = useState<{ n: number } | null>(null);
|
||||
const [forceRemoveDays, setForceRemoveDays] = useState(false);
|
||||
const [titleTouched, setTitleTouched] = useState(false);
|
||||
// Notatka audytowa (edycja planu ACTIVE) — wymagana, gdy coś zmieniamy
|
||||
const [changeNote, setChangeNoteState] = useState('');
|
||||
@@ -294,6 +309,11 @@ export default function PlanEditor() {
|
||||
return { text: dayCountLabel(days.length), color: 'green' };
|
||||
};
|
||||
|
||||
// Dni z historią treningową w wyświetlanej treści tygodnia: w aktywnym planie
|
||||
// ich usunięcie to soft-remove (historia zostaje) — wymaga świadomego potwierdzenia.
|
||||
const historyDaysOf = (wi: number) =>
|
||||
displayedDaysOf(editor.weeks, wi).filter((d) => d.hasHistory);
|
||||
|
||||
// Kropka statusu na zakładce tygodnia (kolory spójne z badge)
|
||||
const DOT_COLORS: Record<BadgeColor, string> = {
|
||||
green: 'bg-accent',
|
||||
@@ -354,7 +374,7 @@ export default function PlanEditor() {
|
||||
...(keepIds && s.id ? { id: s.id } : {}),
|
||||
index: si,
|
||||
reps: s.reps ? parseInt(s.reps) : null,
|
||||
loadKg: s.loadKg ? parseFloat(s.loadKg) : null,
|
||||
loadKg: parseLoadInput(s.loadKg),
|
||||
restSec: s.restSec ? parseInt(s.restSec) : null,
|
||||
rir: s.rir !== '' ? parseInt(s.rir) : null,
|
||||
})),
|
||||
@@ -364,6 +384,9 @@ export default function PlanEditor() {
|
||||
}),
|
||||
};
|
||||
if (noteRequired) body.changeNote = changeNote.trim();
|
||||
// Dzień z historią usunięty za potwierdzeniem „Usuń mimo historii” — backend
|
||||
// soft-remuje go (removedAt), historia sesji/serii zostaje w bazie.
|
||||
if (isPlanActive && forceRemoveDays) body.forceRemoveDays = true;
|
||||
// Data startu w obu trybach — przy tworzeniu: plan tworzony i aktywowany w jednym
|
||||
// kroku; przy edycji (DRAFT): zapis = aktualizacja struktury + aktywacja.
|
||||
// Tydzień startu: bieżący lub przyszły (WeekPicker blokuje minione; guard zapasowy).
|
||||
@@ -410,7 +433,22 @@ export default function PlanEditor() {
|
||||
}
|
||||
navigate(targetPath);
|
||||
} catch (err) {
|
||||
push(err instanceof Error ? err.message : t('wizard.saveError'), 'error');
|
||||
if (err instanceof ApiError && err.code === 'PLAN_DAY_HAS_HISTORY') {
|
||||
// Zapasowy guard (np. dzień z historią usunięty mimochodem): skocz do wskazanego dnia.
|
||||
const d = (err.body?.error?.details ?? {}) as { weekIndex?: number; dayOfWeek?: number };
|
||||
push(
|
||||
t('wizard.historyGuardError', {
|
||||
week: (d.weekIndex ?? 0) + 1,
|
||||
day: d.dayOfWeek != null ? dayName(d.dayOfWeek).toLowerCase() : '',
|
||||
}),
|
||||
'error',
|
||||
);
|
||||
setStep(2);
|
||||
if (d.weekIndex != null) setActiveWeek(d.weekIndex);
|
||||
if (d.dayOfWeek != null) setActiveDow(d.dayOfWeek);
|
||||
} else {
|
||||
push(err instanceof Error ? err.message : t('wizard.saveError'), 'error');
|
||||
}
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -481,6 +519,36 @@ export default function PlanEditor() {
|
||||
},
|
||||
];
|
||||
});
|
||||
// Źródła „Kopiuj dzień z…” — każdy dzień z ćwiczeniami poza edytowanym (ten tydzień:
|
||||
// inne dni tygodnia; inne tygodnie: dowolny dzień, lustrzane źródła rozwiązane)
|
||||
const dayCopySources = editor.weeks.flatMap((w, wi) =>
|
||||
displayedDaysOf(editor.weeks, wi)
|
||||
.filter((d) => d.exercises.length > 0 && !(wi === activeWi && d.dayOfWeek === effDow))
|
||||
.map((d) => {
|
||||
const alias = w.customName.trim();
|
||||
return {
|
||||
wi,
|
||||
dow: d.dayOfWeek,
|
||||
label:
|
||||
wi === activeWi
|
||||
? dayName(d.dayOfWeek)
|
||||
: alias
|
||||
? `${alias} — ${dayName(d.dayOfWeek)}`
|
||||
: `${t('week.title', { n: wi + 1 })} — ${dayName(d.dayOfWeek)}`,
|
||||
summary: exerciseCountLabel(d.exercises.length),
|
||||
};
|
||||
}),
|
||||
);
|
||||
// Podmiana edytowanego dnia (aktywny plan) gdy ma historię — potwierdzenie + forceRemoveDays
|
||||
const applyDayCopy = (srcWi: number, srcDow: number) => {
|
||||
if (effDow == null) return;
|
||||
const targetDay = weekDays.find((d) => d.dayOfWeek === effDow);
|
||||
if (isPlanActive && targetDay?.hasHistory) {
|
||||
setDayCopyReq({ targetDow: effDow, srcWi, srcDow });
|
||||
} else {
|
||||
editor.copyDayTo(activeWi, effDow, srcWi, srcDow);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -496,7 +564,19 @@ export default function PlanEditor() {
|
||||
onTitleBlur={() => setTitleTouched(true)}
|
||||
titleError={titleError}
|
||||
weeksCount={editor.weeksCount}
|
||||
onWeeksCountChange={editor.setWeeksCount}
|
||||
onWeeksCountChange={(n) => {
|
||||
// Skrócenie planu, który usunęłoby tygodnie z dniami z historią —
|
||||
// potwierdzenie + forceRemoveDays (soft-remove, historia zostaje).
|
||||
if (
|
||||
isPlanActive &&
|
||||
n < editor.weeks.length &&
|
||||
editor.weeks.slice(n).some((w) => w.days.some((d) => d.hasHistory))
|
||||
) {
|
||||
setShrinkReq({ n });
|
||||
} else {
|
||||
editor.setWeeksCount(n);
|
||||
}
|
||||
}}
|
||||
gymOptions={gymOptions}
|
||||
gymId={editor.gymId}
|
||||
onGymIdChange={editor.setGymId}
|
||||
@@ -569,7 +649,15 @@ export default function PlanEditor() {
|
||||
customName={week.customName}
|
||||
onCustomNameChange={(v) => editor.setWeekAlias(activeWi, v)}
|
||||
copySources={copySources}
|
||||
onCopyFrom={(srcWi) => editor.copyFromWeek(activeWi, srcWi)}
|
||||
onCopyFrom={(srcWi) => {
|
||||
// Podmiana dni tygodnia z historią (aktywny plan) — stare wiersze
|
||||
// znikają z planu: potwierdzenie + forceRemoveDays.
|
||||
if (isPlanActive && weekDays.some((d) => d.hasHistory)) {
|
||||
setCopyWeekReq({ srcWi });
|
||||
} else {
|
||||
editor.copyFromWeek(activeWi, srcWi);
|
||||
}
|
||||
}}
|
||||
canClear={weekDays.length > 0 || !week.detached}
|
||||
onClear={() => setClearWeekIdx(activeWi)}
|
||||
>
|
||||
@@ -608,6 +696,11 @@ export default function PlanEditor() {
|
||||
<>
|
||||
<DayPicker
|
||||
days={weekDays}
|
||||
lockedDows={
|
||||
isPlanActive
|
||||
? new Set(historyDaysOf(activeWi).map((d) => d.dayOfWeek))
|
||||
: undefined
|
||||
}
|
||||
onAddDay={(dow) => {
|
||||
editor.addDay(activeWi, dow);
|
||||
// teraz, gdy dni są podzakładkami — wyląduj na nowo dodanym dniu
|
||||
@@ -615,9 +708,14 @@ export default function PlanEditor() {
|
||||
}}
|
||||
onRemoveDay={(dow) => {
|
||||
const day = weekDays.find((d) => d.dayOfWeek === dow);
|
||||
// dzień z ćwiczeniami: potwierdzenie (tap na mobile nie może być destrukcyjny)
|
||||
if (day && day.exercises.length > 0) setRemoveDayReq({ wi: activeWi, dow });
|
||||
else editor.removeDay(activeWi, dow);
|
||||
if (!day) return;
|
||||
// dzień z historią (aktywny plan): świadome potwierdzenie + forceRemoveDays
|
||||
if (isPlanActive && day.hasHistory) {
|
||||
setRemoveLockedReq({ wi: activeWi, dow });
|
||||
} else if (day.exercises.length > 0) {
|
||||
// dzień z ćwiczeniami: potwierdzenie (tap na mobile nie może być destrukcyjny)
|
||||
setRemoveDayReq({ wi: activeWi, dow });
|
||||
} else editor.removeDay(activeWi, dow);
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -640,6 +738,19 @@ export default function PlanEditor() {
|
||||
przy ≥2 dniach, ruch zapętlony po dniach treningowych), licznik
|
||||
ćwiczeń zawsze przy prawej krawędzi */}
|
||||
<div className="mt-3 flex items-center justify-between gap-3">
|
||||
{/* Kopiowanie pojedynczego dnia (ten sam dzień tygodnia w innym
|
||||
tygodniu lub inny dzień tygodnia) — wybór źródła w modalu */}
|
||||
{dayCopySources.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('wizard.copyDayFrom')}
|
||||
title={t('wizard.copyDayFrom')}
|
||||
onClick={() => setDayCopyOpen(true)}
|
||||
className={cn(DAY_ARROW, 'shrink-0')}
|
||||
>
|
||||
<Copy className="h-5 w-5" />
|
||||
</button>
|
||||
)}
|
||||
{/* Przy jednym dniu strzałek nie ma, ale ich miejsce zostaje —
|
||||
nazwa dnia zawsze w tym samym punkcie układu */}
|
||||
<div className="flex min-w-0 items-center gap-1">
|
||||
@@ -671,6 +782,12 @@ export default function PlanEditor() {
|
||||
<span aria-hidden="true" className="h-10 w-10 shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
{isPlanActive && activeDay.hasHistory && (
|
||||
<Badge className="shrink-0" color="yellow">
|
||||
<History className="h-3 w-3" />
|
||||
{t('wizard.historyBadge')}
|
||||
</Badge>
|
||||
)}
|
||||
<Badge
|
||||
className="ml-auto shrink-0"
|
||||
color={activeDay.exercises.length > 0 ? 'green' : 'gray'}
|
||||
@@ -719,6 +836,34 @@ export default function PlanEditor() {
|
||||
</>
|
||||
)}
|
||||
</WeekPanel>
|
||||
|
||||
{dayCopyOpen && dayCopySources.length > 0 && effDow != null && (
|
||||
<Modal
|
||||
open
|
||||
onClose={() => setDayCopyOpen(false)}
|
||||
title={t('wizard.dayCopyTitle', { day: dayName(effDow) })}
|
||||
handle
|
||||
>
|
||||
<p className="mb-3 text-dim text-[0.875rem]">{t('wizard.dayCopyDesc')}</p>
|
||||
<div className="flex flex-col gap-1">
|
||||
{dayCopySources.map((s) => (
|
||||
<button
|
||||
key={`${s.wi}:${s.dow}`}
|
||||
type="button"
|
||||
aria-label={t('wizard.dayCopyLabel', { label: s.label })}
|
||||
onClick={() => {
|
||||
applyDayCopy(s.wi, s.dow);
|
||||
setDayCopyOpen(false);
|
||||
}}
|
||||
className="flex cursor-pointer items-center justify-between gap-3 rounded-[10px] px-3 py-2.5 text-left text-[0.95rem] font-semibold transition-colors hover:bg-line/30"
|
||||
>
|
||||
<span>{s.label}</span>
|
||||
<span className="shrink-0 text-dim text-[0.8rem]">{s.summary}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
@@ -748,11 +893,18 @@ export default function PlanEditor() {
|
||||
open={clearWeekIdx !== null}
|
||||
onClose={() => setClearWeekIdx(null)}
|
||||
onConfirm={() => {
|
||||
if (clearWeekIdx !== null) editor.clearWeek(clearWeekIdx);
|
||||
if (clearWeekIdx !== null) {
|
||||
if (isPlanActive && historyDaysOf(clearWeekIdx).length > 0) setForceRemoveDays(true);
|
||||
editor.clearWeek(clearWeekIdx);
|
||||
}
|
||||
setClearWeekIdx(null);
|
||||
}}
|
||||
title={t('wizard.clearWeekTitle', { n: (clearWeekIdx ?? 0) + 1 })}
|
||||
description={t('wizard.clearWeekDesc')}
|
||||
description={
|
||||
clearWeekIdx !== null && isPlanActive && historyDaysOf(clearWeekIdx).length > 0
|
||||
? t('wizard.clearWeekHistoryNote', { count: historyDaysOf(clearWeekIdx).length })
|
||||
: t('wizard.clearWeekDesc')
|
||||
}
|
||||
confirmLabel={t('wizard.clearWeekLabel')}
|
||||
danger
|
||||
/>
|
||||
@@ -780,6 +932,70 @@ export default function PlanEditor() {
|
||||
confirmLabel={t('wizard.removeDayLabel')}
|
||||
danger
|
||||
/>
|
||||
<ConfirmDialog
|
||||
open={removeLockedReq !== null}
|
||||
onClose={() => setRemoveLockedReq(null)}
|
||||
onConfirm={() => {
|
||||
if (removeLockedReq) {
|
||||
editor.removeDay(removeLockedReq.wi, removeLockedReq.dow);
|
||||
setForceRemoveDays(true);
|
||||
}
|
||||
setRemoveLockedReq(null);
|
||||
}}
|
||||
title={t('wizard.removeLockedTitle')}
|
||||
description={t('wizard.removeLockedDesc', {
|
||||
day: removeLockedReq ? dayName(removeLockedReq.dow).toLowerCase() : '',
|
||||
})}
|
||||
confirmLabel={t('wizard.removeLockedLabel')}
|
||||
danger
|
||||
/>
|
||||
<ConfirmDialog
|
||||
open={copyWeekReq !== null}
|
||||
onClose={() => setCopyWeekReq(null)}
|
||||
onConfirm={() => {
|
||||
if (copyWeekReq) {
|
||||
editor.copyFromWeek(activeWi, copyWeekReq.srcWi);
|
||||
setForceRemoveDays(true);
|
||||
}
|
||||
setCopyWeekReq(null);
|
||||
}}
|
||||
title={t('wizard.copyWeekLockedTitle')}
|
||||
description={t('wizard.copyWeekLockedDesc')}
|
||||
confirmLabel={t('wizard.copyWeekLockedLabel')}
|
||||
danger
|
||||
/>
|
||||
<ConfirmDialog
|
||||
open={dayCopyReq !== null}
|
||||
onClose={() => setDayCopyReq(null)}
|
||||
onConfirm={() => {
|
||||
if (dayCopyReq) {
|
||||
editor.copyDayTo(activeWi, dayCopyReq.targetDow, dayCopyReq.srcWi, dayCopyReq.srcDow);
|
||||
setForceRemoveDays(true);
|
||||
}
|
||||
setDayCopyReq(null);
|
||||
}}
|
||||
title={t('wizard.dayCopyLockedTitle')}
|
||||
description={t('wizard.dayCopyLockedDesc', {
|
||||
day: dayCopyReq ? dayName(dayCopyReq.targetDow).toLowerCase() : '',
|
||||
})}
|
||||
confirmLabel={t('wizard.dayCopyLockedLabel')}
|
||||
danger
|
||||
/>
|
||||
<ConfirmDialog
|
||||
open={shrinkReq !== null}
|
||||
onClose={() => setShrinkReq(null)}
|
||||
onConfirm={() => {
|
||||
if (shrinkReq) {
|
||||
editor.setWeeksCount(shrinkReq.n);
|
||||
setForceRemoveDays(true);
|
||||
}
|
||||
setShrinkReq(null);
|
||||
}}
|
||||
title={t('wizard.shrinkWeeksLockedTitle')}
|
||||
description={t('wizard.shrinkWeeksLockedDesc')}
|
||||
confirmLabel={t('wizard.shrinkWeeksLockedLabel')}
|
||||
danger
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Lock } from 'lucide-react';
|
||||
import { dayName } from '../../../lib/format';
|
||||
import type { EditorDay } from './types';
|
||||
|
||||
/* Wybór dni treningowych tygodnia: siatka 7 dni (touch targety 44px, aria-label
|
||||
z pełną nazwą dnia). Pomarańczowy = dzień treningowy, kropka = dzień z ćwiczeniami.
|
||||
Kłódka = dzień z historią treningową (w aktywnym planie: usunięcie wymaga
|
||||
świadomej zgody, historia zostaje).
|
||||
Dzień edytowany przełącza stepper „« dzień »” (PlanEditor) — bez dublowania nazw. */
|
||||
export function DayPicker({
|
||||
days,
|
||||
lockedDows,
|
||||
onAddDay,
|
||||
onRemoveDay,
|
||||
}: {
|
||||
days: EditorDay[];
|
||||
/** Dni z historią treningową — sygnalizowane kłódką. */
|
||||
lockedDows?: Set<number>;
|
||||
onAddDay: (dow: number) => void;
|
||||
onRemoveDay: (dow: number) => void;
|
||||
}) {
|
||||
@@ -20,12 +26,13 @@ export function DayPicker({
|
||||
{[1, 2, 3, 4, 5, 6, 7].map((dow) => {
|
||||
const day = days.find((d) => d.dayOfWeek === dow);
|
||||
const selected = !!day;
|
||||
const locked = selected && !!lockedDows?.has(dow);
|
||||
return (
|
||||
<button
|
||||
key={dow}
|
||||
type="button"
|
||||
aria-pressed={selected}
|
||||
aria-label={dayName(dow)}
|
||||
aria-label={locked ? `${dayName(dow)} — ${t('editor.dayHistoryAria')}` : dayName(dow)}
|
||||
onClick={() => (selected ? onRemoveDay(dow) : onAddDay(dow))}
|
||||
className={`relative min-h-11 rounded-[10px] text-[0.8rem] font-semibold border transition-colors cursor-pointer ${
|
||||
selected
|
||||
@@ -34,6 +41,12 @@ export function DayPicker({
|
||||
}`}
|
||||
>
|
||||
{dayName(dow).slice(0, 3)}
|
||||
{locked && (
|
||||
<Lock
|
||||
aria-hidden="true"
|
||||
className="absolute top-1 right-1 h-3 w-3 text-accent-ink/80"
|
||||
/>
|
||||
)}
|
||||
{selected && (day?.exercises.length ?? 0) > 0 && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { KeyboardEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus, Search } from 'lucide-react';
|
||||
import { Button, Input, Modal } from '../../../components/ui';
|
||||
import { fmtLoadKg } from '../../../lib/format';
|
||||
import { localizedName } from '../../../lib/localizedName';
|
||||
import { MUSCLE_IDS, muscleName } from '../../../lib/labels';
|
||||
import { cn } from '../../../lib/utils';
|
||||
@@ -14,7 +15,7 @@ function latestHint(latest: LatestExerciseResult | undefined, prefix: string): s
|
||||
const s = latest.sets[0];
|
||||
if (s.reps == null && s.loadKg == null) return null;
|
||||
const reps = s.reps != null ? String(s.reps) : '?';
|
||||
const load = s.loadKg != null ? ` @ ${s.loadKg} kg` : '';
|
||||
const load = s.loadKg != null ? ` @ ${fmtLoadKg(s.loadKg)} kg` : '';
|
||||
return `${prefix} ${reps}${load}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
YAxis,
|
||||
} from 'recharts';
|
||||
import { Button } from '../../../components/ui';
|
||||
import { fmtDate } from '../../../lib/format';
|
||||
import { fmtDate, fmtLoadKg } from '../../../lib/format';
|
||||
import type { ExerciseProgressPoint, LatestExerciseResult } from '../../../api/types';
|
||||
|
||||
const TOOLTIP_STYLE = {
|
||||
@@ -82,7 +82,7 @@ export function ExerciseResultsPanel({
|
||||
className="rounded-[10px] border border-line bg-input px-2 py-1 text-[0.875rem]"
|
||||
>
|
||||
{s.reps ?? '?'} {t('exec.repsUnit')}
|
||||
{s.loadKg != null ? ` @ ${s.loadKg} kg` : ''}
|
||||
{s.loadKg != null ? ` @ ${fmtLoadKg(s.loadKg)} kg` : ''}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -17,6 +17,12 @@ export interface EditorDay {
|
||||
id?: string;
|
||||
dayOfWeek: number;
|
||||
exercises: EditorExercise[];
|
||||
/**
|
||||
* Dzień ma historię treningową (status COMPLETED/SKIPPED albo jakakolwiek sesja).
|
||||
* Ustawiane tylko przy wczytaniu planu; w aktywnym planie taki dzień przy
|
||||
* usunięciu jest soft-remove (historia zostaje) — wymaga świadomego potwierdzenia.
|
||||
*/
|
||||
hasHistory?: boolean;
|
||||
}
|
||||
|
||||
export interface EditorWeek {
|
||||
@@ -52,6 +58,8 @@ export function withoutIds(days: EditorDay[]): EditorDay[] {
|
||||
return days.map((d) => ({
|
||||
...d,
|
||||
id: undefined,
|
||||
// kopia jest nowym wierszem — historia należy do wiersza źródłowego
|
||||
hasHistory: undefined,
|
||||
exercises: d.exercises.map((e) => ({
|
||||
...e,
|
||||
id: undefined,
|
||||
@@ -66,6 +74,8 @@ export function weekFromApi(week: {
|
||||
days: {
|
||||
id?: string;
|
||||
dayOfWeek: number;
|
||||
status?: string;
|
||||
sessions?: { id: string }[];
|
||||
exercises: {
|
||||
id?: string;
|
||||
exerciseId: string;
|
||||
@@ -84,13 +94,14 @@ export function weekFromApi(week: {
|
||||
days: week.days.map((d) => ({
|
||||
id: d.id,
|
||||
dayOfWeek: d.dayOfWeek,
|
||||
hasHistory: (d.status != null && d.status !== 'PLANNED') || (d.sessions?.length ?? 0) > 0,
|
||||
exercises: d.exercises.map((e) => ({
|
||||
id: e.id,
|
||||
exerciseId: e.exerciseId,
|
||||
sets: e.sets.map((s) => ({
|
||||
id: s.id,
|
||||
reps: s.reps?.toString() ?? '',
|
||||
loadKg: s.loadKg?.toString() ?? '',
|
||||
loadKg: s.loadKg != null ? String(s.loadKg).replace('.', ',') : '',
|
||||
restSec: s.restSec?.toString() ?? '',
|
||||
rir: s.rir?.toString() ?? '',
|
||||
})),
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { useCallback, useMemo, useRef, useState } from 'react';
|
||||
import type { LatestExerciseResult } from '../../../api/types';
|
||||
import { sanitizeLoadInput } from '../../../lib/format';
|
||||
import {
|
||||
DEFAULT_SET,
|
||||
displayedDaysOf,
|
||||
emptyWeek,
|
||||
weekFromApi,
|
||||
withoutIds,
|
||||
type EditorDay,
|
||||
type EditorSet,
|
||||
type EditorWeek,
|
||||
} from './types';
|
||||
@@ -152,8 +154,9 @@ export function usePlanEditorState() {
|
||||
);
|
||||
|
||||
const setSetField = useCallback(
|
||||
(wi: number, di: number, ei: number, si: number, field: keyof EditorSet, value: string) =>
|
||||
editWeek(wi, (w) => ({
|
||||
(wi: number, di: number, ei: number, si: number, field: keyof EditorSet, value: string) => {
|
||||
const v = field === 'loadKg' ? sanitizeLoadInput(value) : value;
|
||||
return editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) =>
|
||||
idx === di
|
||||
? {
|
||||
@@ -162,14 +165,15 @@ export function usePlanEditorState() {
|
||||
x === ei
|
||||
? {
|
||||
...ex,
|
||||
sets: ex.sets.map((s, y) => (y === si ? { ...s, [field]: value } : s)),
|
||||
sets: ex.sets.map((s, y) => (y === si ? { ...s, [field]: v } : s)),
|
||||
}
|
||||
: ex,
|
||||
),
|
||||
}
|
||||
: d,
|
||||
),
|
||||
})),
|
||||
}));
|
||||
},
|
||||
[editWeek],
|
||||
);
|
||||
|
||||
@@ -268,7 +272,10 @@ export function usePlanEditorState() {
|
||||
sets: latest.sets.map((ls) => ({
|
||||
...DEFAULT_SET,
|
||||
reps: ls.reps != null ? String(ls.reps) : DEFAULT_SET.reps,
|
||||
loadKg: ls.loadKg != null ? String(ls.loadKg) : DEFAULT_SET.loadKg,
|
||||
loadKg:
|
||||
ls.loadKg != null
|
||||
? String(ls.loadKg).replace('.', ',')
|
||||
: DEFAULT_SET.loadKg,
|
||||
})),
|
||||
}
|
||||
: ex,
|
||||
@@ -298,22 +305,44 @@ export function usePlanEditorState() {
|
||||
});
|
||||
}, []);
|
||||
|
||||
/** Jawne odłączenie lustrzanego tygodnia: kopia dni z tygodnia 1 + `detached`.
|
||||
Tydzień 1 i już odłączone — bez zmian (bezpieczne nb. auto-detach w `editWeek`). */
|
||||
const detachWeek = useCallback((wi: number) => {
|
||||
setWeeks((ws) =>
|
||||
ws.map((w, i) =>
|
||||
i === wi && i > 0 && !w.detached
|
||||
? {
|
||||
days: withoutIds(structuredClone(ws[0].days)),
|
||||
detached: true,
|
||||
customName: w.customName,
|
||||
}
|
||||
: w,
|
||||
),
|
||||
);
|
||||
/** Kopiowanie zawartości pojedynczego dnia (stepper „Kopiuj dzień z…”): bieżący dzień
|
||||
tygodnia `wi` przejmuje ćwiczenia i serie dnia `srcDow` z tygodnia `srcWi`
|
||||
(źródło lustrzane rozwiązane przez `displayedDaysOf`), zostając pod swoim
|
||||
`targetDow`; kopia bez id wierszy, tydzień docelowy odłączony. */
|
||||
const copyDayTo = useCallback((wi: number, targetDow: number, srcWi: number, srcDow: number) => {
|
||||
setWeeks((ws) => {
|
||||
if (!ws[wi] || !ws[srcWi]) return ws;
|
||||
if (wi === srcWi && targetDow === srcDow) return ws;
|
||||
const src = displayedDaysOf(ws, srcWi).find((d) => d.dayOfWeek === srcDow);
|
||||
if (!src) return ws;
|
||||
const clone: EditorDay = withoutIds([structuredClone(src)])[0];
|
||||
clone.dayOfWeek = targetDow;
|
||||
return ws.map((w, i) => {
|
||||
if (i !== wi) return w;
|
||||
const days: EditorDay[] = w.days.filter((d) => d.dayOfWeek !== targetDow);
|
||||
days.push(clone);
|
||||
days.sort((a, b) => a.dayOfWeek - b.dayOfWeek);
|
||||
return { days, detached: true, customName: w.customName };
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
/** Jawne odłączenie lustrzanego tygodnia: kopia dni z tygodnia 1 + `detached`.
|
||||
Tydzień 1 i już odłączone — bez zmian (bezpieczne nb. auto-detach w `editWeek`). */ const detachWeek =
|
||||
useCallback((wi: number) => {
|
||||
setWeeks((ws) =>
|
||||
ws.map((w, i) =>
|
||||
i === wi && i > 0 && !w.detached
|
||||
? {
|
||||
days: withoutIds(structuredClone(ws[0].days)),
|
||||
detached: true,
|
||||
customName: w.customName,
|
||||
}
|
||||
: w,
|
||||
),
|
||||
);
|
||||
}, []);
|
||||
|
||||
const clearWeek = useCallback(
|
||||
(wi: number) =>
|
||||
setWeeks((ws) => ws.map((w, i) => (i === wi ? { ...w, days: [], detached: true } : w))),
|
||||
@@ -351,6 +380,7 @@ export function usePlanEditorState() {
|
||||
removeSet,
|
||||
prefillExercise,
|
||||
copyFromWeek,
|
||||
copyDayTo,
|
||||
detachWeek,
|
||||
clearWeek,
|
||||
};
|
||||
|
||||
@@ -502,6 +502,31 @@ describe('PlanEditor — data startu i menu kontekstowe', () => {
|
||||
expect(screen.getByText('Przysiady')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('krok 2: „Kopiuj dzień z…” podmienia bieżący dzień treścią innego dnia tygodnia', async () => {
|
||||
mockApi({});
|
||||
const user = userEvent.setup();
|
||||
renderApp();
|
||||
await loginAndOpenNewPlan(user);
|
||||
|
||||
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan');
|
||||
await user.click(screen.getByRole('button', { name: 'Dalej' }));
|
||||
// tydzień 1: Poniedziałek + Przysiady, Środa + Wyciskanie
|
||||
await user.click(screen.getByRole('button', { name: 'Poniedziałek' }));
|
||||
await user.click(screen.getByRole('button', { name: 'dodaj ćwiczenie…' }));
|
||||
await user.click(await screen.findByRole('option', { name: /Przysiady/ }));
|
||||
await user.click(screen.getByRole('button', { name: 'Środa' }));
|
||||
await user.click(screen.getByRole('button', { name: 'dodaj ćwiczenie…' }));
|
||||
await user.click(await screen.findByRole('option', { name: /Wyciskanie/ }));
|
||||
|
||||
// bieżący dzień (Środa) przejmuje zawartość Poniedziałku
|
||||
await user.click(screen.getByRole('button', { name: 'Kopiuj dzień z…' }));
|
||||
expect(screen.getByRole('button', { name: 'Kopiuj: Poniedziałek' })).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Kopiuj: Poniedziałek' }));
|
||||
expect(screen.getByText('Przysiady')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Wyciskanie na wyciągu')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('1 ćwiczenie')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('pokazuje „Wstecz” w treści formularza na /plans/new', async () => {
|
||||
mockApi({});
|
||||
const user = userEvent.setup();
|
||||
@@ -627,7 +652,9 @@ async function loginAndOpenEditor(user: userEvent.User) {
|
||||
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
|
||||
expect(await screen.findByRole('heading', { name: 'Plan w trakcie' })).toBeInTheDocument();
|
||||
// akcja „Edytuj” w topmenu (PlanDetail) prowadzi do edytora
|
||||
await user.click(within(document.querySelector('header')!).getByRole('button', { name: 'Edytuj' }));
|
||||
await user.click(
|
||||
within(document.querySelector('header')!).getByRole('button', { name: 'Edytuj' }),
|
||||
);
|
||||
}
|
||||
|
||||
describe('PlanEditor — edycja aktywnego planu (notatka + id wierszy)', () => {
|
||||
@@ -642,7 +669,9 @@ describe('PlanEditor — edycja aktywnego planu (notatka + id wierszy)', () => {
|
||||
|
||||
// krok 1 aktywnego planu: brak wyboru tygodnia startu, jest notatka o zmianach
|
||||
expect(screen.queryByRole('group', { name: 'Wybór tygodnia startu' })).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Plan jest realizowany — data startu jest niezmienna.')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('Plan jest realizowany — data startu jest niezmienna.'),
|
||||
).toBeInTheDocument();
|
||||
const noteField = screen
|
||||
.getByText('Notatka o zmianach')
|
||||
.closest('[data-slot="field"]') as HTMLElement;
|
||||
@@ -677,7 +706,52 @@ describe('PlanEditor — edycja aktywnego planu (notatka + id wierszy)', () => {
|
||||
expect(day.id).toBe('td-1');
|
||||
const exercise = (day.exercises as Record<string, unknown>[])[0];
|
||||
expect(exercise.id).toBe('tpe-1');
|
||||
expect((exercise.sets as Record<string, unknown>[])[0]).toMatchObject({ id: 'tps-1', reps: 12 });
|
||||
expect((exercise.sets as Record<string, unknown>[])[0]).toMatchObject({
|
||||
id: 'tps-1',
|
||||
reps: 12,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('PlanEditor — dzień z historią w aktywnym planie', () => {
|
||||
it('usunięcie dnia z historią: potwierdzenie „Usuń mimo historii”, zapis = PATCH z forceRemoveDays', async () => {
|
||||
const capture: Capture = {};
|
||||
const plan = activePlan();
|
||||
const day = (plan.weeks as Record<string, unknown>[])[0].days as Record<string, unknown>[];
|
||||
day[0].status = 'COMPLETED';
|
||||
day[0].sessions = [{ id: 'ts-1', status: 'COMPLETED', startedAt: '2026-08-24T10:00:00.000Z' }];
|
||||
mockEditApi(capture, plan);
|
||||
const user = userEvent.setup();
|
||||
renderApp();
|
||||
await loginAndOpenEditor(user);
|
||||
expect(await screen.findByRole('heading', { name: 'Edycja planu' })).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Dalej' }));
|
||||
// dzień z historią: kłódka w a11y + badge „Historia” w stepperze dnia
|
||||
const lockedDay = await screen.findByRole('button', {
|
||||
name: 'Poniedziałek — dzień z historią treningów',
|
||||
});
|
||||
expect(screen.getByText('Historia')).toBeInTheDocument();
|
||||
|
||||
await user.click(lockedDay);
|
||||
expect(
|
||||
await screen.findByRole('heading', { name: 'Usunąć dzień z historią?' }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText(/historia treningowa zostanie zachowana/)).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Usuń mimo historii' }));
|
||||
|
||||
// zapis bez notatki = powrót na krok 1; tam uzupełniamy notatkę audytową i zapisujemy
|
||||
await user.click(screen.getByRole('button', { name: 'Zapisz zmiany' }));
|
||||
expect((await screen.findAllByText(/wpisz notatkę o zmianach/)).length).toBeGreaterThan(0);
|
||||
const noteField = screen
|
||||
.getByText('Notatka o zmianach')
|
||||
.closest('[data-slot="field"]') as HTMLElement;
|
||||
await user.type(within(noteField).getByRole('textbox'), 'Zmiana po konsultacji z trenerem');
|
||||
await user.click(screen.getByRole('button', { name: 'Zapisz zmiany' }));
|
||||
await waitFor(() => expect(capture.patchPlanBody).toBeDefined());
|
||||
expect(capture.patchPlanBody).toMatchObject({ forceRemoveDays: true });
|
||||
const weeks = capture.patchPlanBody!.weeks as Record<string, unknown>[];
|
||||
expect((weeks[0].days as unknown[]).length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -689,7 +763,10 @@ describe('PlanEditor — dzień bez ćwiczeń blokuje zapis', () => {
|
||||
renderApp();
|
||||
await loginAndOpenNewPlan(user);
|
||||
|
||||
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan pusty dzień');
|
||||
await user.type(
|
||||
screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'),
|
||||
'Plan pusty dzień',
|
||||
);
|
||||
await user.click(screen.getByRole('button', { name: 'Dalej' }));
|
||||
// dzień treningowy bez ćwiczeń (klik w siatce dni = dzień z 0 ćwiczeń)
|
||||
await user.click(screen.getByRole('button', { name: 'Poniedziałek' }));
|
||||
|
||||
@@ -144,6 +144,37 @@ test('kopiowanie dni z dowolnego tygodnia („Kopiuj z…”)', async ({ page })
|
||||
await expect(page.getByText('Przysiady')).toBeVisible();
|
||||
});
|
||||
|
||||
test('kopiowanie zawartości dnia („Kopiuj dzień z…")', async ({ page }) => {
|
||||
mockPlans(page);
|
||||
await login(page);
|
||||
|
||||
await page.getByRole('link', { name: 'Plany treningowe' }).click();
|
||||
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
|
||||
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan');
|
||||
await page.getByRole('button', { name: 'Dalej' }).click();
|
||||
|
||||
// tydzień 1: Poniedziałek + Przysiady; następnie pusty Środa (edytowany dzień)
|
||||
await page.getByRole('button', { name: 'Pon' }).click();
|
||||
await page.getByRole('button', { name: 'dodaj ćwiczenie…' }).click();
|
||||
await page.getByRole('option', { name: /Przysiady/ }).click();
|
||||
await page.getByRole('button', { name: 'Śr' }).click();
|
||||
await expect(page.getByText('Przysiady')).toHaveCount(0);
|
||||
|
||||
// modal źródeł: poniedziałek tygodnia 1 + lustrzane tygodnie pokazujące jego treści
|
||||
await page.getByRole('button', { name: 'Kopiuj dzień z…' }).click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog.getByRole('button', { name: /^Kopiuj: Poniedziałek$/ })).toBeVisible();
|
||||
await expect(
|
||||
dialog.getByRole('button', { name: /^Kopiuj: Tydzień 2 — Poniedziałek$/ }),
|
||||
).toBeVisible();
|
||||
await dialog.getByRole('button', { name: /^Kopiuj: Poniedziałek$/ }).click();
|
||||
|
||||
// Środa przejęła ćwiczenia Poniedziałku, a Poniedziałek został nietknięty
|
||||
await expect(page.getByText('Przysiady')).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Pon' }).click();
|
||||
await expect(page.getByText('Przysiady')).toBeVisible();
|
||||
});
|
||||
|
||||
test('zmiana kolejności ćwiczeń i stepper serii', async ({ page }) => {
|
||||
mockPlans(page);
|
||||
await login(page);
|
||||
@@ -181,3 +212,31 @@ test('zmiana kolejności ćwiczeń i stepper serii', async ({ page }) => {
|
||||
await page.getByRole('button', { name: 'Usuń ostatnią serię' }).first().click();
|
||||
await expect(page.getByRole('textbox', { name: 'Seria 2: Powt.' })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('obciążenie po przecinku: kropka normalizowana, znaki obce odrzucane, zapis przechodzi', async ({
|
||||
page,
|
||||
}) => {
|
||||
mockPlans(page);
|
||||
await login(page);
|
||||
|
||||
await page.getByRole('link', { name: 'Plany treningowe' }).click();
|
||||
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
|
||||
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan');
|
||||
await page.getByRole('button', { name: 'Dalej' }).click();
|
||||
await page.getByRole('button', { name: 'Pon' }).click();
|
||||
await page.getByRole('button', { name: 'dodaj ćwiczenie…' }).click();
|
||||
await page.getByRole('option', { name: /Przysiady/ }).click();
|
||||
|
||||
const load = page.getByRole('textbox', { name: 'Seria 1: Obciążenie' });
|
||||
await load.fill('62,5');
|
||||
await expect(load).toHaveValue('62,5');
|
||||
await load.fill('62.5');
|
||||
await expect(load).toHaveValue('62,5');
|
||||
await load.fill('a62x,555!');
|
||||
await expect(load).toHaveValue('62,55');
|
||||
|
||||
// zapis akceptowany (do API leci 62.55 jako number)
|
||||
await page.getByRole('button', { name: 'Dalej' }).click();
|
||||
await page.getByRole('button', { name: 'Zapisz' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Plan', exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -113,6 +113,44 @@ describe('usePlanEditorState — akcje mutacji', () => {
|
||||
expect(result.current.weeks).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('copyDayTo podmienia bieżący dzień treścią dnia z innego dnia/tygodnia (kopia bez id)', () => {
|
||||
const { result } = renderHook(() => usePlanEditorState());
|
||||
act(() => result.current.addDay(0, 1));
|
||||
act(() => result.current.addExercise(0, 0, 'ex-1'));
|
||||
act(() => result.current.addDay(0, 3));
|
||||
act(() => result.current.addExercise(0, 1, 'ex-2'));
|
||||
act(() => result.current.addDay(0, 5));
|
||||
|
||||
// Piątek przejmuje zawartość Środy — dzień zostaje pod Piątkiem
|
||||
act(() => result.current.copyDayTo(0, 5, 0, 3));
|
||||
const fri = result.current.weeks[0].days.find((d) => d.dayOfWeek === 5);
|
||||
expect(fri?.exercises.map((e) => e.exerciseId)).toEqual(['ex-2']);
|
||||
expect(result.current.weeks[0].days.map((d) => d.dayOfWeek)).toEqual([1, 3, 5]);
|
||||
|
||||
// źródło lustrzane: tydzień 2 (mirror) rozwiązuje się do tygodnia 1; cel się odłącza
|
||||
act(() => result.current.copyDayTo(2, 7, 1, 1));
|
||||
expect(result.current.weeks[2].detached).toBe(true);
|
||||
const sun = result.current.weeks[2].days.find((d) => d.dayOfWeek === 7);
|
||||
expect(sun?.exercises.map((e) => e.exerciseId)).toEqual(['ex-1']);
|
||||
|
||||
// kopiowanie w siebie (ten sam tydzień + ten sam dzień) — bez zmian
|
||||
act(() => result.current.copyDayTo(0, 1, 0, 1));
|
||||
expect(result.current.weeks[0].days).toHaveLength(3);
|
||||
|
||||
// nieistniejące źródło (tydzień 2 po odłączeniu ma tylko Niedzielę) — bez zmian
|
||||
act(() => result.current.copyDayTo(0, 1, 2, 5));
|
||||
expect(
|
||||
result.current.weeks[0].days
|
||||
.find((d) => d.dayOfWeek === 1)
|
||||
?.exercises.map((e) => e.exerciseId),
|
||||
).toEqual(['ex-1']);
|
||||
|
||||
// kopia = nowy wiersz — id wierszy źródła zrzucone
|
||||
const strippedFri = result.current.weeks[0].days.find((d) => d.dayOfWeek === 5);
|
||||
expect(strippedFri?.id).toBeUndefined();
|
||||
expect(strippedFri?.exercises[0].id).toBeUndefined();
|
||||
});
|
||||
|
||||
it('prefillExercise wypełnia serie z ostatniej sesji (brak danych → domyślne)', () => {
|
||||
const { result } = renderHook(() => usePlanEditorState());
|
||||
act(() => result.current.addDay(0, 1));
|
||||
@@ -258,6 +296,11 @@ describe('usePlanEditorState — akcje mutacji', () => {
|
||||
expect(result.current.weeks[1].days[0].exercises[0].id).toBeUndefined();
|
||||
expect(result.current.weeks[1].days[0].exercises[0].sets[0].id).toBeUndefined();
|
||||
|
||||
// „Kopiuj dzień z…” = podmiana dnia nowym wierszem — id celu też zrzucane
|
||||
act(() => result.current.copyDayTo(0, 1, 1, 1));
|
||||
expect(result.current.weeks[0].days[0].id).toBeUndefined();
|
||||
expect(result.current.weeks[0].days[0].exercises[0].sets[0].id).toBeUndefined();
|
||||
|
||||
// rozbudowa liczby tygodni: kopia ostatniego tygodnia tez bez id
|
||||
act(() => result.current.initFromPlan(plan));
|
||||
act(() => result.current.setWeeksCount(3));
|
||||
@@ -275,9 +318,7 @@ describe('usePlanEditorState — akcje mutacji', () => {
|
||||
{
|
||||
id: 'td-1',
|
||||
dayOfWeek: 1,
|
||||
exercises: [
|
||||
{ id: 'tpe-1', exerciseId: 'ex-1', sets: [{ id: 'tps-1', reps: '10' }] },
|
||||
],
|
||||
exercises: [{ id: 'tpe-1', exerciseId: 'ex-1', sets: [{ id: 'tps-1', reps: '10' }] }],
|
||||
},
|
||||
]);
|
||||
expect(stripped[0].id).toBeUndefined();
|
||||
@@ -285,4 +326,38 @@ describe('usePlanEditorState — akcje mutacji', () => {
|
||||
expect(stripped[0].exercises[0].sets[0].id).toBeUndefined();
|
||||
expect(stripped[0].exercises[0].sets[0].reps).toBe('10');
|
||||
});
|
||||
|
||||
it('dzień z historią (status/sesje z API): hasHistory ustawione; kopia tygodnia je gubi', () => {
|
||||
const { result } = renderHook(() => usePlanEditorState());
|
||||
const plan: PlanLike = {
|
||||
title: 't',
|
||||
weeksCount: 2,
|
||||
weeks: [
|
||||
{
|
||||
index: 0,
|
||||
days: [
|
||||
{
|
||||
id: 'td-1',
|
||||
dayOfWeek: 1,
|
||||
status: 'COMPLETED',
|
||||
sessions: [{ id: 'ts-1' }],
|
||||
exercises: [],
|
||||
},
|
||||
{ id: 'td-2', dayOfWeek: 3, status: 'SKIPPED', sessions: [], exercises: [] },
|
||||
{ id: 'td-3', dayOfWeek: 5, status: 'PLANNED', sessions: [], exercises: [] },
|
||||
],
|
||||
},
|
||||
{ index: 1, days: [] },
|
||||
],
|
||||
};
|
||||
act(() => result.current.initFromPlan(plan));
|
||||
expect(result.current.weeks[0].days[0].hasHistory).toBe(true);
|
||||
expect(result.current.weeks[0].days[1].hasHistory).toBe(true);
|
||||
expect(result.current.weeks[0].days[2].hasHistory).toBe(false);
|
||||
|
||||
// kopia dni to nowe wiersze — historia należy do wierszy źródłowych
|
||||
act(() => result.current.copyFromWeek(1, 0));
|
||||
expect(result.current.weeks[1].days[0].id).toBeUndefined();
|
||||
expect(result.current.weeks[1].days[0].hasHistory).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
65
app/test/plan-load-input.test.ts
Normal file
65
app/test/plan-load-input.test.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { sanitizeLoadInput, parseLoadInput } from '../src/lib/format';
|
||||
import { usePlanEditorState } from '../src/pages/plans/plan-editor/usePlanEditorState';
|
||||
|
||||
describe('sanitizeLoadInput', () => {
|
||||
it('dopuszcza przecinek dziesiętny i normalizuje kropkę do przecinka', () => {
|
||||
expect(sanitizeLoadInput('62,5')).toBe('62,5');
|
||||
expect(sanitizeLoadInput('6.5')).toBe('6,5');
|
||||
expect(sanitizeLoadInput('1.25')).toBe('1,25');
|
||||
});
|
||||
|
||||
it('zwija wiele separatorów i ucina miejsca dziesiętne do dwóch', () => {
|
||||
expect(sanitizeLoadInput('6,,5')).toBe('6,5');
|
||||
expect(sanitizeLoadInput('6.5.5,5')).toBe('6,55');
|
||||
expect(sanitizeLoadInput('1,999')).toBe('1,99');
|
||||
});
|
||||
|
||||
it('usuwa znaki niedziesiętne i zera wiodące', () => {
|
||||
expect(sanitizeLoadInput('60 kg')).toBe('60');
|
||||
expect(sanitizeLoadInput('007')).toBe('7');
|
||||
expect(sanitizeLoadInput('abc')).toBe('');
|
||||
expect(sanitizeLoadInput('')).toBe('');
|
||||
});
|
||||
|
||||
it('dopełnia zero przy przecinku wiodącym i ogranicza do limitu API (1000)', () => {
|
||||
expect(sanitizeLoadInput(',5')).toBe('0,5');
|
||||
expect(sanitizeLoadInput('12345')).toBe('1000');
|
||||
expect(sanitizeLoadInput('1000,5')).toBe('1000');
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseLoadInput', () => {
|
||||
it('zwraca liczbę dla wartości z przecinkiem lub kropką', () => {
|
||||
expect(parseLoadInput('62,5')).toBe(62.5);
|
||||
expect(parseLoadInput('60')).toBe(60);
|
||||
expect(parseLoadInput('0,5')).toBe(0.5);
|
||||
});
|
||||
|
||||
it('zwraca null dla pustego, zera i wartości spoza formatu (nigdy NaN)', () => {
|
||||
expect(parseLoadInput('')).toBeNull();
|
||||
expect(parseLoadInput('0')).toBeNull();
|
||||
expect(parseLoadInput('6abc')).toBeNull();
|
||||
expect(parseLoadInput('6,555')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('usePlanEditorState — sanitacja pola obciążenia', () => {
|
||||
it('setSetField przechowuje zawsze poprawną formę liczby, inne pola bez zmian', () => {
|
||||
const { result } = renderHook(() => usePlanEditorState());
|
||||
act(() => result.current.addDay(0, 1));
|
||||
act(() => result.current.addExercise(0, 0, 'ex-1'));
|
||||
const load = () => result.current.weeks[0].days[0].exercises[0].sets[0].loadKg;
|
||||
act(() => result.current.setSetField(0, 0, 0, 0, 'loadKg', '62,5'));
|
||||
expect(load()).toBe('62,5');
|
||||
act(() => result.current.setSetField(0, 0, 0, 0, 'loadKg', '62.5x'));
|
||||
expect(load()).toBe('62,5');
|
||||
act(() => result.current.setSetField(0, 0, 0, 0, 'loadKg', '5abc'));
|
||||
expect(load()).toBe('5');
|
||||
act(() => result.current.setSetField(0, 0, 0, 0, 'loadKg', '9999'));
|
||||
expect(load()).toBe('1000');
|
||||
act(() => result.current.setSetField(0, 0, 0, 0, 'reps', '12'));
|
||||
expect(result.current.weeks[0].days[0].exercises[0].sets[0].reps).toBe('12');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user